feat(pdf): add fileBookmarks to merge for one bookmark per merged PDF

This commit is contained in:
Julien Neuhart
2026-11-17 19:06:54 +01:00
parent b574de919e
commit 48ad2a7227
5 changed files with 338 additions and 8 deletions

View File

@@ -294,19 +294,31 @@ func (p *Processor) write(ctx *api.Context, pipeline *litho.Pipeline, ops []stri
}
// merge appends every document, in order, into one named after the first.
// With file bookmarks, each document gets a top-level bookmark at its first
// page, its own outline nested under it, even when it is the only one.
func (p *Processor) merge(ctx *api.Context, s *mergeStage, docs []document, password string) ([]document, error) {
// A single document is not rewritten, but it is read all the same: merge
// must not hand back a file the other routes refuse.
if len(docs) == 1 {
if len(docs) == 0 {
return docs, nil
}
if s.FileBookmarks != nil {
err := checkLabelNames(s.FileBookmarks, docs)
if err != nil {
return nil, &stageError{op: "merge", filename: docs[0].filename, err: err}
}
}
// A single document without file bookmarks is not rewritten, but it is
// read all the same: merge must not hand back a file the other routes
// refuse.
if len(docs) == 1 && s.FileBookmarks == nil {
r, err := p.open(ctx, docs[0].path, password)
if err != nil {
return nil, &stageError{op: "merge", filename: docs[0].filename, err: err}
}
_ = r.Close()
}
if len(docs) < 2 {
return docs, nil
}
@@ -326,7 +338,36 @@ func (p *Processor) merge(ctx *api.Context, s *mergeStage, docs []document, pass
readers = append(readers, r)
}
pipeline := litho.NewPipeline().Open(readers[0]).Merge(readers[1:])
var pipeline *litho.Pipeline
switch {
case s.FileBookmarks == nil:
pipeline = litho.NewPipeline().Open(readers[0]).Merge(readers[1:])
case len(readers) == 1:
// litho merges two documents or more. One document keeps its pages
// and gains the bookmark in an update, as set-bookmarks does.
outline, err := readers[0].Bookmarks(ctx)
if err != nil {
return nil, &stageError{op: "merge", filename: docs[0].filename, err: err}
}
bookmarks := []models.Bookmark{{
Title: fileBookmarkLabels(ctx, s.FileBookmarks, readers, docs)[0],
PageNumber: 1,
Children: outline,
}}
pipeline = litho.NewPipeline().Open(readers[0]).Apply(func(_ context.Context, w *litho.Writer) error {
w.SetBookmarks(bookmarks)
return nil
})
default:
pipeline = litho.NewPipeline().Open(readers[0]).Merge(readers[1:], litho.WithBookmarks(litho.BookmarkOptions{
Handling: litho.BookmarkUpdate,
WrapEachSource: true,
SourceLabels: fileBookmarkLabels(ctx, s.FileBookmarks, readers, docs),
}))
}
merged, err := p.write(ctx, pipeline, []string{"merge"}, docs[0].filename, signatureRemoval(s)...)
if err != nil {
@@ -336,6 +377,57 @@ func (p *Processor) merge(ctx *api.Context, s *mergeStage, docs []document, pass
return []document{merged}, nil
}
// checkLabelNames refuses a label of b for a filename no document has.
func checkLabelNames(b *fileBookmarks, docs []document) error {
for _, name := range sortedKeys(b.Labels) {
if !slices.ContainsFunc(docs, func(d document) bool { return d.filename == name }) {
return &stageInputError{message: fmt.Sprintf(`"fileBookmarks.labels" must name an uploaded PDF, got %q; the uploaded PDFs are %s`, name, documentNames(docs))}
}
}
return nil
}
// fileBookmarkLabels returns the label of each document's bookmark, in order
// (see [fileBookmarks]). A title that cannot be read is skipped, with a
// warning.
func fileBookmarkLabels(ctx *api.Context, b *fileBookmarks, readers []*litho.Reader, docs []document) []string {
labels := make([]string, len(docs))
for i, d := range docs {
if label, ok := b.Labels[d.filename]; ok {
labels[i] = label
continue
}
for _, source := range b.sources() {
switch source {
case "title":
metadata, err := readers[i].Metadata(ctx)
if err != nil {
ctx.Log().WarnContext(ctx, fmt.Sprintf("read the title of '%s' for its bookmark: %s", d.filename, err))
continue
}
if title := metadata["Title"]; strings.TrimSpace(title) != "" {
labels[i] = title
}
case "filename":
labels[i] = strings.TrimSuffix(d.filename, filepath.Ext(d.filename))
if strings.TrimSpace(labels[i]) == "" {
labels[i] = d.filename
}
}
if labels[i] != "" {
break
}
}
}
return labels
}
// compose draws the pages the placements of s name, each from the document
// its source names, on new pages, and returns that one document, named after
// the first.

View File

@@ -15,6 +15,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
@@ -1522,3 +1523,106 @@ func TestRunSignErrors(t *testing.T) {
})
}
}
// TestRunMergeFileBookmarks pins the bookmark merge adds per document with
// fileBookmarks: at the document's first page, its own outline nested under
// it, labeled by an explicit label, its title, or its filename.
func TestRunMergeFileBookmarks(t *testing.T) {
alpha := models.Bookmark{Title: "Alpha", PageNumber: 1, Children: []models.Bookmark{
{Title: "A1", PageNumber: 1},
{Title: "A2", PageNumber: 2},
}}
for _, tc := range []struct {
name string
inputs []string
stages string
want []models.Bookmark
}{
{
name: "title, then filename",
inputs: []string{"titled_alpha.pdf", "titled_bravo.pdf", "untitled_gamma.pdf"},
stages: `[{"op":"merge","fileBookmarks":{}}]`,
want: []models.Bookmark{
alpha,
{Title: "Bravo", PageNumber: 3},
{Title: "untitled_gamma", PageNumber: 4},
},
},
{
name: "filename only",
inputs: []string{"titled_alpha.pdf", "untitled_gamma.pdf"},
stages: `[{"op":"merge","fileBookmarks":{"label":["filename"]}}]`,
want: []models.Bookmark{
{Title: "titled_alpha", PageNumber: 1, Children: alpha.Children},
{Title: "untitled_gamma", PageNumber: 3},
},
},
{
name: "title, with filename implied last",
inputs: []string{"titled_bravo.pdf", "untitled_gamma.pdf"},
stages: `[{"op":"merge","fileBookmarks":{"label":["title"]}}]`,
want: []models.Bookmark{
{Title: "Bravo", PageNumber: 1},
{Title: "untitled_gamma", PageNumber: 2},
},
},
{
name: "an explicit label wins",
inputs: []string{"titled_alpha.pdf", "titled_bravo.pdf"},
stages: `[{"op":"merge","fileBookmarks":{"labels":{"titled_bravo.pdf":"Annex B"}}}]`,
want: []models.Bookmark{alpha, {Title: "Annex B", PageNumber: 3}},
},
{
name: "a single document",
inputs: []string{"titled_alpha.pdf"},
stages: `[{"op":"merge","fileBookmarks":{}}]`,
want: []models.Bookmark{alpha},
},
{
name: "without fileBookmarks, the outlines are concatenated",
inputs: []string{"titled_alpha.pdf", "titled_bravo.pdf"},
stages: `[{"op":"merge"}]`,
want: alpha.Children,
},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, paths := testContext(t, tc.inputs...)
inputs := make([]string, len(tc.inputs))
for i, name := range tc.inputs {
inputs[i] = paths[name]
}
outputs, err := testProcessor().Run(ctx, mustStages(t, tc.stages), inputs, nil)
if err != nil {
t.Fatalf("Run: %v", err)
}
got, err := openOutput(t, outputs[0]).Bookmarks(context.Background())
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, tc.want) {
t.Fatalf("outline = %+v, want %+v", got, tc.want)
}
})
}
}
func TestRunMergeFileBookmarksUnknownLabel(t *testing.T) {
ctx, paths := testContext(t, "page_1.pdf", "page_2.pdf")
_, err := testProcessor().Run(ctx, mustStages(t, `[{"op":"merge","fileBookmarks":{"labels":{"nope.pdf":"N"}}}]`), []string{paths["page_1.pdf"], paths["page_2.pdf"]}, nil)
if err == nil {
t.Fatal("Run: want an error")
}
want := `Stage 'merge' failed on 'page_1.pdf': "fileBookmarks.labels" must name an uploaded PDF, got "nope.pdf"; the uploaded PDFs are page_1.pdf, page_2.pdf`
status, message := api.ParseError(err)
if status != http.StatusBadRequest || message != want {
t.Fatalf("got %d %q, want 400 %q", status, message, want)
}
}

