mirror of
https://github.com/gotenberg/gotenberg.git
synced 2026-12-06 16:22:15 +00:00
feat(libreoffice): add failOnMissingFonts and warn about missing fonts
This commit is contained in:
@@ -12,7 +12,7 @@ ARG GOLANG_VERSION=1.27.4
|
||||
FROM debian:13-slim AS lok-binary-stage
|
||||
|
||||
# See https://github.com/gotenberg/lok/releases.
|
||||
ARG LOK_VERSION=v0.0.9
|
||||
ARG LOK_VERSION=v0.0.10
|
||||
|
||||
RUN apt-get update -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends ca-certificates curl \
|
||||
|
||||
@@ -57,6 +57,19 @@ var (
|
||||
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.
|
||||
type Api struct {
|
||||
autoStart bool
|
||||
@@ -168,6 +181,13 @@ type Options struct {
|
||||
// were accepted.
|
||||
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
|
||||
// .od[tpgs] extension will have that extension changed to .pdf when the
|
||||
// link is exported to PDF. The source document remains untouched.
|
||||
@@ -341,6 +361,7 @@ func DefaultOptions() Options {
|
||||
ExportOnlyNotesPages: false,
|
||||
ExportNotesInMargin: false,
|
||||
ShowTrackedChanges: false,
|
||||
FailOnMissingFonts: false,
|
||||
ConvertOooTargetToPdfTarget: false,
|
||||
ExportLinksRelativeFsys: false,
|
||||
ExportHiddenSlides: false,
|
||||
@@ -763,7 +784,8 @@ func libreofficeErrorType(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, ErrInvalidPdfFormats),
|
||||
errors.Is(err, ErrLoadFailed),
|
||||
errors.Is(err, ErrInvalidPassword):
|
||||
errors.Is(err, ErrInvalidPassword),
|
||||
errors.As(err, new(*MissingFontsError)):
|
||||
return gotenberg.ErrorTypeInvalidInput
|
||||
case errors.Is(err, ErrMemoryLimitExceeded):
|
||||
return "libreoffice_memory_limit"
|
||||
|
||||
@@ -22,6 +22,7 @@ func TestLibreofficeErrorType(t *testing.T) {
|
||||
{"invalid pdf formats", ErrInvalidPdfFormats, "invalid_input"},
|
||||
{"load failed", ErrLoadFailed, "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"},
|
||||
{"crashed", ErrCrashed, "libreoffice_exception"},
|
||||
{"queue size exceeded", gotenberg.ErrMaximumQueueSizeExceeded, "libreoffice_unavailable"},
|
||||
|
||||
@@ -137,9 +137,10 @@ type lokRequest struct {
|
||||
|
||||
// lokResponse is the answer of lok's long-running mode to a request.
|
||||
type lokResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Code string `json:"code"`
|
||||
Error string `json:"error"`
|
||||
Success bool `json:"success"`
|
||||
Code string `json:"code"`
|
||||
Error string `json:"error"`
|
||||
FontsMissing []string `json:"fontsMissing"`
|
||||
}
|
||||
|
||||
// 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 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
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package api
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -31,7 +33,7 @@ func TestMain(m *testing.M) {
|
||||
}
|
||||
|
||||
// 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"
|
||||
// exits. It records its arguments next to its profile.
|
||||
func fakeLok() {
|
||||
@@ -64,6 +66,9 @@ func fakeLok() {
|
||||
case "ok":
|
||||
_ = os.WriteFile(req.OutputPath, line, 0o600)
|
||||
_ = 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":
|
||||
_ = out.Encode(lokResponse{Code: lokCodeInvalidPassword, Error: "failed to load document: wrong document password"})
|
||||
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) {
|
||||
p := startFakeLok(t)
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@ package libreoffice
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
|
||||
@@ -62,6 +64,7 @@ func convertRoute(libreOffice libreofficeapi.Converter, processor *pdf.Processor
|
||||
Bool("exportOnlyNotesPages", &options.ExportOnlyNotesPages).
|
||||
Bool("exportNotesInMargin", &options.ExportNotesInMargin).
|
||||
Bool("showTrackedChanges", &options.ShowTrackedChanges).
|
||||
Bool("failOnMissingFonts", &options.FailOnMissingFonts).
|
||||
Bool("convertOooTargetToPdfTarget", &options.ConvertOooTargetToPdfTarget).
|
||||
Bool("exportLinksRelativeFsys", &options.ExportLinksRelativeFsys).
|
||||
Bool("exportHiddenSlides", &options.ExportHiddenSlides).
|
||||
@@ -176,20 +179,23 @@ func convertRoute(libreOffice libreofficeapi.Converter, processor *pdf.Processor
|
||||
|
||||
outputPaths := make([]string, len(inputPaths))
|
||||
for i, inputPath := range inputPaths {
|
||||
filename := ctx.OriginalFilename(inputPath)
|
||||
|
||||
// document.docx -> document.docx.pdf, which names the output,
|
||||
// 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 {
|
||||
filename := ctx.OriginalFilename(inputPath)
|
||||
|
||||
// Blame the client only when one of its inputs is actually
|
||||
// implicated, since the server is the only remaining
|
||||
// explanation otherwise. A password failure aborts on
|
||||
// import, before the export filter applies any page range.
|
||||
// See https://github.com/gotenberg/gotenberg/issues/1588.
|
||||
var sentinel api.SentinelHttpError
|
||||
var missingFonts *libreofficeapi.MissingFontsError
|
||||
switch {
|
||||
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))
|
||||
@@ -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))
|
||||
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))
|
||||
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):
|
||||
// The same document exceeds the limit again: a 4xx
|
||||
// tells the client not to retry it as is.
|
||||
|
||||
@@ -127,6 +127,14 @@ func TestConvertRoute_FailureStatus(t *testing.T) {
|
||||
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'.",
|
||||
},
|
||||
{
|
||||
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",
|
||||
inputPath: plain,
|
||||
|
||||
@@ -100,6 +100,36 @@ Feature: /forms/libreoffice/convert
|
||||
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)
|
||||
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):
|
||||
@@ -397,6 +427,7 @@ Feature: /forms/libreoffice/convert
|
||||
| exportOnlyNotesPages | foo | field |
|
||||
| exportNotesInMargin | foo | field |
|
||||
| showTrackedChanges | foo | field |
|
||||
| failOnMissingFonts | foo | field |
|
||||
| convertOooTargetToPdfTarget | foo | field |
|
||||
| exportLinksRelativeFsys | 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 'exportNotesInMargin' 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 'exportLinksRelativeFsys' is invalid (got 'foo', want true or false)
|
||||
form field 'exportHiddenSlides' is invalid (got 'foo', want true or false)
|
||||
|
||||
BIN
test/integration/testdata/missing_font.docx
vendored
Normal file
BIN
test/integration/testdata/missing_font.docx
vendored
Normal file
Binary file not shown.
Reference in New Issue
Block a user