-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpdf_renderer.go
More file actions
2010 lines (1806 loc) · 56.4 KB
/
pdf_renderer.go
File metadata and controls
2010 lines (1806 loc) · 56.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"image/png"
"io"
"log"
"math"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/code128"
"github.com/boombuler/barcode/ean"
"github.com/signintech/gopdf"
goqrcode "github.com/skip2/go-qrcode"
)
const mmToPt = 2.835 // 1mm = 2.835 PDF points
// ════════════════════════════════════════════════════
// Schema types
// ════════════════════════════════════════════════════
// PdfmeSchema represents a parsed pdfme template schema (v4 or v5).
type PdfmeSchema struct {
Schemas [][]PdfmeField `json:"schemas"` // pages → fields
BasePdf PdfmeBasePdf `json:"basePdf"`
}
// PdfmeBasePdf is the page dimensions and optional background PDF.
type PdfmeBasePdf struct {
Width float64 `json:"width"` // mm
Height float64 `json:"height"` // mm
Padding []float64 `json:"padding"`
BackgroundPdf string // base64-encoded PDF to use as page background (decoded from basePdf string)
}
// PdfmeField is a single field in the schema.
type PdfmeField struct {
Name string `json:"name"`
Type string `json:"type"`
Position PdfmePos `json:"position"`
Width float64 `json:"width"` // mm
Height float64 `json:"height"` // mm
FontSize float64 `json:"fontSize,omitempty"`
FontName string `json:"fontName,omitempty"`
FontWeight string `json:"fontWeight,omitempty"` // "bold"
Alignment string `json:"alignment,omitempty"`
VerticalAlignment string `json:"verticalAlignment,omitempty"` // top | middle | bottom
FontColor string `json:"fontColor,omitempty"`
BackgroundColor string `json:"backgroundColor,omitempty"`
BorderWidth jsonFloat `json:"borderWidth,omitempty"`
BorderColor string `json:"borderColor,omitempty"`
LineHeight float64 `json:"lineHeight,omitempty"`
Content string `json:"content,omitempty"`
Text string `json:"text,omitempty"`
Variables []string `json:"variables,omitempty"`
DynamicFontSize *DynFontSize `json:"dynamicFontSize,omitempty"`
Rotate float64 `json:"rotate,omitempty"`
Opacity float64 `json:"opacity,omitempty"`
Color string `json:"color,omitempty"` // for line type
// Table-specific
Head []string `json:"head,omitempty"`
HeadWidthPercentages []float64 `json:"headWidthPercentages,omitempty"`
ShowHead *bool `json:"showHead,omitempty"`
TableStyles json.RawMessage `json:"tableStyles,omitempty"`
HeadStyles json.RawMessage `json:"headStyles,omitempty"`
BodyStyles json.RawMessage `json:"bodyStyles,omitempty"`
// Rectangle-specific
Radius float64 `json:"radius,omitempty"`
// QR-specific: color finder patterns differently (custom extension, compatible with readers)
QrFinderColor string `json:"qrFinderColor,omitempty"`
// Text decoration
CharacterSpacing float64 `json:"characterSpacing,omitempty"`
Underline bool `json:"underline,omitempty"`
Strikethrough bool `json:"strikethrough,omitempty"`
// Layout
Padding jsonPadding `json:"padding,omitempty"`
}
// DynFontSize controls auto-sizing for text fields.
type DynFontSize struct {
Min float64 `json:"min"`
Max float64 `json:"max"`
Fit string `json:"fit"` // "vertical" | "horizontal"
}
// jsonFloat handles borderWidth being either a number or an object.
type jsonFloat float64
func (jf *jsonFloat) UnmarshalJSON(b []byte) error {
var f float64
if err := json.Unmarshal(b, &f); err == nil {
*jf = jsonFloat(f)
return nil
}
// borderWidth can be {top,right,bottom,left} — take top as representative
var obj map[string]float64
if err := json.Unmarshal(b, &obj); err == nil {
if v, ok := obj["top"]; ok {
*jf = jsonFloat(v)
}
return nil
}
*jf = 0
return nil
}
// jsonPadding handles padding as a number or [top,right,bottom,left] array.
type jsonPadding struct {
Top, Right, Bottom, Left float64
}
func (jp *jsonPadding) UnmarshalJSON(b []byte) error {
var n float64
if err := json.Unmarshal(b, &n); err == nil {
jp.Top, jp.Right, jp.Bottom, jp.Left = n, n, n, n
return nil
}
var arr []float64
if err := json.Unmarshal(b, &arr); err == nil {
switch len(arr) {
case 1:
jp.Top, jp.Right, jp.Bottom, jp.Left = arr[0], arr[0], arr[0], arr[0]
case 2:
jp.Top, jp.Bottom = arr[0], arr[0]
jp.Right, jp.Left = arr[1], arr[1]
case 3:
jp.Top = arr[0]
jp.Right, jp.Left = arr[1], arr[1]
jp.Bottom = arr[2]
case 4:
jp.Top, jp.Right, jp.Bottom, jp.Left = arr[0], arr[1], arr[2], arr[3]
}
return nil
}
return nil
}
// PdfmePos is x,y in mm.
type PdfmePos struct {
X float64 `json:"x"`
Y float64 `json:"y"`
}
// TableStyle holds parsed table style properties.
type TableStyle struct {
FontSize float64 `json:"fontSize"`
FontColor string `json:"fontColor"`
FontName string `json:"fontName"`
BackgroundColor string `json:"backgroundColor"`
Alignment string `json:"alignment"`
BorderColor string `json:"borderColor"`
}
var (
imgCache = map[string]string{}
imgCacheMu sync.Mutex
)
// ════════════════════════════════════════════════════
// Schema parsing — v4 and v5 with all basePdf formats
// ════════════════════════════════════════════════════
// ParsePdfmeSchema parses raw JSON into PdfmeSchema.
// Supports:
// - v5: schemas: [[{name:"...", type:"...", ...}, ...]]
// - v4: schemas: [{"fieldName": {type:"...", ...}, ...}]
// - basePdf: {width, height, padding} | "BLANK" | "data:application/pdf;base64,..." | "JVBERi0x..."
// - Multi-page: multiple entries in schemas array
func ParsePdfmeSchema(raw json.RawMessage) (*PdfmeSchema, error) {
// First extract basePdf (can be object, string, or missing)
basePdf := parseBasePdf(raw)
// Try v5 format: schemas is array of arrays
var v5 struct {
Schemas [][]PdfmeField `json:"schemas"`
}
if err := json.Unmarshal(raw, &v5); err == nil && len(v5.Schemas) > 0 && len(v5.Schemas[0]) > 0 {
schema := &PdfmeSchema{Schemas: v5.Schemas, BasePdf: basePdf}
applyBasePdfDefaults(schema)
log.Printf("[pdf] Parsed v5 schema: %d pages, %d fields on page 0", len(schema.Schemas), len(schema.Schemas[0]))
return schema, nil
}
// Try v4 format: schemas is array of keyed objects.
// IMPORTANT: Must preserve JSON key order — it defines the z-order (layer order).
// Go maps lose insertion order, so we use json.Decoder to iterate keys in order.
var v4raw struct {
Schemas []json.RawMessage `json:"schemas"`
}
if err := json.Unmarshal(raw, &v4raw); err != nil || len(v4raw.Schemas) == 0 {
return nil, fmt.Errorf("parse pdfme schema: no valid schemas found")
}
schema := &PdfmeSchema{BasePdf: basePdf}
schema.Schemas = make([][]PdfmeField, len(v4raw.Schemas))
for i, pageRaw := range v4raw.Schemas {
schema.Schemas[i] = parseV4PageOrdered(pageRaw, i)
}
applyBasePdfDefaults(schema)
totalFields := 0
for _, p := range schema.Schemas {
totalFields += len(p)
}
log.Printf("[pdf] Parsed v4 schema: %d pages, %d total fields", len(schema.Schemas), totalFields)
return schema, nil
}
// parseV4PageOrdered parses a single v4 schema page, preserving JSON key order (= z-order).
// Two-phase approach:
// Phase 1: Use json.Decoder (Token for keys, Decode to skip values) to extract key order.
// Phase 2: Unmarshal into map for reliable field parsing.
func parseV4PageOrdered(pageRaw json.RawMessage, pageIndex int) []PdfmeField {
// Phase 1: Extract ordered keys
dec := json.NewDecoder(bytes.NewReader(pageRaw))
t, err := dec.Token() // opening {
if err != nil || t != json.Delim('{') {
log.Printf("[pdf] Warning: page %d is not a JSON object", pageIndex)
return nil
}
var keyOrder []string
for dec.More() {
// Read key
t, err := dec.Token()
if err != nil {
break
}
key, ok := t.(string)
if !ok {
break
}
keyOrder = append(keyOrder, key)
// Skip value (Decode consumes one complete JSON value)
var skip json.RawMessage
if err := dec.Decode(&skip); err != nil {
log.Printf("[pdf] Warning: could not skip value for key %q on page %d: %v", key, pageIndex, err)
break
}
}
// Phase 2: Unmarshal full map for reliable field values
var fieldMap map[string]json.RawMessage
if err := json.Unmarshal(pageRaw, &fieldMap); err != nil {
log.Printf("[pdf] Warning: could not unmarshal page %d as map: %v", pageIndex, err)
return nil
}
// Build fields in key order (= z-order from JSON)
var fields []PdfmeField
for _, key := range keyOrder {
if strings.HasPrefix(key, "_") {
continue
}
raw, ok := fieldMap[key]
if !ok {
continue
}
var field PdfmeField
if err := json.Unmarshal(raw, &field); err != nil {
log.Printf("[pdf] Warning: skip field %q on page %d: %v", key, pageIndex, err)
continue
}
field.Name = key
fields = append(fields, field)
}
log.Printf("[pdf] Page %d: parsed %d fields in z-order (keys: %d, map entries: %d)",
pageIndex, len(fields), len(keyOrder), len(fieldMap))
return fields
}
// parseBasePdf handles all basePdf formats: object, "BLANK", base64 PDF string.
func parseBasePdf(raw json.RawMessage) PdfmeBasePdf {
var wrapper struct {
BasePdf json.RawMessage `json:"basePdf"`
}
if err := json.Unmarshal(raw, &wrapper); err != nil || wrapper.BasePdf == nil {
return PdfmeBasePdf{} // will get defaults
}
// Try as dimension object
var bp PdfmeBasePdf
if err := json.Unmarshal(wrapper.BasePdf, &bp); err == nil && (bp.Width > 0 || bp.Height > 0) {
return bp
}
// Try as string ("BLANK" or base64 PDF)
var s string
if err := json.Unmarshal(wrapper.BasePdf, &s); err == nil {
if s == "BLANK" || s == "" {
return PdfmeBasePdf{Width: 210, Height: 297} // A4
}
// base64 PDF — store it for use as background, default page size to A4
return PdfmeBasePdf{Width: 210, Height: 297, BackgroundPdf: s}
}
// Also check for pageConfig (ISI custom format)
var pcWrapper struct {
PageConfig struct {
Width float64 `json:"width"`
Height float64 `json:"height"`
Size string `json:"size"`
Orientation string `json:"orientation"`
} `json:"pageConfig"`
}
if err := json.Unmarshal(raw, &pcWrapper); err == nil && pcWrapper.PageConfig.Width > 0 {
w := pcWrapper.PageConfig.Width
h := pcWrapper.PageConfig.Height
// Some templates use cm instead of mm (width=21 instead of 210)
if w < 100 {
w *= 10
h *= 10
}
return PdfmeBasePdf{Width: w, Height: h}
}
return PdfmeBasePdf{} // will get defaults
}
func applyBasePdfDefaults(schema *PdfmeSchema) {
if schema.BasePdf.Width == 0 {
schema.BasePdf.Width = 210 // A4 default
}
if schema.BasePdf.Height == 0 {
schema.BasePdf.Height = 297 // A4 default
}
}
// ════════════════════════════════════════════════════
// Bulk PDF rendering — multi-page template support
// ════════════════════════════════════════════════════
// RenderBulkPDF generates a multi-page PDF from rows of data using a pdfme schema.
// For multi-page templates, each row produces N pages (one per schema page).
func RenderBulkPDF(schema *PdfmeSchema, rows []map[string]string, outputPath string) error {
pdf := gopdf.GoPdf{}
pageW := schema.BasePdf.Width * mmToPt
pageH := schema.BasePdf.Height * mmToPt
pdf.Start(gopdf.Config{
PageSize: gopdf.Rect{W: pageW, H: pageH},
})
// Reset font registry for this render
fontRegistryMu.Lock()
fontRegistry = map[string]bool{}
fontRegistryMu.Unlock()
// Load default fonts
fontPath, boldFontPath := findFonts()
fontLoaded := false
if fontPath != "" {
if err := pdf.AddTTFFont("default", fontPath); err != nil {
log.Printf("[pdf] Warning: could not load font %s: %v", fontPath, err)
} else {
fontLoaded = true
fontRegistry["default"] = true
log.Printf("[pdf] Font loaded: %s", fontPath)
}
}
if boldFontPath != "" {
if err := pdf.AddTTFFont("bold", boldFontPath); err != nil {
log.Printf("[pdf] Warning: could not load bold font %s: %v", boldFontPath, err)
} else {
fontRegistry["bold"] = true
log.Printf("[pdf] Bold font loaded: %s", boldFontPath)
}
}
if !fontLoaded {
log.Printf("[pdf] WARNING: No font loaded — text fields will be empty.")
}
// Pre-load named fonts referenced in schema fields
loadedFontNames := map[string]bool{}
for _, page := range schema.Schemas {
for _, field := range page {
if field.FontName != "" && !loadedFontNames[field.FontName] {
loadedFontNames[field.FontName] = true
loadNamedFont(&pdf, field.FontName)
}
}
}
// Import background PDF template if present (basePdf as base64 PDF)
bgTplID := -1
var bgTmpFile string
if schema.BasePdf.BackgroundPdf != "" {
bgTmpFile = decodeBackgroundPdf(schema.BasePdf.BackgroundPdf)
if bgTmpFile != "" {
bgTplID = pdf.ImportPage(bgTmpFile, 1, "/MediaBox")
log.Printf("[pdf] Background PDF imported from base64 (tplID=%d)", bgTplID)
}
}
defer func() {
if bgTmpFile != "" {
os.Remove(bgTmpFile)
}
}()
for ri, row := range rows {
if ri == 0 {
log.Printf("[pdf] === Row 0 data keys: %v", mapKeys(row))
}
// Render ALL pages from the template for each row
for pi, pageFields := range schema.Schemas {
pdf.AddPage()
// Draw background PDF on every page
if bgTplID >= 0 {
pdf.UseImportedTemplate(bgTplID, 0, 0, pageW, pageH)
}
for _, field := range pageFields {
value := resolveFieldValue(field, row)
if ri == 0 && pi == 0 {
log.Printf("[pdf] Field %q type=%s text=%q vars=%v → value=%q",
field.Name, field.Type, truncate(field.Text, 50), field.Variables, truncate(value, 60))
}
x := field.Position.X * mmToPt
y := field.Position.Y * mmToPt
w := field.Width * mmToPt
h := field.Height * mmToPt
// Apply opacity by blending colors with white (gopdf SetTransparency is unreliable).
// On white paper, blended color == transparent color visually.
if field.Opacity > 0 && field.Opacity < 1 {
op := field.Opacity
field.Color = blendColorWithWhite(field.Color, op)
field.FontColor = blendColorWithWhite(field.FontColor, op)
field.BorderColor = blendColorWithWhite(field.BorderColor, op)
field.BackgroundColor = blendColorWithWhite(field.BackgroundColor, op)
}
// Apply rotation around field center
hasRotation := field.Rotate != 0
if hasRotation {
cx := x + w/2
cy := y + h/2
pdf.Rotate(field.Rotate, cx, cy)
}
// Render background/border first (for any type)
if field.BackgroundColor != "" || float64(field.BorderWidth) > 0 {
renderFieldBackground(&pdf, field, x, y, w, h)
}
switch field.Type {
case "text", "multiVariableText":
if value == "" {
goto fieldDone
}
renderTextField(&pdf, field, value, x, y, w, h, fontLoaded)
case "qrcode":
log.Printf("[pdf] QR CASE: field=%q value=%q content=%q opacity=%.2f w=%.1f h=%.1f",
field.Name, value, field.Content, field.Opacity, w, h)
if value == "" {
value = field.Content
}
if value == "" {
value = field.Name
log.Printf("[pdf] QR using field name as placeholder: %q", value)
}
renderQRField(&pdf, field, value, x, y, w, h)
log.Printf("[pdf] QR rendered OK: field=%q", field.Name)
case "image":
renderImageField(&pdf, field, row, x, y, w, h)
case "barcode", "code128", "code39", "ean13", "ean8":
if value == "" {
goto fieldDone
}
renderBarcodeField(&pdf, value, x, y, w, h)
case "table":
renderTableField(&pdf, field, row, x, y, w, h, fontLoaded)
case "line":
renderLineField(&pdf, field, x, y, w, h)
case "rectangle":
renderRectangleField(&pdf, field, x, y, w, h)
case "ellipse":
renderEllipseField(&pdf, field, x, y, w, h)
}
fieldDone:
// Clear rotation
if hasRotation {
pdf.RotateReset()
}
}
}
}
return pdf.WritePdf(outputPath)
}
// ════════════════════════════════════════════════════
// Field rendering
// ════════════════════════════════════════════════════
func renderFieldBackground(pdf *gopdf.GoPdf, field PdfmeField, x, y, w, h float64) {
if field.BackgroundColor != "" {
r, g, b, _ := parseColor(field.BackgroundColor)
pdf.SetFillColor(r, g, b)
pdf.RectFromUpperLeftWithStyle(x, y, w, h, "F")
}
// borderWidth is in mm, SetLineWidth expects pt
bw := float64(field.BorderWidth) * mmToPt
if bw > 0 {
color := field.BorderColor
if color == "" {
color = "#000000"
}
r, g, b, _ := parseColor(color)
pdf.SetStrokeColor(r, g, b)
pdf.SetLineWidth(bw)
pdf.RectFromUpperLeftWithStyle(x, y, w, h, "D")
}
}
func renderTextField(pdf *gopdf.GoPdf, field PdfmeField, value string, x, y, w, h float64, fontLoaded bool) {
if !fontLoaded {
return
}
// Apply padding — shrink effective area
px, py, pw, ph := x, y, w, h
pad := field.Padding
if pad.Top > 0 || pad.Right > 0 || pad.Bottom > 0 || pad.Left > 0 {
padT := pad.Top * mmToPt
padR := pad.Right * mmToPt
padB := pad.Bottom * mmToPt
padL := pad.Left * mmToPt
px += padL
py += padT
pw -= padL + padR
ph -= padT + padB
if pw < 0 {
pw = 0
}
if ph < 0 {
ph = 0
}
}
// Resolve font family FIRST (needed for dynamic font size measurement)
fontFamily := "default"
boldFamily := "bold"
if field.FontName != "" {
fam, _ := loadNamedFont(pdf, field.FontName)
fontFamily = fam
boldFamily = fam + "_bold"
}
// Active font = bold or regular
activeFontFamily := fontFamily
if field.FontWeight == "bold" {
activeFontFamily = boldFamily
}
// Line height multiplier
lh := field.LineHeight
if lh <= 0 {
lh = 1.4
}
fontSize := field.FontSize
if fontSize == 0 {
fontSize = 10
}
// Dynamic font size: try to fit text within bounds (uses correct font for measuring)
if field.DynamicFontSize != nil && field.DynamicFontSize.Max > 0 {
fontSize = calculateDynamicFontSize(pdf, value, pw, ph, field.DynamicFontSize, activeFontFamily, lh)
}
// Set the active font with style flags
// gopdf style flags: Regular=0, Bold=2, Underline=4
styleFlag := gopdf.Regular
if field.Underline {
styleFlag |= gopdf.Underline
}
if styleFlag != gopdf.Regular {
if err := pdf.SetFontWithStyle(activeFontFamily, styleFlag, fontSize); err != nil {
pdf.SetFont(activeFontFamily, "", fontSize)
}
} else {
if err := pdf.SetFont(activeFontFamily, "", fontSize); err != nil {
pdf.SetFont("default", "", fontSize)
}
}
// Character spacing
if field.CharacterSpacing != 0 {
pdf.SetCharSpacing(field.CharacterSpacing)
}
// Font color
if field.FontColor != "" {
r, g, b, _ := parseColor(field.FontColor)
pdf.SetTextColor(r, g, b)
} else {
pdf.SetTextColor(0, 0, 0)
}
// lineSpacingPt: vertical space per line in PDF points
// fontSize is in points, lineHeight is a multiplier → result is in points
lineSpacingPt := fontSize * lh
// Word-wrap text into lines that fit within the available width
lines := wrapTextByWord(pdf, value, pw)
totalTextH := float64(len(lines)) * lineSpacingPt
// Vertical alignment (start position)
textY := py
switch field.VerticalAlignment {
case "middle":
if totalTextH < ph {
textY = py + (ph-totalTextH)/2
}
case "bottom":
if totalTextH < ph {
textY = py + ph - totalTextH
}
// default "top": textY = py
}
pdf.SetX(px)
pdf.SetY(textY)
for li, line := range lines {
if li > 0 {
textY += lineSpacingPt
pdf.SetY(textY)
}
// Don't render lines that overflow the padded area
if textY > py+ph {
break
}
// Horizontal alignment (start position)
lineX := px
textW, _ := pdf.MeasureTextWidth(line)
switch field.Alignment {
case "center":
if textW < pw {
lineX = px + (pw-textW)/2
}
case "right":
if textW < pw {
lineX = px + pw - textW
}
// default "left": lineX = px
}
pdf.SetX(lineX)
pdf.CellWithOption(&gopdf.Rect{W: pw, H: lineSpacingPt}, line, gopdf.CellOption{})
// Strikethrough — draw a line through the middle of the text
if field.Strikethrough {
stY := textY + lineSpacingPt*0.4
drawW := textW
if drawW > pw {
drawW = pw
}
r, g, b, _ := parseColor(field.FontColor)
pdf.SetStrokeColor(r, g, b)
pdf.SetLineWidth(fontSize * 0.05)
pdf.Line(lineX, stY, lineX+drawW, stY)
}
}
// Reset character spacing
if field.CharacterSpacing != 0 {
pdf.SetCharSpacing(0)
}
}
// wrapTextByWord splits text into lines that fit within maxWidth (in PDF points).
// Respects existing \n line breaks. Wraps by word boundary (space).
// The font must already be set on pdf before calling.
func wrapTextByWord(pdf *gopdf.GoPdf, text string, maxWidth float64) []string {
if maxWidth <= 0 {
return []string{text}
}
var result []string
paragraphs := strings.Split(text, "\n")
for _, para := range paragraphs {
if para == "" {
result = append(result, "")
continue
}
words := strings.Fields(para)
if len(words) == 0 {
result = append(result, "")
continue
}
currentLine := words[0]
for i := 1; i < len(words); i++ {
candidate := currentLine + " " + words[i]
candidateW, _ := pdf.MeasureTextWidth(candidate)
if candidateW <= maxWidth {
currentLine = candidate
} else {
result = append(result, currentLine)
currentLine = words[i]
// If a single word is wider than maxWidth, it still gets its own line
}
}
result = append(result, currentLine)
}
return result
}
// countWrappedLines counts how many lines the text would occupy after word wrapping.
// The font must already be set on pdf before calling.
func countWrappedLines(pdf *gopdf.GoPdf, text string, maxWidth float64) int {
lines := wrapTextByWord(pdf, text, maxWidth)
return len(lines)
}
// calculateDynamicFontSize finds the largest font size (between min and max) that fits text within w×h.
// fontFamily: the gopdf font name to use for measuring.
// lineHeight: the line-height multiplier from the field (e.g. 1.4).
// w, h: available space in PDF points.
func calculateDynamicFontSize(pdf *gopdf.GoPdf, text string, w, h float64, dfs *DynFontSize, fontFamily string, lineHeight float64) float64 {
if lineHeight <= 0 {
lineHeight = 1.4
}
if fontFamily == "" {
fontFamily = "default"
}
for size := dfs.Max; size >= dfs.Min; size -= 0.5 {
if err := pdf.SetFont(fontFamily, "", size); err != nil {
continue
}
lineSpacingPt := size * lineHeight
if dfs.Fit == "horizontal" {
// For horizontal fit, each paragraph must fit in one line (no wrapping)
paragraphs := strings.Split(text, "\n")
fits := true
for _, para := range paragraphs {
paraW, _ := pdf.MeasureTextWidth(para)
if paraW > w {
fits = false
break
}
}
if fits {
return size
}
} else {
// "vertical" — word-wrap and check total height fits
totalLines := countWrappedLines(pdf, text, w)
totalH := float64(totalLines) * lineSpacingPt
if totalH <= h {
return size
}
}
}
return dfs.Min
}
func renderQRField(pdf *gopdf.GoPdf, field PdfmeField, value string, x, y, w, h float64) {
log.Printf("[pdf] QR RENDER: field=%q value=%q pos=(%.1f,%.1f) size=(%.1f x %.1f)", field.Name, value, x, y, w, h)
qr, err := goqrcode.New(value, goqrcode.Medium)
if err != nil {
log.Printf("[pdf] QR error: %v", err)
return
}
qr.DisableBorder = true
bitmap := qr.Bitmap()
size := len(bitmap)
if size == 0 {
log.Printf("[pdf] QR bitmap empty for %q", value)
return
}
log.Printf("[pdf] QR bitmap size=%d modules, moduleW=%.2f moduleH=%.2f", size, w/float64(size), h/float64(size))
// Colors
fgColor := field.Color
if fgColor == "" {
fgColor = "#000000"
}
finderColor := field.QrFinderColor
if finderColor == "" {
finderColor = fgColor // same as foreground by default
}
moduleW := w / float64(size)
moduleH := h / float64(size)
// isFinderModule returns true if (row,col) is inside one of the 3 finder patterns (7x7 each).
// Finder patterns include the 7x7 area plus the 1-module separator border around them.
isFinderModule := func(row, col int) bool {
// Top-left: rows 0-6, cols 0-6
if row <= 6 && col <= 6 {
return true
}
// Top-right: rows 0-6, cols (size-7) to (size-1)
if row <= 6 && col >= size-7 {
return true
}
// Bottom-left: rows (size-7) to (size-1), cols 0-6
if row >= size-7 && col <= 6 {
return true
}
return false
}
// Draw foreground modules
fgR, fgG, fgB, _ := parseColor(fgColor)
fpR, fpG, fpB, _ := parseColor(finderColor)
for row := 0; row < size; row++ {
for col := 0; col < size; col++ {
if !bitmap[row][col] {
continue
}
mx := x + float64(col)*moduleW
my := y + float64(row)*moduleH
if isFinderModule(row, col) {
pdf.SetFillColor(fpR, fpG, fpB)
} else {
pdf.SetFillColor(fgR, fgG, fgB)
}
pdf.RectFromUpperLeftWithStyle(mx, my, moduleW, moduleH, "F")
}
}
}
func renderBarcodeField(pdf *gopdf.GoPdf, value string, x, y, w, h float64) {
var bc barcode.Barcode
var err error
bc, err = code128.Encode(value)
if err != nil {
bc, err = ean.Encode(value)
if err != nil {
log.Printf("[pdf] barcode error for %q: %v", value, err)
return
}
}
imgW := int(w / mmToPt * 10)
imgH := int(h / mmToPt * 10)
if imgW < 100 {
imgW = 100
}
if imgH < 30 {
imgH = 30
}
bc, err = barcode.Scale(bc, imgW, imgH)
if err != nil {
return
}
tmpFile, err := os.CreateTemp("", "bc-*.png")
if err != nil {
return
}
defer os.Remove(tmpFile.Name())
if err := png.Encode(tmpFile, bc); err != nil {
return
}
tmpFile.Close()
pdf.Image(tmpFile.Name(), x, y, &gopdf.Rect{W: w, H: h})
}
func renderImageField(pdf *gopdf.GoPdf, field PdfmeField, row map[string]string, x, y, w, h float64) {
// Resolve content: check row data first (for dynamic images), then static content
content := ""
// Try row variable (mapped data)
if val, ok := row[field.Name]; ok && val != "" {
content = val
}
// Try variables array
if content == "" {
for _, v := range field.Variables {
if val, ok := row[v]; ok && val != "" {
content = val
break
}
}
}
// Fallback to static content from template (base64 logos, etc.)
if content == "" {
content = field.Content
}
if content == "" {
return
}
// Handle base64 inline images (data URI or raw base64)
if strings.HasPrefix(content, "data:image/") {
localPath := saveBase64Image(content)
if localPath != "" {
defer os.Remove(localPath)
pdf.Image(localPath, x, y, &gopdf.Rect{W: w, H: h})
}
return
}
// Handle raw base64 (no data: prefix but starts with base64 chars)
if len(content) > 100 && !strings.HasPrefix(content, "http") && !strings.Contains(content[:20], "/") {
// Likely raw base64 — try to decode
localPath := saveBase64Image("data:image/png;base64," + content)
if localPath != "" {
defer os.Remove(localPath)
pdf.Image(localPath, x, y, &gopdf.Rect{W: w, H: h})
}
return
}
// Handle HTTP URLs
if strings.HasPrefix(content, "http") {
localPath := getCachedImage(content)
if localPath != "" {
pdf.Image(localPath, x, y, &gopdf.Rect{W: w, H: h})
}
return
}
// Handle local file paths
if _, err := os.Stat(content); err == nil {
pdf.Image(content, x, y, &gopdf.Rect{W: w, H: h})
}
}
func renderLineField(pdf *gopdf.GoPdf, field PdfmeField, x, y, w, h float64) {
color := field.Color
if color == "" {
color = field.FontColor
}
if color == "" {
color = "#000000"
}
r, g, b, _ := parseColor(color)
// pdfme renders lines as thin filled rectangles, not stroked paths.
// Using fill instead of stroke ensures SetTransparency applies correctly
// (gopdf transparency affects fill operations reliably).
pdf.SetFillColor(r, g, b)
pdf.RectFromUpperLeftWithStyle(x, y, w, h, "F")
}
func renderEllipseField(pdf *gopdf.GoPdf, field PdfmeField, x, y, w, h float64) {
// Fill
if field.BackgroundColor != "" {
r, g, b, _ := parseColor(field.BackgroundColor)
pdf.SetFillColor(r, g, b)
}
// Stroke — borderWidth is in mm, SetLineWidth expects pt
bw := float64(field.BorderWidth) * mmToPt
if bw > 0 {
color := field.BorderColor
if color == "" {
color = field.Color
}
if color == "" {
color = "#000000"
}
r, g, b, _ := parseColor(color)
pdf.SetStrokeColor(r, g, b)
pdf.SetLineWidth(bw)
}
// Oval uses x1,y1,x2,y2 (bounding box corners)
pdf.Oval(x, y, x+w, y+h)
}
func renderRectangleField(pdf *gopdf.GoPdf, field PdfmeField, x, y, w, h float64) {
style := ""
// pdfme uses "color" as the fill color for rectangles; also check backgroundColor
fillColor := field.Color
if fillColor == "" {