View File

@@ -36,14 +36,70 @@ type rewriter interface {
}
// mergeStage appends every current document, in order, into one.
// FileBookmarks, when set, adds one top-level bookmark per document, leading
// to its first page, with the document's own outline nested under it.
type mergeStage struct {
FileBookmarks *fileBookmarks `json:"fileBookmarks"`
signatureDrop
}
func (*mergeStage) op() string { return "merge" }
func (*mergeStage) validate() error { return nil }
func (*mergeStage) op() string { return "merge" }
func (s *mergeStage) validate() error {
if s.FileBookmarks == nil {
return nil
}
return s.FileBookmarks.validate()
}
func (*mergeStage) files() []string { return nil }
// fileBookmarks labels the bookmark merge adds for each document. Labels
// gives the label of the documents it names by filename. Every other document
// takes the first non-blank label of the sources Label lists, in order:
// "title", the document's title metadata, and "filename", its filename
// without the extension. filename ends every list, so each document gets a
// label, and Label defaults to ["title","filename"].
type fileBookmarks struct {
Label []string `json:"label"`
Labels map[string]string `json:"labels"`
}
// labelSources are the values of [fileBookmarks.Label].
var labelSources = []string{"title", "filename"}
func (b *fileBookmarks) validate() error {
for _, source := range b.Label {
if !slices.Contains(labelSources, source) {
return fmt.Errorf(`"fileBookmarks.label" must list label sources among %s, got %q`, strings.Join(labelSources, ", "), source)
}
}
for _, name := range sortedKeys(b.Labels) {
if strings.TrimSpace(b.Labels[name]) == "" {
return fmt.Errorf(`"fileBookmarks.labels" must give %q a non-blank label`, name)
}
}
return nil
}
// sources returns the label sources to try, in order: Label, or the default,
// with "filename" last when Label leaves it out.
func (b *fileBookmarks) sources() []string {
if len(b.Label) == 0 {
return labelSources
}
if slices.Contains(b.Label, "filename") {
return b.Label
}
return append(slices.Clone(b.Label), "filename")
}
// splitStage turns each current document into several. Every splits it into
// chunks of that many pages; Ranges into one document per page selection, such
// as ["1-3","4","5,7"].

