feat(libreoffice): add failOnMissingFonts and warn about missing fonts

This commit is contained in:
Julien Neuhart
2026-12-03 09:50:39 +01:00
parent 8295283a25
commit a5f02a867e
9 changed files with 132 additions and 10 deletions

View File

@@ -12,7 +12,7 @@ ARG GOLANG_VERSION=1.27.4
FROM debian:13-slim AS lok-binary-stage FROM debian:13-slim AS lok-binary-stage
# See https://github.com/gotenberg/lok/releases. # See https://github.com/gotenberg/lok/releases.
ARG LOK_VERSION=v0.0.9 ARG LOK_VERSION=v0.0.10
RUN apt-get update -qq \ RUN apt-get update -qq \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends ca-certificates curl \ && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends ca-certificates curl \

View File

@@ -57,6 +57,19 @@ var (
ErrMemoryLimitExceeded = errors.New("LibreOffice exceeded its memory limit") ErrMemoryLimitExceeded = errors.New("LibreOffice exceeded its memory limit")
) )
// MissingFontsError happens when [Options.FailOnMissingFonts] is set and
// LibreOffice drew some of the document's fonts with other fonts, as they are
// not installed.
type MissingFontsError struct {
// Fonts lists the missing font families, sorted.
Fonts []string
}
// Error implements the error interface.
func (e *MissingFontsError) Error() string {
return "missing fonts: " + strings.Join(e.Fonts, ", ")
}
// Api is a module that provides a [Converter] backed by LibreOffice. // Api is a module that provides a [Converter] backed by LibreOffice.
type Api struct { type Api struct {
autoStart bool autoStart bool
@@ -168,6 +181,13 @@ type Options struct {
// were accepted. // were accepted.
ShowTrackedChanges bool ShowTrackedChanges bool
// FailOnMissingFonts fails the conversion with a [MissingFontsError] when
// LibreOffice draws some of the document's fonts with other fonts, as
// they are not installed. When false, the conversion goes on and logs a
// warning. A metric-compatible replacement, such as Carlito for Calibri,
// keeps the layout and does not count.
FailOnMissingFonts bool
// ConvertOooTargetToPdfTarget specifies that the target documents with // ConvertOooTargetToPdfTarget specifies that the target documents with
// .od[tpgs] extension will have that extension changed to .pdf when the // .od[tpgs] extension will have that extension changed to .pdf when the
// link is exported to PDF. The source document remains untouched. // link is exported to PDF. The source document remains untouched.
@@ -341,6 +361,7 @@ func DefaultOptions() Options {
ExportOnlyNotesPages: false, ExportOnlyNotesPages: false,
ExportNotesInMargin: false, ExportNotesInMargin: false,
ShowTrackedChanges: false, ShowTrackedChanges: false,
FailOnMissingFonts: false,
ConvertOooTargetToPdfTarget: false, ConvertOooTargetToPdfTarget: false,
ExportLinksRelativeFsys: false, ExportLinksRelativeFsys: false,
ExportHiddenSlides: false, ExportHiddenSlides: false,
@@ -763,7 +784,8 @@ func libreofficeErrorType(err error) string {
switch { switch {
case errors.Is(err, ErrInvalidPdfFormats), case errors.Is(err, ErrInvalidPdfFormats),
errors.Is(err, ErrLoadFailed), errors.Is(err, ErrLoadFailed),
errors.Is(err, ErrInvalidPassword): errors.Is(err, ErrInvalidPassword),
errors.As(err, new(*MissingFontsError)):
return gotenberg.ErrorTypeInvalidInput return gotenberg.ErrorTypeInvalidInput
case errors.Is(err, ErrMemoryLimitExceeded): case errors.Is(err, ErrMemoryLimitExceeded):
return "libreoffice_memory_limit" return "libreoffice_memory_limit"

View File

@@ -22,6 +22,7 @@ func TestLibreofficeErrorType(t *testing.T) {
{"invalid pdf formats", ErrInvalidPdfFormats, "invalid_input"}, {"invalid pdf formats", ErrInvalidPdfFormats, "invalid_input"},
{"load failed", ErrLoadFailed, "invalid_input"}, {"load failed", ErrLoadFailed, "invalid_input"},
{"invalid password", ErrInvalidPassword, "invalid_input"}, {"invalid password", ErrInvalidPassword, "invalid_input"},
{"missing fonts", fmt.Errorf("supervisor run task: %w", &MissingFontsError{Fonts: []string{"Minion Pro"}}), "invalid_input"},
{"save failed", ErrSaveFailed, "libreoffice_exception"}, {"save failed", ErrSaveFailed, "libreoffice_exception"},
{"crashed", ErrCrashed, "libreoffice_exception"}, {"crashed", ErrCrashed, "libreoffice_exception"},
{"queue size exceeded", gotenberg.ErrMaximumQueueSizeExceeded, "libreoffice_unavailable"}, {"queue size exceeded", gotenberg.ErrMaximumQueueSizeExceeded, "libreoffice_unavailable"},

View File

@@ -137,9 +137,10 @@ type lokRequest struct {
// lokResponse is the answer of lok's long-running mode to a request. // lokResponse is the answer of lok's long-running mode to a request.
type lokResponse struct { type lokResponse struct {
Success bool `json:"success"` Success bool `json:"success"`
Code string `json:"code"` Code string `json:"code"`
Error string `json:"error"` Error string `json:"error"`
FontsMissing []string `json:"fontsMissing"`
} }
// lok's paper formats: unset keeps the document's size, user takes the width // lok's paper formats: unset keeps the document's size, user takes the width
@@ -586,6 +587,16 @@ func (p *libreOfficeProcess) pdf(ctx context.Context, logger *slog.Logger, input
} }
if resp.Success { if resp.Success {
if len(resp.FontsMissing) == 0 {
return nil
}
if options.FailOnMissingFonts {
return &MissingFontsError{Fonts: resp.FontsMissing}
}
logger.WarnContext(ctx, fmt.Sprintf("LibreOffice drew these fonts with other fonts, as they are not installed: %s", strings.Join(resp.FontsMissing, ", ")))
return nil return nil
} }

View File

@@ -2,6 +2,7 @@ package api
import ( import (
"bufio" "bufio"
"bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -10,6 +11,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"slices"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -31,7 +33,7 @@ func TestMain(m *testing.M) {
} }
// fakeLok answers each request according to the input filename: "ok" writes // fakeLok answers each request according to the input filename: "ok" writes
// the output, "badpass", "unreadable", "destroyed" and "panic" fail with lok's // the output, "fonts" writes it and reports missing fonts, "badpass", "unreadable", "destroyed" and "panic" fail with lok's
// codes, "hang" never answers, "hog" allocates until it is killed, and "crash" // codes, "hang" never answers, "hog" allocates until it is killed, and "crash"
// exits. It records its arguments next to its profile. // exits. It records its arguments next to its profile.
func fakeLok() { func fakeLok() {
@@ -64,6 +66,9 @@ func fakeLok() {
case "ok": case "ok":
_ = os.WriteFile(req.OutputPath, line, 0o600) _ = os.WriteFile(req.OutputPath, line, 0o600)
_ = out.Encode(lokResponse{Success: true}) _ = out.Encode(lokResponse{Success: true})
case "fonts":
_ = os.WriteFile(req.OutputPath, line, 0o600)
_ = out.Encode(lokResponse{Success: true, FontsMissing: []string{"Minion Pro", "Zapfino"}})
case "badpass": case "badpass":
_ = out.Encode(lokResponse{Code: lokCodeInvalidPassword, Error: "failed to load document: wrong document password"}) _ = out.Encode(lokResponse{Code: lokCodeInvalidPassword, Error: "failed to load document: wrong document password"})
case "unreadable": case "unreadable":
@@ -321,6 +326,41 @@ func TestLibreOfficeProcess_EnableMacros(t *testing.T) {
} }
} }
// Missing fonts only log a warning, unless FailOnMissingFonts turns them into
// a MissingFontsError.
func TestLibreOfficeProcess_MissingFonts(t *testing.T) {
for _, fail := range []bool{false, true} {
t.Run(fmt.Sprint(fail), func(t *testing.T) {
p := startFakeLok(t)
var logs bytes.Buffer
logger := slog.New(slog.NewTextHandler(&logs, nil))
dir := t.TempDir()
options := DefaultOptions()
options.FailOnMissingFonts = fail
err := p.pdf(context.Background(), logger, filepath.Join(dir, "fonts.docx"), filepath.Join(dir, "out.pdf"), options)
var missing *MissingFontsError
if fail {
if !errors.As(err, &missing) || !slices.Equal(missing.Fonts, []string{"Minion Pro", "Zapfino"}) {
t.Fatalf("pdf = %v, want a MissingFontsError listing Minion Pro and Zapfino", err)
}
return
}
if err != nil {
t.Fatalf("pdf: %v", err)
}
if !strings.Contains(logs.String(), "level=WARN") || !strings.Contains(logs.String(), "Minion Pro, Zapfino") {
t.Errorf("no warning naming the missing fonts:\n%s", logs.String())
}
})
}
}
func TestLibreOfficeProcess_InvalidPdfFormats(t *testing.T) { func TestLibreOfficeProcess_InvalidPdfFormats(t *testing.T) {
p := startFakeLok(t) p := startFakeLok(t)

View File

@@ -3,9 +3,11 @@ package libreoffice
import ( import (
"errors" "errors"
"fmt" "fmt"
"log/slog"
"maps" "maps"
"net/http" "net/http"
"slices" "slices"
"strings"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5"
@@ -62,6 +64,7 @@ func convertRoute(libreOffice libreofficeapi.Converter, processor *pdf.Processor
Bool("exportOnlyNotesPages", &options.ExportOnlyNotesPages). Bool("exportOnlyNotesPages", &options.ExportOnlyNotesPages).
Bool("exportNotesInMargin", &options.ExportNotesInMargin). Bool("exportNotesInMargin", &options.ExportNotesInMargin).
Bool("showTrackedChanges", &options.ShowTrackedChanges). Bool("showTrackedChanges", &options.ShowTrackedChanges).
Bool("failOnMissingFonts", &options.FailOnMissingFonts).
Bool("convertOooTargetToPdfTarget", &options.ConvertOooTargetToPdfTarget). Bool("convertOooTargetToPdfTarget", &options.ConvertOooTargetToPdfTarget).
Bool("exportLinksRelativeFsys", &options.ExportLinksRelativeFsys). Bool("exportLinksRelativeFsys", &options.ExportLinksRelativeFsys).
Bool("exportHiddenSlides", &options.ExportHiddenSlides). Bool("exportHiddenSlides", &options.ExportHiddenSlides).
@@ -176,20 +179,23 @@ func convertRoute(libreOffice libreofficeapi.Converter, processor *pdf.Processor
outputPaths := make([]string, len(inputPaths)) outputPaths := make([]string, len(inputPaths))
for i, inputPath := range inputPaths { for i, inputPath := range inputPaths {
filename := ctx.OriginalFilename(inputPath)
// document.docx -> document.docx.pdf, which names the output, // document.docx -> document.docx.pdf, which names the output,
// or the archive entry, and the parts of a split. // or the archive entry, and the parts of a split.
outputPaths[i] = ctx.GeneratePathFromFilename(ctx.OriginalFilename(inputPath) + ".pdf") outputPaths[i] = ctx.GeneratePathFromFilename(filename + ".pdf")
err = libreOffice.Pdf(ctx, ctx.Log(), inputPath, outputPaths[i], options) // The filename tells which document a warning, such as one
// about missing fonts, is about.
err = libreOffice.Pdf(ctx, ctx.Log().With(slog.String("filename", filename)), inputPath, outputPaths[i], options)
if err != nil { if err != nil {
filename := ctx.OriginalFilename(inputPath)
// Blame the client only when one of its inputs is actually // Blame the client only when one of its inputs is actually
// implicated, since the server is the only remaining // implicated, since the server is the only remaining
// explanation otherwise. A password failure aborts on // explanation otherwise. A password failure aborts on
// import, before the export filter applies any page range. // import, before the export filter applies any page range.
// See https://github.com/gotenberg/gotenberg/issues/1588. // See https://github.com/gotenberg/gotenberg/issues/1588.
var sentinel api.SentinelHttpError var sentinel api.SentinelHttpError
var missingFonts *libreofficeapi.MissingFontsError
switch { switch {
case errors.Is(err, libreofficeapi.ErrInvalidPassword): case errors.Is(err, libreofficeapi.ErrInvalidPassword):
sentinel = api.NewSentinelHttpError(http.StatusBadRequest, fmt.Sprintf("The password for the document '%s' is incorrect. Check the 'password' form field.", filename)) sentinel = api.NewSentinelHttpError(http.StatusBadRequest, fmt.Sprintf("The password for the document '%s' is incorrect. Check the 'password' form field.", filename))
@@ -199,6 +205,8 @@ func convertRoute(libreOffice libreofficeapi.Converter, processor *pdf.Processor
sentinel = api.NewSentinelHttpError(http.StatusBadRequest, fmt.Sprintf("LibreOffice could not read the document '%s'. Ensure the file is not corrupted and that its extension matches its actual format.", filename)) sentinel = api.NewSentinelHttpError(http.StatusBadRequest, fmt.Sprintf("LibreOffice could not read the document '%s'. Ensure the file is not corrupted and that its extension matches its actual format.", filename))
case errors.Is(err, libreofficeapi.ErrSaveFailed) && options.PageRanges != "": case errors.Is(err, libreofficeapi.ErrSaveFailed) && options.PageRanges != "":
sentinel = api.NewSentinelHttpError(http.StatusBadRequest, fmt.Sprintf("LibreOffice could not apply the pages '%s' to the document '%s'. Check the 'nativePages' form field; valid values look like '1-4', '2' or '1,3,5-7'.", options.PageRanges, filename)) sentinel = api.NewSentinelHttpError(http.StatusBadRequest, fmt.Sprintf("LibreOffice could not apply the pages '%s' to the document '%s'. Check the 'nativePages' form field; valid values look like '1-4', '2' or '1,3,5-7'.", options.PageRanges, filename))
case errors.As(err, &missingFonts):
sentinel = api.NewSentinelHttpError(http.StatusConflict, fmt.Sprintf("The document '%s' uses fonts that are not installed: %s. Install them on the server, or remove the 'failOnMissingFonts' form field to convert with replacement fonts.", filename, strings.Join(missingFonts.Fonts, ", ")))
case errors.Is(err, libreofficeapi.ErrMemoryLimitExceeded): case errors.Is(err, libreofficeapi.ErrMemoryLimitExceeded):
// The same document exceeds the limit again: a 4xx // The same document exceeds the limit again: a 4xx
// tells the client not to retry it as is. // tells the client not to retry it as is.

View File

@@ -127,6 +127,14 @@ func TestConvertRoute_FailureStatus(t *testing.T) {
wantStatus: http.StatusBadRequest, wantStatus: http.StatusBadRequest,
wantBody: "LibreOffice could not apply the pages 'foo' to the document 'page_1.docx'. Check the 'nativePages' form field; valid values look like '1-4', '2' or '1,3,5-7'.", wantBody: "LibreOffice could not apply the pages 'foo' to the document 'page_1.docx'. Check the 'nativePages' form field; valid values look like '1-4', '2' or '1,3,5-7'.",
}, },
{
name: "missing fonts",
inputPath: plain,
values: map[string][]string{"failOnMissingFonts": {"true"}},
err: fmt.Errorf("supervisor run task: %w", &libreofficeapi.MissingFontsError{Fonts: []string{"Minion Pro", "Zapfino"}}),
wantStatus: http.StatusConflict,
wantBody: "The document 'page_1.docx' uses fonts that are not installed: Minion Pro, Zapfino. Install them on the server, or remove the 'failOnMissingFonts' form field to convert with replacement fonts.",
},
{ {
name: "nothing implicated, save failed", name: "nothing implicated, save failed",
inputPath: plain, inputPath: plain,

View File

@@ -100,6 +100,36 @@ Feature: /forms/libreoffice/convert
Inserted text. Inserted text.
""" """
Scenario: POST /forms/libreoffice/convert (Missing Fonts)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
| files | testdata/missing_font.docx | file |
Then the response status code should be 200
Then the response header "Content-Type" should be "application/pdf"
Then the Gotenberg container should log the following entries:
| LibreOffice drew these fonts with other fonts, as they are not installed: Gotenberg Missing Font |
| "filename":"missing_font.docx" |
Scenario: POST /forms/libreoffice/convert (Fail On Missing Fonts)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
| files | testdata/missing_font.docx | file |
| failOnMissingFonts | true | field |
Then the response status code should be 409
Then the response header "Content-Type" should be "text/plain; charset=UTF-8"
Then the response body should match string:
"""
The document 'missing_font.docx' uses fonts that are not installed: Gotenberg Missing Font. Install them on the server, or remove the 'failOnMissingFonts' form field to convert with replacement fonts.
"""
Scenario: POST /forms/libreoffice/convert (Fail On Missing Fonts, Fonts Installed)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
| files | testdata/page_1.docx | file |
| failOnMissingFonts | true | field |
Then the response status code should be 200
Then the response header "Content-Type" should be "application/pdf"
Scenario: POST /forms/libreoffice/convert (Many Documents) Scenario: POST /forms/libreoffice/convert (Many Documents)
Given I have a default Gotenberg container Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s): When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
@@ -397,6 +427,7 @@ Feature: /forms/libreoffice/convert
| exportOnlyNotesPages | foo | field | | exportOnlyNotesPages | foo | field |
| exportNotesInMargin | foo | field | | exportNotesInMargin | foo | field |
| showTrackedChanges | foo | field | | showTrackedChanges | foo | field |
| failOnMissingFonts | foo | field |
| convertOooTargetToPdfTarget | foo | field | | convertOooTargetToPdfTarget | foo | field |
| exportLinksRelativeFsys | foo | field | | exportLinksRelativeFsys | foo | field |
| exportHiddenSlides | foo | field | | exportHiddenSlides | foo | field |
@@ -440,6 +471,7 @@ Feature: /forms/libreoffice/convert
form field 'exportOnlyNotesPages' is invalid (got 'foo', want true or false) form field 'exportOnlyNotesPages' is invalid (got 'foo', want true or false)
form field 'exportNotesInMargin' is invalid (got 'foo', want true or false) form field 'exportNotesInMargin' is invalid (got 'foo', want true or false)
form field 'showTrackedChanges' is invalid (got 'foo', want true or false) form field 'showTrackedChanges' is invalid (got 'foo', want true or false)
form field 'failOnMissingFonts' is invalid (got 'foo', want true or false)
form field 'convertOooTargetToPdfTarget' is invalid (got 'foo', want true or false) form field 'convertOooTargetToPdfTarget' is invalid (got 'foo', want true or false)
form field 'exportLinksRelativeFsys' is invalid (got 'foo', want true or false) form field 'exportLinksRelativeFsys' is invalid (got 'foo', want true or false)
form field 'exportHiddenSlides' is invalid (got 'foo', want true or false) form field 'exportHiddenSlides' is invalid (got 'foo', want true or false)

Binary file not shown.