Skip to content

Commit e9a6713

Browse files
committed
feat(pdfengines): apply multiple stamps in one request (#1601)
1 parent 41b33fd commit e9a6713

5 files changed

Lines changed: 361 additions & 8 deletions

File tree

‎pkg/modules/api/formdata.go‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,36 @@ func (form *FormData) Stamp(target *string) *FormData {
479479
return form
480480
}
481481

482+
// Stamps binds the absolute paths of every file uploaded with the "stamp"
483+
// field name, in submission order. Unlike [FormData.Stamp], it keeps all of
484+
// them so a route can apply several stamps in a single request.
485+
func (form *FormData) Stamps(target *[]string) *FormData {
486+
if form.errors != nil {
487+
return form
488+
}
489+
490+
if paths, ok := form.filesByField[StampFormField]; ok {
491+
*target = paths
492+
}
493+
494+
return form
495+
}
496+
497+
// Strings binds every value submitted for key, in submission order. A field
498+
// repeated in the multipart body (e.g. multiple "stampSource") contributes one
499+
// entry per occurrence, which lets a route read parallel field arrays.
500+
func (form *FormData) Strings(key string, target *[]string) *FormData {
501+
if form.errors != nil {
502+
return form
503+
}
504+
505+
if values, ok := form.values[key]; ok {
506+
*target = values
507+
}
508+
509+
return form
510+
}
511+
482512
// FacturXXml binds the absolute path of the uploaded Factur-X CII invoice
483513
// XML. Only a file uploaded with the "facturxXml" field name is included.
484514
func (form *FormData) FacturXXml(target *string) *FormData {

‎pkg/modules/api/formdata_test.go‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1837,3 +1837,46 @@ func TestFormData_paths_excludesFacturXXml(t *testing.T) {
18371837
t.Errorf("expected only the non-Factur-X .xml document, got %+v", paths)
18381838
}
18391839
}
1840+
1841+
func TestFormData_Strings(t *testing.T) {
1842+
form := &FormData{
1843+
values: map[string][]string{
1844+
"foo": {"a", "b", "c"},
1845+
},
1846+
}
1847+
1848+
var got []string
1849+
form.Strings("foo", &got)
1850+
1851+
if want := []string{"a", "b", "c"}; !reflect.DeepEqual(got, want) {
1852+
t.Errorf("expected %+v, got %+v", want, got)
1853+
}
1854+
1855+
var missing []string
1856+
form.Strings("bar", &missing)
1857+
if missing != nil {
1858+
t.Errorf("expected nil for a missing key, got %+v", missing)
1859+
}
1860+
}
1861+
1862+
func TestFormData_Stamps(t *testing.T) {
1863+
form := &FormData{
1864+
filesByField: map[string][]string{
1865+
StampFormField: {"/tmp/abc/a.png", "/tmp/abc/b.pdf"},
1866+
},
1867+
}
1868+
1869+
var got []string
1870+
form.Stamps(&got)
1871+
1872+
if want := []string{"/tmp/abc/a.png", "/tmp/abc/b.pdf"}; !reflect.DeepEqual(got, want) {
1873+
t.Errorf("expected %+v, got %+v", want, got)
1874+
}
1875+
1876+
empty := &FormData{}
1877+
var none []string
1878+
empty.Stamps(&none)
1879+
if none != nil {
1880+
t.Errorf("expected nil when no stamp file was uploaded, got %+v", none)
1881+
}
1882+
}

‎pkg/modules/pdfengines/routes.go‎

Lines changed: 114 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -934,6 +934,92 @@ func EnsureStampFile(stamp *gotenberg.Stamp, uploadedFile string) error {
934934
return nil
935935
}
936936

937+
// FormDataPdfStamps builds the ordered list of stamps from the repeated stamp
938+
// fields: stampSource, stampExpression, stampPages and stampOptions. The number
939+
// of stamps equals the number of stampSource values, so a single occurrence of
940+
// each field yields one stamp, preserving the single-stamp behavior. Fields are
941+
// aligned by position; a missing expression, pages or options entry defaults to
942+
// empty. Image and pdf stamps take their file from the uploaded stamp files, in
943+
// order (see [BindStampFiles]).
944+
func FormDataPdfStamps(form *api.FormData) ([]gotenberg.Stamp, error) {
945+
var sources, expressions, pages, options []string
946+
form.
947+
Strings("stampSource", &sources).
948+
Strings("stampExpression", &expressions).
949+
Strings("stampPages", &pages).
950+
Strings("stampOptions", &options)
951+
952+
at := func(values []string, i int) string {
953+
if i < len(values) {
954+
return values[i]
955+
}
956+
return ""
957+
}
958+
959+
stamps := make([]gotenberg.Stamp, 0, len(sources))
960+
for i, source := range sources {
961+
if source != gotenberg.StampSourceText && source != gotenberg.StampSourceImage && source != gotenberg.StampSourcePDF {
962+
return nil, api.WrapError(
963+
fmt.Errorf("wrong stampSource value '%s'", source),
964+
api.NewSentinelHttpError(
965+
http.StatusBadRequest,
966+
fmt.Sprintf("Invalid form data: form field 'stampSource' is invalid (got '%s', resulting to wrong value, expected either '%s', '%s' or '%s')", source, gotenberg.StampSourceText, gotenberg.StampSourceImage, gotenberg.StampSourcePDF),
967+
),
968+
)
969+
}
970+
971+
var opts map[string]string
972+
if raw := at(options, i); raw != "" {
973+
err := json.Unmarshal([]byte(raw), &opts)
974+
if err != nil {
975+
return nil, api.WrapError(
976+
fmt.Errorf("unmarshal stampOptions: %w", err),
977+
api.NewSentinelHttpError(
978+
http.StatusBadRequest,
979+
"Invalid form data: form field 'stampOptions' is invalid",
980+
),
981+
)
982+
}
983+
}
984+
985+
stamps = append(stamps, gotenberg.Stamp{
986+
Source: source,
987+
Expression: at(expressions, i),
988+
Pages: at(pages, i),
989+
Options: opts,
990+
})
991+
}
992+
993+
return stamps, nil
994+
}
995+
996+
// BindStampFiles assigns each image or pdf stamp its uploaded file, consuming
997+
// stampFiles in order. Text stamps take no file. It returns an [api] HTTP 400
998+
// error when an image or pdf stamp has no file left to consume, which also
999+
// prevents an anonymous caller from passing an arbitrary filesystem path via
1000+
// stampExpression.
1001+
func BindStampFiles(stamps []gotenberg.Stamp, stampFiles []string) error {
1002+
fileIndex := 0
1003+
for i := range stamps {
1004+
if stamps[i].Source != gotenberg.StampSourceImage && stamps[i].Source != gotenberg.StampSourcePDF {
1005+
continue
1006+
}
1007+
if fileIndex >= len(stampFiles) {
1008+
return api.WrapError(
1009+
errors.New("not enough stamp files for the image or pdf stamps"),
1010+
api.NewSentinelHttpError(
1011+
http.StatusBadRequest,
1012+
"Invalid form data: a stamp file is required for image or pdf source",
1013+
),
1014+
)
1015+
}
1016+
stamps[i].Expression = stampFiles[fileIndex]
1017+
fileIndex++
1018+
}
1019+
1020+
return nil
1021+
}
1022+
9371023
// EnsureWatermarkFile mirrors [EnsureStampFile] for a watermark. The
9381024
// shape is identical: image or pdf sources must be accompanied by an
9391025
// uploaded file, and the file path replaces watermark.Expression to
@@ -1773,25 +1859,45 @@ func stampRoute(engine gotenberg.PdfEngine) api.Route {
17731859
ctx := c.Get("context").(*api.Context)
17741860

17751861
form := ctx.FormData()
1776-
stamp := FormDataPdfStamp(form, true)
1777-
stampFile := FormDataPdfStampFile(form)
1862+
1863+
// Reading the stamp fields as parallel arrays applies several
1864+
// stamps in one request. A single occurrence of each field is the
1865+
// existing single-stamp behavior.
1866+
stamps, err := FormDataPdfStamps(form)
1867+
if err != nil {
1868+
return fmt.Errorf("form data stamps: %w", err)
1869+
}
17781870

17791871
var inputPaths []string
1780-
err := form.
1872+
var stampFiles []string
1873+
err = form.
17811874
MandatoryPaths([]string{".pdf"}, &inputPaths).
1875+
Stamps(&stampFiles).
17821876
Validate()
17831877
if err != nil {
17841878
return fmt.Errorf("validate form data: %w", err)
17851879
}
17861880

1787-
err = EnsureStampFile(&stamp, stampFile)
1788-
if err != nil {
1789-
return fmt.Errorf("validate stamp: %w", err)
1881+
if len(stamps) == 0 {
1882+
return api.WrapError(
1883+
errors.New("no stamp provided"),
1884+
api.NewSentinelHttpError(
1885+
http.StatusBadRequest,
1886+
"Invalid form data: form field 'stampSource' is required",
1887+
),
1888+
)
17901889
}
17911890

1792-
err = StampStub(ctx, engine, stamp, inputPaths)
1891+
err = BindStampFiles(stamps, stampFiles)
17931892
if err != nil {
1794-
return fmt.Errorf("stamp PDFs: %w", err)
1893+
return fmt.Errorf("bind stamp files: %w", err)
1894+
}
1895+
1896+
for _, stamp := range stamps {
1897+
err = StampStub(ctx, engine, stamp, inputPaths)
1898+
if err != nil {
1899+
return fmt.Errorf("stamp PDFs: %w", err)
1900+
}
17951901
}
17961902

17971903
err = ctx.AddOutputPaths(inputPaths...)
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
package pdfengines
2+
3+
import (
4+
"errors"
5+
"net/http"
6+
"reflect"
7+
"testing"
8+
9+
"github.com/gotenberg/gotenberg/v8/pkg/gotenberg"
10+
"github.com/gotenberg/gotenberg/v8/pkg/modules/api"
11+
)
12+
13+
func TestFormDataPdfStamps(t *testing.T) {
14+
for _, tc := range []struct {
15+
scenario string
16+
values map[string][]string
17+
expect []gotenberg.Stamp
18+
expectErr bool
19+
expectCode int
20+
}{
21+
{
22+
scenario: "single text stamp (backward compatible)",
23+
values: map[string][]string{
24+
"stampSource": {"text"},
25+
"stampExpression": {"CONFIDENTIAL"},
26+
"stampOptions": {`{"rot":"45"}`},
27+
},
28+
expect: []gotenberg.Stamp{
29+
{Source: "text", Expression: "CONFIDENTIAL", Options: map[string]string{"rot": "45"}},
30+
},
31+
},
32+
{
33+
scenario: "multiple stamps aligned by position",
34+
values: map[string][]string{
35+
"stampSource": {"text", "image"},
36+
"stampExpression": {"ONE"},
37+
"stampPages": {"1-2", "3"},
38+
"stampOptions": {`{"pos":"tl"}`, `{"pos":"br"}`},
39+
},
40+
expect: []gotenberg.Stamp{
41+
{Source: "text", Expression: "ONE", Pages: "1-2", Options: map[string]string{"pos": "tl"}},
42+
{Source: "image", Expression: "", Pages: "3", Options: map[string]string{"pos": "br"}},
43+
},
44+
},
45+
{
46+
scenario: "no stamp fields",
47+
values: map[string][]string{},
48+
expect: []gotenberg.Stamp{},
49+
},
50+
{
51+
scenario: "invalid source",
52+
values: map[string][]string{"stampSource": {"text", "foo"}},
53+
expectErr: true,
54+
expectCode: http.StatusBadRequest,
55+
},
56+
{
57+
scenario: "invalid options JSON",
58+
values: map[string][]string{
59+
"stampSource": {"text"},
60+
"stampOptions": {"{"},
61+
},
62+
expectErr: true,
63+
expectCode: http.StatusBadRequest,
64+
},
65+
} {
66+
t.Run(tc.scenario, func(t *testing.T) {
67+
ctx := &api.ContextMock{Context: &api.Context{}}
68+
ctx.SetValues(tc.values)
69+
form := ctx.FormData()
70+
71+
got, err := FormDataPdfStamps(form)
72+
73+
if tc.expectErr {
74+
if err == nil {
75+
t.Fatal("expected an error, got nil")
76+
}
77+
var httpErr api.HttpError
78+
if !errors.As(err, &httpErr) {
79+
t.Fatalf("expected an api.HttpError, got %T", err)
80+
}
81+
if status, _ := httpErr.HttpError(); status != tc.expectCode {
82+
t.Fatalf("status = %d, want %d", status, tc.expectCode)
83+
}
84+
return
85+
}
86+
87+
if err != nil {
88+
t.Fatalf("expected no error, got %v", err)
89+
}
90+
if !reflect.DeepEqual(got, tc.expect) {
91+
t.Fatalf("stamps = %#v, want %#v", got, tc.expect)
92+
}
93+
})
94+
}
95+
}
96+
97+
func TestBindStampFiles(t *testing.T) {
98+
for _, tc := range []struct {
99+
scenario string
100+
stamps []gotenberg.Stamp
101+
files []string
102+
expect []gotenberg.Stamp
103+
expectErr bool
104+
expectCode int
105+
}{
106+
{
107+
scenario: "text stamps consume no files",
108+
stamps: []gotenberg.Stamp{{Source: "text", Expression: "FOO"}},
109+
expect: []gotenberg.Stamp{{Source: "text", Expression: "FOO"}},
110+
},
111+
{
112+
scenario: "image and pdf stamps consume files in order, overwriting expression",
113+
stamps: []gotenberg.Stamp{
114+
{Source: "image", Expression: "ignored"},
115+
{Source: "text", Expression: "MIDDLE"},
116+
{Source: "pdf"},
117+
},
118+
files: []string{"/a.png", "/b.pdf"},
119+
expect: []gotenberg.Stamp{
120+
{Source: "image", Expression: "/a.png"},
121+
{Source: "text", Expression: "MIDDLE"},
122+
{Source: "pdf", Expression: "/b.pdf"},
123+
},
124+
},
125+
{
126+
scenario: "not enough files for the image or pdf stamps",
127+
stamps: []gotenberg.Stamp{{Source: "image"}, {Source: "image"}},
128+
files: []string{"/a.png"},
129+
expectErr: true,
130+
expectCode: http.StatusBadRequest,
131+
},
132+
} {
133+
t.Run(tc.scenario, func(t *testing.T) {
134+
err := BindStampFiles(tc.stamps, tc.files)
135+
136+
if tc.expectErr {
137+
if err == nil {
138+
t.Fatal("expected an error, got nil")
139+
}
140+
var httpErr api.HttpError
141+
if !errors.As(err, &httpErr) {
142+
t.Fatalf("expected an api.HttpError, got %T", err)
143+
}
144+
if status, _ := httpErr.HttpError(); status != tc.expectCode {
145+
t.Fatalf("status = %d, want %d", status, tc.expectCode)
146+
}
147+
return
148+
}
149+
150+
if err != nil {
151+
t.Fatalf("expected no error, got %v", err)
152+
}
153+
if !reflect.DeepEqual(tc.stamps, tc.expect) {
154+
t.Fatalf("stamps = %#v, want %#v", tc.stamps, tc.expect)
155+
}
156+
})
157+
}
158+
}

0 commit comments

Comments
 (0)