Repository navigation
Expand file tree
/
Copy pathpage.go
More file actions
2436 lines (2162 loc) · 61.2 KB
/
Copy pathpage.go
File metadata and controls
2436 lines (2162 loc) · 61.2 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 presspdf
import (
"fmt"
"math"
"strings"
"github.com/akkaraponph/presspdf/internal/content"
"github.com/akkaraponph/presspdf/internal/resources"
"github.com/akkaraponph/presspdf/internal/state"
)
// Page represents a single PDF page with methods for drawing text,
// shapes, images, barcodes, and other content. A Page is created by
// [Document.AddPage] and remains valid for the lifetime of the document.
//
// If automatic page breaks are enabled, a stale *Page transparently
// forwards drawing operations to the newest page.
type Page struct {
doc *Document
stream content.Stream
size PageSize
w, h float64 // page dimensions in user units
// cursor position in user units
x, y float64
// page-local font state
fontFamily string
fontStyle string
fontSizePt float64
fontEntry *resources.FontEntry
// next is a forwarding pointer set by auto page break. When a page
// break occurs, the old page's next points to the new page so that
// stale *Page references transparently follow to the active page.
next *Page
// links holds hyperlink annotations for this page.
links []linkAnnotation
// page boxes (optional: TrimBox, CropBox, BleedBox, ArtBox) in PDF points
pageBoxes map[string][4]float64
// file attachment annotations on this page
attachAnnotations []attachAnnotation
// tagged PDF (structure tree)
nextMCID int // next marked content ID for this page
structElements []*structElement // elements on this page
currentTag *structElement // current open tag (for nesting)
}
// attachAnnotation represents a file attachment annotation on a page.
type attachAnnotation struct {
attachment Attachment
x, y, w, h float64 // rect in user units
}
// linkAnnotation represents a hyperlink annotation on a page.
type linkAnnotation struct {
x, y, w, h float64 // rect in user units
url string // non-empty for URL links
anchor string // non-empty for internal links
linkID int // >0 for integer-based internal links (set via Link)
}
// linkDest stores the target for an integer-based internal link.
type linkDest struct {
page *Page // target page (nil until SetLink is called)
y float64 // Y position in user units
}
// --- Page break support ---
// active follows the forwarding chain to the current active page.
// When auto page break creates a new page, the old page's next field
// points to it. This lets stale *Page references seamlessly reach the
// latest page.
func (p *Page) active() *Page {
for p.next != nil {
p = p.next
}
return p
}
// checkPageBreak creates a new page if content of height h would overflow
// past the bottom margin. Returns the page to draw on (p itself or the
// newly created page).
func (p *Page) checkPageBreak(h float64) *Page {
d := p.doc
if !d.autoPageBreak || d.inHeader || d.inFooter {
return p
}
// Custom accept-page-break function: if it returns false, suppress break.
if d.acceptPageBreakFunc != nil && !d.acceptPageBreakFunc() {
return p
}
// Would content overflow?
if p.y+h <= p.h-d.bMargin {
return p
}
// If we're already at the top margin (fresh page), allow overflow to
// prevent an infinite loop when a single cell is taller than the page.
if p.y <= d.tMargin {
return p
}
np := d.AddPage(p.size)
p.next = np
return np
}
// PageBreakTrigger returns the Y position (in user units) at which an
// automatic page break would be triggered.
func (p *Page) PageBreakTrigger() float64 {
return p.h - p.doc.bMargin
}
// --- Text methods ---
// TextAt draws text at the given position (in user units, top-left origin).
func (p *Page) TextAt(x, y float64, text string) {
p = p.active()
if p.doc.err != nil {
return
}
fe := p.effectiveFontEntry()
if fe == nil {
p.doc.err = fmt.Errorf("TextAt: no font set")
return
}
k := p.doc.k
xPt := state.ToPointsX(x, k)
// Position text baseline: y + 0.7 * fontSize (approximate ascender)
fontSize := p.effectiveFontSizePt() / k
yPt := state.ToPointsY(y+0.7*fontSize, p.h, k)
// Handle text color and decoration
d := p.doc
tc := d.textColor
needDeco := d.underline || d.strikethrough
needState := !tc.IsBlack() || needDeco
if needState {
p.stream.SaveState()
p.stream.SetFillColorRGB(tc.R, tc.G, tc.B)
}
p.stream.BeginText()
p.stream.SetFont("F"+fe.Index, p.effectiveFontSizePt())
p.stream.MoveText(xPt, yPt)
p.emitText(fe, text)
p.stream.EndText()
if d.underline {
p.drawTextDecoration(x, y+0.7*fontSize, text)
}
if d.strikethrough {
p.drawTextDecoration(x, y+0.3*fontSize, text)
}
if needState {
p.stream.RestoreState()
}
}
// SetFont sets the font for this page.
func (p *Page) SetFont(family, style string, size float64) {
p = p.active()
if p.doc.err != nil {
return
}
fe, err := p.doc.fonts.Register(family, style)
if err != nil {
p.doc.err = fmt.Errorf("Page.SetFont: %w", err)
return
}
p.fontFamily = family
p.fontStyle = style
p.fontSizePt = size
p.fontEntry = fe
p.applyFont(fe, size)
}
// SetFontSize changes the font size for this page without changing the family or style.
func (p *Page) SetFontSize(size float64) {
p = p.active()
if p.doc.err != nil {
return
}
fe := p.effectiveFontEntry()
if fe == nil {
p.doc.err = fmt.Errorf("Page.SetFontSize: no font set")
return
}
p.fontSizePt = size
p.applyFont(fe, size)
}
// SetFontStyle changes the font style for this page (e.g. "B", "I", "BI", "")
// without changing the family or size. The font family+style must already be registered.
func (p *Page) SetFontStyle(style string) {
p = p.active()
if p.doc.err != nil {
return
}
family := p.fontFamily
if family == "" {
family = p.doc.fontFamily
}
if family == "" {
p.doc.err = fmt.Errorf("Page.SetFontStyle: no font set")
return
}
fe, ok := p.doc.fonts.Get(family, style)
if !ok {
var err error
fe, err = p.doc.fonts.Register(family, style)
if err != nil {
p.doc.err = fmt.Errorf("Page.SetFontStyle: %w", err)
return
}
}
p.fontFamily = family
p.fontStyle = style
p.fontEntry = fe
p.applyFont(fe, p.effectiveFontSizePt())
}
// GetFontFamily returns the effective font family for this page.
func (p *Page) GetFontFamily() string {
p = p.active()
if p.fontFamily != "" {
return p.fontFamily
}
return p.doc.fontFamily
}
// GetFontStyle returns the effective font style for this page.
func (p *Page) GetFontStyle() string {
p = p.active()
if p.fontEntry != nil {
return p.fontStyle
}
return p.doc.fontStyle
}
// GetFontSize returns the effective font size in points for this page.
func (p *Page) GetFontSize() float64 {
return p.active().effectiveFontSizePt()
}
// GetStringWidth returns the width of s in user units using the current font.
func (p *Page) GetStringWidth(s string) float64 {
p = p.active()
fe := p.effectiveFontEntry()
if fe == nil {
return 0
}
var w int
if fe.Type == "TTF" {
w = resources.StringWidthUTF8(fe, s)
} else {
w = resources.StringWidth(fe, s)
}
return float64(w) * p.effectiveFontSizePt() / 1000.0 / p.doc.k
}
// --- Drawing methods ---
// Line draws a line segment from (x1,y1) to (x2,y2) in user units.
func (p *Page) Line(x1, y1, x2, y2 float64) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.MoveTo(
state.ToPointsX(x1, k),
state.ToPointsY(y1, p.h, k),
)
p.stream.LineTo(
state.ToPointsX(x2, k),
state.ToPointsY(y2, p.h, k),
)
p.stream.Stroke()
}
// Rect draws a rectangle. style: "D" (draw/stroke), "F" (fill), "DF" or "FD" (both).
func (p *Page) Rect(x, y, w, h float64, style string) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.Rect(
state.ToPointsX(x, k),
state.ToPointsY(y+h, p.h, k), // bottom-left corner in PDF coords
w*k,
h*k,
)
style = strings.ToUpper(style)
switch style {
case "F":
p.stream.Fill()
case "DF", "FD":
p.stream.FillStroke()
default: // "D" or ""
p.stream.Stroke()
}
}
// RoundedRect draws a rectangle with rounded corners.
// r is the corner radius in user units. If r exceeds half the width or
// height it is clamped automatically.
// style: "D" (stroke), "F" (fill), "DF" or "FD" (fill and stroke).
func (p *Page) RoundedRect(x, y, w, h, r float64, style string) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.RoundedRect(
state.ToPointsX(x, k),
state.ToPointsY(y+h, p.h, k), // bottom-left corner in PDF coords
w*k,
h*k,
r*k,
)
style = strings.ToUpper(style)
switch style {
case "F":
p.stream.Fill()
case "DF", "FD":
p.stream.FillStroke()
default: // "D" or ""
p.stream.Stroke()
}
}
// RoundedRectExt draws a rectangle with per-corner radii.
// rTL, rTR, rBR, rBL are the radii for top-left, top-right, bottom-right,
// and bottom-left corners respectively. A zero radius produces a square corner.
// style: "D" (stroke), "F" (fill), "DF" or "FD" (fill and stroke).
func (p *Page) RoundedRectExt(x, y, w, h, rTL, rTR, rBR, rBL float64, style string) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.RoundedRectExt(
state.ToPointsX(x, k),
state.ToPointsY(y+h, p.h, k),
w*k, h*k,
rTL*k, rTR*k, rBR*k, rBL*k,
)
p.paintStyle(style)
}
// Circle draws a circle centered at (x, y) with radius r in user units.
// style: "D" (stroke), "F" (fill), "DF" or "FD" (fill and stroke).
func (p *Page) Circle(x, y, r float64, style string) {
p.Ellipse(x, y, r, r, style)
}
// Ellipse draws an ellipse centered at (x, y) with horizontal radius rx
// and vertical radius ry in user units.
// style: "D" (stroke), "F" (fill), "DF" or "FD" (fill and stroke).
func (p *Page) Ellipse(x, y, rx, ry float64, style string) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
// Centre in PDF points.
cx := state.ToPointsX(x, k)
cy := state.ToPointsY(y, p.h, k)
rxPt := rx * k
ryPt := ry * k
// Approximate a full ellipse with 4 cubic Bézier arcs.
// κ = 4/3 * (√2 − 1) ≈ 0.5522847498
const kappa = 0.5522847498
kx := rxPt * kappa
ky := ryPt * kappa
// Start at the rightmost point.
p.stream.MoveTo(cx+rxPt, cy)
// Top-right quadrant (0° → 90° in PDF coords, i.e. rightward → upward).
p.stream.CurveTo(cx+rxPt, cy+ky, cx+kx, cy+ryPt, cx, cy+ryPt)
// Top-left quadrant.
p.stream.CurveTo(cx-kx, cy+ryPt, cx-rxPt, cy+ky, cx-rxPt, cy)
// Bottom-left quadrant.
p.stream.CurveTo(cx-rxPt, cy-ky, cx-kx, cy-ryPt, cx, cy-ryPt)
// Bottom-right quadrant.
p.stream.CurveTo(cx+kx, cy-ryPt, cx+rxPt, cy-ky, cx+rxPt, cy)
style = strings.ToUpper(style)
switch style {
case "F":
p.stream.Fill()
case "DF", "FD":
p.stream.FillStroke()
default:
p.stream.Stroke()
}
}
// EllipseRotated draws a rotated ellipse centered at (x, y) with horizontal
// radius rx, vertical radius ry, and rotation degRotate (degrees, clockwise).
// style: "D" (stroke), "F" (fill), "DF" or "FD" (fill and stroke).
func (p *Page) EllipseRotated(x, y, rx, ry, degRotate float64, style string) {
if degRotate == 0 {
p.Ellipse(x, y, rx, ry, style)
return
}
p = p.active()
if p.doc.err != nil {
return
}
p.stream.SaveState()
k := p.doc.k
cx := state.ToPointsX(x, k)
cy := state.ToPointsY(y, p.h, k)
// Apply rotation around the centre point.
rad := -degRotate * math.Pi / 180.0
cosA := math.Cos(rad)
sinA := math.Sin(rad)
e := cx*(1-cosA) + cy*sinA
f := cy*(1-cosA) - cx*sinA
p.stream.ConcatMatrix(cosA, sinA, -sinA, cosA, e, f)
// Draw the unrotated ellipse at the centre.
rxPt := rx * k
ryPt := ry * k
const kappa = 0.5522847498
kx := rxPt * kappa
ky := ryPt * kappa
p.stream.MoveTo(cx+rxPt, cy)
p.stream.CurveTo(cx+rxPt, cy+ky, cx+kx, cy+ryPt, cx, cy+ryPt)
p.stream.CurveTo(cx-kx, cy+ryPt, cx-rxPt, cy+ky, cx-rxPt, cy)
p.stream.CurveTo(cx-rxPt, cy-ky, cx-kx, cy-ryPt, cx, cy-ryPt)
p.stream.CurveTo(cx+kx, cy-ryPt, cx+rxPt, cy-ky, cx+rxPt, cy)
p.paintStyle(style)
p.stream.RestoreState()
}
// Arc draws an elliptical arc centered at (x, y) with horizontal radius rx
// and vertical radius ry, from startDeg to endDeg (both in degrees,
// counterclockwise from 3-o'clock). style: "D" (stroke), "F" (fill),
// "DF"/"FD" (fill and stroke). When filled, the arc is closed as a pie
// slice (lines from endpoints to center).
func (p *Page) Arc(x, y, rx, ry, startDeg, endDeg float64, style string) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
cx := state.ToPointsX(x, k)
cy := state.ToPointsY(y, p.h, k)
rxPt := rx * k
ryPt := ry * k
// In PDF coordinates, Y increases upward but our user angles assume
// counterclockwise from 3-o'clock which maps naturally.
p.arcPath(cx, cy, rxPt, ryPt, startDeg, endDeg)
style = strings.ToUpper(style)
needClose := style == "F" || style == "DF" || style == "FD"
if needClose {
// Close as pie slice: line to center and back.
p.stream.LineTo(cx, cy)
p.stream.ClosePath()
}
switch style {
case "F":
p.stream.Fill()
case "DF", "FD":
p.stream.FillStroke()
default:
p.stream.Stroke()
}
}
// arcPath emits Bézier curves approximating an elliptical arc.
// All coordinates are in PDF points. Angles are in degrees.
func (p *Page) arcPath(cx, cy, rx, ry, startDeg, endDeg float64) {
// Normalize so startDeg < endDeg
for endDeg < startDeg {
endDeg += 360
}
// Split into segments of at most 90° each for Bézier accuracy.
totalAngle := endDeg - startDeg
nSegs := int(math.Ceil(totalAngle / 90.0))
if nSegs < 1 {
nSegs = 1
}
segAngle := totalAngle / float64(nSegs) * math.Pi / 180.0
angle := startDeg * math.Pi / 180.0
// First point
startX := cx + rx*math.Cos(angle)
startY := cy + ry*math.Sin(angle)
p.stream.MoveTo(startX, startY)
for i := 0; i < nSegs; i++ {
a1 := angle
a2 := angle + segAngle
p.arcSegment(cx, cy, rx, ry, a1, a2)
angle = a2
}
}
// arcSegment emits a single cubic Bézier curve approximating an arc
// from angle a1 to a2 (radians) on an ellipse centered at (cx,cy).
func (p *Page) arcSegment(cx, cy, rx, ry, a1, a2 float64) {
// Bézier approximation for a circular arc, scaled to ellipse.
// alpha = 4/3 * tan((a2-a1)/4)
da := a2 - a1
alpha := 4.0 / 3.0 * math.Tan(da/4.0)
cos1 := math.Cos(a1)
sin1 := math.Sin(a1)
cos2 := math.Cos(a2)
sin2 := math.Sin(a2)
// Control point 1
cp1x := cx + rx*(cos1-alpha*sin1)
cp1y := cy + ry*(sin1+alpha*cos1)
// Control point 2
cp2x := cx + rx*(cos2+alpha*sin2)
cp2y := cy + ry*(sin2-alpha*cos2)
// End point
endX := cx + rx*cos2
endY := cy + ry*sin2
p.stream.CurveTo(cp1x, cp1y, cp2x, cp2y, endX, endY)
}
// --- Path building API ---
//
// These methods construct a path incrementally without painting it.
// Call DrawPath to actually stroke, fill, or both.
// Point represents a 2D point in user-unit coordinates.
type Point struct {
X, Y float64
}
// Pt is a convenience constructor for Point.
func Pt(x, y float64) Point { return Point{X: x, Y: y} }
// MoveTo begins a new subpath at the given point (user units, top-left origin).
// This sets the current point without drawing anything.
func (p *Page) MoveTo(x, y float64) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.MoveTo(state.ToPointsX(x, k), state.ToPointsY(y, p.h, k))
}
// LineTo appends a straight line segment from the current point to (x, y).
func (p *Page) LineTo(x, y float64) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.LineTo(state.ToPointsX(x, k), state.ToPointsY(y, p.h, k))
}
// CurveTo appends a cubic Bézier curve from the current point to (x, y)
// using control points (cx0, cy0) and (cx1, cy1).
func (p *Page) CurveTo(cx0, cy0, cx1, cy1, x, y float64) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.CurveTo(
state.ToPointsX(cx0, k), state.ToPointsY(cy0, p.h, k),
state.ToPointsX(cx1, k), state.ToPointsY(cy1, p.h, k),
state.ToPointsX(x, k), state.ToPointsY(y, p.h, k),
)
}
// CurveToQuadratic appends a quadratic Bézier curve from the current point
// to (x, y) using control point (cx, cy). Internally this uses the PDF v
// operator (cubic Bézier with the first control point at the current point).
func (p *Page) CurveToQuadratic(cx, cy, x, y float64) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.CurveToV(
state.ToPointsX(cx, k), state.ToPointsY(cy, p.h, k),
state.ToPointsX(x, k), state.ToPointsY(y, p.h, k),
)
}
// ClosePath closes the current subpath by drawing a straight line back
// to the starting point (the most recent MoveTo).
func (p *Page) ClosePath() {
p = p.active()
if p.doc.err != nil {
return
}
p.stream.ClosePath()
}
// DrawPath paints the current path using the given style string.
//
// High-level styles: "D" (stroke), "F" (fill), "DF"/"FD" (fill and stroke).
//
// PDF path-painting operators are also accepted directly:
// "S" stroke, "s" close and stroke, "f" fill (nonzero winding),
// "f*" fill (even-odd), "B" fill and stroke (nonzero), "B*" fill and
// stroke (even-odd), "b" close+fill+stroke (nonzero),
// "b*" close+fill+stroke (even-odd).
func (p *Page) DrawPath(style string) {
p = p.active()
if p.doc.err != nil {
return
}
switch strings.ToUpper(style) {
case "F":
p.stream.Fill()
case "F*":
p.stream.FillEvenOdd()
case "DF", "FD":
p.stream.FillStroke()
case "DF*", "FD*":
p.stream.FillStrokeEvenOdd()
default:
// Check lowercase operators that shouldn't be uppercased.
switch style {
case "s":
p.stream.CloseAndStroke()
case "b":
p.stream.CloseFillStroke()
case "b*":
p.stream.CloseFillStrokeEvenOdd()
default:
// "D", "S", "", or anything else → stroke.
p.stream.Stroke()
}
}
}
// --- Standalone curve methods ---
// Curve draws a quadratic Bézier curve from (x0, y0) to (x1, y1) with
// control point (cx, cy). style: "D" (stroke), "F" (fill), "DF"/"FD" (both).
func (p *Page) Curve(x0, y0, cx, cy, x1, y1 float64, style string) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.MoveTo(state.ToPointsX(x0, k), state.ToPointsY(y0, p.h, k))
p.stream.CurveToV(
state.ToPointsX(cx, k), state.ToPointsY(cy, p.h, k),
state.ToPointsX(x1, k), state.ToPointsY(y1, p.h, k),
)
p.paintStyle(style)
}
// CurveCubic draws a cubic Bézier curve from (x0, y0) to (x1, y1)
// with control points (cx0, cy0) and (cx1, cy1).
// style: "D" (stroke), "F" (fill), "DF"/"FD" (both).
func (p *Page) CurveCubic(x0, y0, cx0, cy0, cx1, cy1, x1, y1 float64, style string) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
p.stream.MoveTo(state.ToPointsX(x0, k), state.ToPointsY(y0, p.h, k))
p.stream.CurveTo(
state.ToPointsX(cx0, k), state.ToPointsY(cy0, p.h, k),
state.ToPointsX(cx1, k), state.ToPointsY(cy1, p.h, k),
state.ToPointsX(x1, k), state.ToPointsY(y1, p.h, k),
)
p.paintStyle(style)
}
// --- Polygon and Beziergon ---
// Polygon draws a closed polygon through the given points.
// At least 3 points are required; fewer is a no-op.
// style: "D" (stroke), "F" (fill), "DF"/"FD" (both).
func (p *Page) Polygon(points []Point, style string) {
p = p.active()
if p.doc.err != nil || len(points) < 3 {
return
}
k := p.doc.k
p.stream.MoveTo(
state.ToPointsX(points[0].X, k),
state.ToPointsY(points[0].Y, p.h, k),
)
for _, pt := range points[1:] {
p.stream.LineTo(
state.ToPointsX(pt.X, k),
state.ToPointsY(pt.Y, p.h, k),
)
}
// Close back to the first point.
p.stream.LineTo(
state.ToPointsX(points[0].X, k),
state.ToPointsY(points[0].Y, p.h, k),
)
p.paintStyle(style)
}
// Beziergon draws a closed figure defined by cubic Bézier curve segments.
// The first point is the starting point. Each subsequent group of three
// points (control1, control2, endpoint) defines one curve segment.
// Therefore len(points) must be 1 + 3*n where n >= 1.
// style: "D" (stroke), "F" (fill), "DF"/"FD" (both).
func (p *Page) Beziergon(points []Point, style string) {
p = p.active()
if p.doc.err != nil || len(points) < 4 {
return
}
k := p.doc.k
p.stream.MoveTo(
state.ToPointsX(points[0].X, k),
state.ToPointsY(points[0].Y, p.h, k),
)
pts := points[1:]
for len(pts) >= 3 {
p.stream.CurveTo(
state.ToPointsX(pts[0].X, k), state.ToPointsY(pts[0].Y, p.h, k),
state.ToPointsX(pts[1].X, k), state.ToPointsY(pts[1].Y, p.h, k),
state.ToPointsX(pts[2].X, k), state.ToPointsY(pts[2].Y, p.h, k),
)
pts = pts[3:]
}
p.paintStyle(style)
}
// --- ArcTo (path-based arc) ---
// ArcTo appends an elliptical arc to the current path. The arc is centered
// at (x, y) with horizontal radius rx and vertical radius ry. degRotate
// rotates the ellipse. degStart and degEnd define the arc sweep in degrees,
// measured counter-clockwise from the 3 o'clock position. If the arc's
// start point differs from the current path point, a connecting line is drawn.
//
// Unlike Arc, this method does NOT paint the path — call DrawPath afterwards.
func (p *Page) ArcTo(x, y, rx, ry, degRotate, degStart, degEnd float64) {
p = p.active()
if p.doc.err != nil {
return
}
k := p.doc.k
cx := state.ToPointsX(x, k)
cy := state.ToPointsY(y, p.h, k)
rxPt := rx * k
ryPt := ry * k
// Normalize so degStart < degEnd.
for degEnd < degStart {
degEnd += 360
}
totalAngle := degEnd - degStart
nSegs := int(math.Ceil(totalAngle / 60.0))
if nSegs < 2 {
nSegs = 2
}
segAngle := totalAngle / float64(nSegs) * math.Pi / 180.0
if degRotate != 0 {
a := -degRotate * math.Pi / 180.0
p.stream.SaveState()
p.stream.ConcatMatrix(
math.Cos(a), -math.Sin(a),
math.Sin(a), math.Cos(a),
cx, cy,
)
cx = 0
cy = 0
}
angle := degStart * math.Pi / 180.0
dtm := segAngle / 3.0
// Compute the first point on the arc.
a0 := cx + rxPt*math.Cos(angle)
b0 := cy + ryPt*math.Sin(angle)
c0 := -rxPt * math.Sin(angle)
d0 := ryPt * math.Cos(angle)
// Draw a line to the start of the arc (connects to existing path).
p.stream.LineTo(a0, b0)
for j := 1; j <= nSegs; j++ {
t := (float64(j)*segAngle + degStart*math.Pi/180.0)
a1 := cx + rxPt*math.Cos(t)
b1 := cy + ryPt*math.Sin(t)
c1 := -rxPt * math.Sin(t)
d1 := ryPt * math.Cos(t)
p.stream.CurveTo(
a0+(c0*dtm), b0+(d0*dtm),
a1-(c1*dtm), b1-(d1*dtm),
a1, b1,
)
a0, b0, c0, d0 = a1, b1, c1, d1
}
if degRotate != 0 {
p.stream.RestoreState()
}
}
// paintStyle is a helper that emits the appropriate path-painting operator.
func (p *Page) paintStyle(style string) {
style = strings.ToUpper(style)
switch style {
case "F":
p.stream.Fill()
case "DF", "FD":
p.stream.FillStroke()
default:
p.stream.Stroke()
}
}
// SetDashPattern sets the line dash pattern for subsequent strokes.
// dashArray contains alternating dash and gap lengths in user units.
// phase is the offset into the pattern at which the stroke begins.
// Call with an empty dashArray (or nil) and phase 0 to restore solid lines.
func (p *Page) SetDashPattern(dashArray []float64, phase float64) {
p = p.active()
k := p.doc.k
pts := make([]float64, len(dashArray))
for i, v := range dashArray {
pts[i] = v * k
}
p.stream.SetDash(pts, phase*k)
}
// DrawImageRect draws a registered image at (x, y) with the given width and height.
func (p *Page) DrawImageRect(name string, x, y, w, h float64) {
p = p.active()
if p.doc.err != nil {
return
}
entry, ok := p.doc.images.Get(name)
if !ok {
p.doc.err = fmt.Errorf("DrawImageRect: image %q not registered", name)
return
}
k := p.doc.k
wPt := w * k
hPt := h * k
xPt := state.ToPointsX(x, k)
yPt := state.ToPointsY(y+h, p.h, k) // bottom-left of image in PDF coords
p.stream.DrawImage("Im"+entry.Name, wPt, 0, 0, hPt, xPt, yPt)
}
// DrawImage draws a registered image with flow support.
// If flow is true, the image is positioned at the current cursor Y (ignoring
// the y parameter), a page break is triggered if needed, and the cursor
// advances past the image. If flow is false, behavior is identical to
// DrawImageRect.
func (p *Page) DrawImage(name string, x, y, w, h float64, flow bool) {
p = p.active()
if p.doc.err != nil {
return
}
if flow {
p = p.checkPageBreak(h)
y = p.y
p.DrawImageRect(name, x, y, w, h)
p.y += h
} else {
p.DrawImageRect(name, x, y, w, h)
}
}
// SetHomeXY resets the cursor to the top-left position (left margin, top margin).
func (p *Page) SetHomeXY() {
p = p.active()
p.x = p.doc.lMargin
p.y = p.doc.tMargin
}
// RawWriteStr writes a raw PDF content stream string to the page.
// The string is written as-is with no coordinate conversion or escaping.
// Use this only when you know exactly what PDF operators to emit.
func (p *Page) RawWriteStr(s string) {
p = p.active()
p.stream.Raw(s)
}
// RawWriteBuf writes raw PDF content stream bytes to the page.
func (p *Page) RawWriteBuf(data []byte) {
p = p.active()
p.stream.Raw(string(data))
}
// --- Transforms ---
// TransformBegin saves the graphics state. Must be paired with
// TransformEnd after the transformed drawing operations.
func (p *Page) TransformBegin() {
p = p.active()
p.stream.SaveState()
}
// TransformEnd restores the graphics state saved by TransformBegin.
func (p *Page) TransformEnd() {
p = p.active()
p.stream.RestoreState()
}
// Rotate applies a counterclockwise rotation of angleDeg degrees around
// the point (x, y) in user units. Must be called between TransformBegin
// and TransformEnd.
func (p *Page) Rotate(angleDeg, x, y float64) {
p = p.active()
k := p.doc.k
cx := state.ToPointsX(x, k)
cy := state.ToPointsY(y, p.h, k)
rad := angleDeg * math.Pi / 180.0
cosA := math.Cos(rad)
sinA := math.Sin(rad)
a := cosA
b := sinA
c := -sinA
d := cosA
e := cx*(1-cosA) + cy*sinA
f := cy*(1-cosA) - cx*sinA
p.stream.ConcatMatrix(a, b, c, d, e, f)
}
// Scale applies a scaling transform with factors sx and sy around the
// point (x, y) in user units. Must be called between TransformBegin
// and TransformEnd.
func (p *Page) Scale(sx, sy, x, y float64) {
p = p.active()
k := p.doc.k
cx := state.ToPointsX(x, k)
cy := state.ToPointsY(y, p.h, k)
a := sx
b := 0.0
c := 0.0
d := sy
e := cx * (1 - sx)
f := cy * (1 - sy)
p.stream.ConcatMatrix(a, b, c, d, e, f)
}
// Skew applies a skew transform. angleX is the horizontal shear angle
// and angleY is the vertical shear angle (both in degrees), around the
// point (x, y) in user units. Must be called between TransformBegin
// and TransformEnd.
func (p *Page) Skew(angleX, angleY, x, y float64) {
p = p.active()
k := p.doc.k
cx := state.ToPointsX(x, k)
cy := state.ToPointsY(y, p.h, k)
tanX := math.Tan(angleX * math.Pi / 180.0)
tanY := math.Tan(angleY * math.Pi / 180.0)
a := 1.0
b := tanY
c := tanX
d := 1.0
e := -cy * tanX
f := -cx * tanY
p.stream.ConcatMatrix(a, b, c, d, e, f)
}
// Translate applies a translation by (tx, ty) user units. Positive tx
// moves right, positive ty moves down. Must be called between