View File

@@ -68,6 +68,9 @@ func TestParseStages(t *testing.T) {
{name: "empty split range", raw: `[{"op":"split","ranges":["1-3",""]}]`, wantErr: `"ranges" entry 1 must select pages`},
{name: "timestamp url scheme", raw: `[{"op":"timestamp","timestampUrl":"file:///etc/passwd"}]`, wantErr: "http:// or https://"},
{name: "decrypt not first", raw: `[{"op":"merge"},{"op":"decrypt","password":"x"}]`, wantErr: "must be the first stage"},
{name: "unknown label source", raw: `[{"op":"merge","fileBookmarks":{"label":["subject"]}}]`, wantErr: `merge: "fileBookmarks.label" must list label sources among title, filename, got "subject"`},
{name: "blank file label", raw: `[{"op":"merge","fileBookmarks":{"labels":{"a.pdf":" "}}}]`, wantErr: `merge: "fileBookmarks.labels" must give "a.pdf" a non-blank label`},
{name: "unknown fileBookmarks option", raw: `[{"op":"merge","fileBookmarks":{"format":"{n}"}}]`, wantErr: "merge:"},
{name: "edit after remediate", raw: `[{"op":"remediate","profile":"PDF/A-2b"},{"op":"rotate","angle":90}]`, wantErr: `cannot follow "remediate"`},
{name: "decrypt after encrypt", raw: `[{"op":"encrypt","userPassword":"u"},{"op":"decrypt","password":"x"}]`, wantErr: `stage 1: "decrypt" must be the first stage`},
{name: "two remediations", raw: `[{"op":"remediate","profile":"PDF/UA-1"},{"op":"remediate","profile":"PDF/UA-1"}]`, wantErr: `stage 1: only one "remediate" stage is allowed`},

View File

@@ -59,6 +59,81 @@ Feature: /forms/pdf/merge
Then the response status code should be 200
Then the "foo.pdf" PDF should have 3 page(s)
# fileBookmarks adds a top-level bookmark per merged PDF, labeled by its title
# metadata, falling back to its filename, at its first page, with its own
# outline nested underneath. See https://github.com/gotenberg/gotenberg/issues/1736.
Scenario: POST /forms/pdf/merge (File Bookmarks)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/pdf/merge" endpoint with the following form data and header(s):
| files | testdata/titled_alpha.pdf | file |
| files | testdata/titled_bravo.pdf | file |
| files | testdata/untitled_gamma.pdf | file |
| fileBookmarks | {} | field |
| Gotenberg-Output-Filename | foo | header |
Then the response status code should be 200
Then the response header "Content-Type" should be "application/pdf"
When I make a "POST" request to Gotenberg at the "/forms/pdf/bookmarks" endpoint with the following form data and header(s):
| files | teststore/foo.pdf | file |
Then the response status code should be 200
Then the response body should match JSON:
"""
{
"foo.pdf": [
{
"title": "Alpha",
"pageNumber": 1,
"children": [
{ "title": "A1", "pageNumber": 1 },
{ "title": "A2", "pageNumber": 2 }
]
},
{ "title": "Bravo", "pageNumber": 3 },
{ "title": "untitled_gamma", "pageNumber": 4 }
]
}
"""
Scenario: POST /forms/pdf/pipe (File Bookmarks Labels)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/pdf/pipe" endpoint with the following form data and header(s):
| files | testdata/titled_alpha.pdf | file |
| files | testdata/titled_bravo.pdf | file |
| stages | [{"op":"merge","fileBookmarks":{"label":["filename"],"labels":{"titled_bravo.pdf":"Annex B"}}}] | field |
| Gotenberg-Output-Filename | foo | header |
Then the response status code should be 200
When I make a "POST" request to Gotenberg at the "/forms/pdf/bookmarks" endpoint with the following form data and header(s):
| files | teststore/foo.pdf | file |
Then the response status code should be 200
Then the response body should match JSON:
"""
{
"foo.pdf": [
{
"title": "titled_alpha",
"pageNumber": 1,
"children": [
{ "title": "A1", "pageNumber": 1 },
{ "title": "A2", "pageNumber": 2 }
]
},
{ "title": "Annex B", "pageNumber": 3 }
]
}
"""
Scenario: POST /forms/pdf/merge (File Bookmarks Unknown Label)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/pdf/merge" endpoint with the following form data and header(s):
| files | testdata/page_1.pdf | file |
| files | testdata/page_2.pdf | file |
| fileBookmarks | {"labels":{"nope.pdf":"N"}} | field |
Then the response status code should be 400
Then the response header "Content-Type" should be "text/plain; charset=UTF-8"
Then the response body should match string:
"""
Stage 'merge' failed on 'page_1.pdf': "fileBookmarks.labels" must name an uploaded PDF, got "nope.pdf"; the uploaded PDFs are page_1.pdf, page_2.pdf
"""
Scenario: POST /forms/pdf/merge (Bad Request)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/pdf/merge" endpoint with the following form data and header(s):