-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument.go
More file actions
414 lines (347 loc) · 9.04 KB
/
document.go
File metadata and controls
414 lines (347 loc) · 9.04 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
package pdf
import (
"bytes"
"io"
"strings"
. "github.com/tinywasm/fmt"
"github.com/tinywasm/pdf/fpdf"
)
// Document wraps the internal fpdf.Fpdf to provide a fluent API.
type Document struct {
internal *fpdf.Fpdf
logger func(message ...any)
// Resource registries
fonts map[string]string // family -> path
images map[string]string // name -> path
}
// DefaultFontPath is the default path to the Arial UTF-8 font.
const DefaultFontPath = "fonts/Arial.ttf"
// NewDocument creates a new Document instance with UTF-8 support.
func NewDocument() *Document {
d := &Document{
fonts: make(map[string]string),
images: make(map[string]string),
}
d.initIO() // initializes logger + IO depending on build tag
d.internal = fpdf.New(
fpdf.WriteFileFunc(d.writeFile),
fpdf.ReadFileFunc(d.readFile),
fpdf.FileSizeFunc(d.fileSize),
)
d.loadDefaultFont()
return d
}
// loadDefaultFont loads Arial as UTF-8 font so the default "Arial" supports unicode.
func (d *Document) loadDefaultFont() {
data, err := d.readFile(DefaultFontPath)
if err != nil {
return // fallback to built-in Arial (Latin-1 only)
}
d.internal.AddUTF8FontFromBytes("Arial", "", data)
}
// SetLog sets the logger function.
func (d *Document) SetLog(fn func(...any)) *Document {
d.logger = fn
return d
}
// Log writes a message to the logger.
func (d *Document) Log(message ...any) {
if d.logger != nil {
d.logger(message...)
}
}
// RegisterFont registers a font to be loaded.
// path should be the path to the .ttf file.
func (d *Document) RegisterFont(family, path string) *Document {
d.fonts[family] = path
return d
}
// RegisterImage registers an image to be loaded.
func (d *Document) RegisterImage(name, path string) *Document {
d.images[name] = path
return d
}
// Load loads all registered resources.
func (d *Document) Load(cb func(error)) {
for family, path := range d.fonts {
data, err := d.readFile(path)
if err != nil {
cb(err)
return
}
// We assume regular style ("") and UTF8 font for now
d.internal.AddUTF8FontFromBytes(family, "", data)
}
for name, path := range d.images {
data, err := d.readFile(path)
if err != nil {
cb(err)
return
}
ext := ""
if idx := strings.LastIndex(path, "."); idx != -1 {
ext = path[idx+1:]
}
opt := fpdf.ImageOptions{ImageType: ext, ReadDpi: true}
d.internal.RegisterImageOptionsReader(name, opt, bytes.NewReader(data))
}
cb(nil)
}
// Draw is a placeholder for consistency, though currently operations draw immediately.
func (d *Document) Draw() *Document {
return d
}
// WritePdf generates the PDF and writes it to the specified path.
func (d *Document) WritePdf(path string) error {
return d.internal.OutputFileAndClose(path)
}
// OutputTo writes the generated PDF into the provided writer.
func (d *Document) OutputTo(w io.Writer) error {
return d.internal.Output(w)
}
// --- Base Components ---
// AddText adds a text paragraph.
func (d *Document) AddText(text string) *TextComponent {
return &TextComponent{
doc: d,
text: text,
}
}
// AddHeader1 adds a level 1 header.
func (d *Document) AddHeader1(text string) *Document {
d.internal.SetFont("Arial", "B", 24)
d.internal.CellFormat(0, 10, text, "", 1, "L", false, 0, "")
d.internal.Ln(5)
return d
}
// AddHeader2 adds a level 2 header.
func (d *Document) AddHeader2(text string) *Document {
d.internal.SetFont("Arial", "B", 18)
d.internal.CellFormat(0, 10, text, "", 1, "L", false, 0, "")
d.internal.Ln(4)
return d
}
// AddHeader3 adds a level 3 header.
func (d *Document) AddHeader3(text string) *Document {
d.internal.SetFont("Arial", "B", 14)
d.internal.CellFormat(0, 10, text, "", 1, "L", false, 0, "")
d.internal.Ln(3)
return d
}
// SpaceBefore adds vertical space.
func (d *Document) SpaceBefore(u float64) *Document {
d.internal.Ln(u)
return d
}
// AddPage adds a new page.
func (d *Document) AddPage() *Document {
d.internal.AddPage()
return d
}
// AddSeparator adds a horizontal line.
func (d *Document) AddSeparator() *Document {
x := d.internal.GetX()
y := d.internal.GetY()
w, _ := d.internal.GetPageSize()
lMargin, _, rMargin, _ := d.internal.GetMargins()
width := w - lMargin - rMargin
d.internal.Line(x, y+2, x+width, y+2)
d.internal.Ln(5)
return d
}
// AddImage adds an image by name (must be registered/loaded).
func (d *Document) AddImage(name string) *ImageComponent {
return &ImageComponent{
doc: d,
name: name,
}
}
// --- Components Helpers ---
type TextComponent struct {
doc *Document
text string
align string
color [3]int
bold bool
size float64
}
func (t *TextComponent) Bold() *TextComponent {
t.bold = true
return t
}
func (t *TextComponent) AlignRight() *TextComponent {
t.align = "R"
return t
}
func (t *TextComponent) AlignCenter() *TextComponent {
t.align = "C"
return t
}
func (t *TextComponent) Justify() *TextComponent {
t.align = "J"
return t
}
func (t *TextComponent) SetColor(r, g, b int) *TextComponent {
t.color = [3]int{r, g, b}
return t
}
func (t *TextComponent) Draw() *Document {
// Apply styles
style := ""
if t.bold {
style = "B"
}
// Default font if not set
family := t.doc.internal.GetFontFamily()
if family == "" {
family = "Arial" // Fallback
}
size := t.size
if size == 0 {
pt, _ := t.doc.internal.GetFontSize()
size = pt
}
t.doc.internal.SetFont(family, style, size)
t.doc.internal.SetTextColor(t.color[0], t.color[1], t.color[2])
align := "L"
if t.align != "" {
align = t.align
}
t.doc.internal.MultiCell(0, 5, t.text, "", align, false)
// Reset text color to black (optional, but good practice)
t.doc.internal.SetTextColor(0, 0, 0)
return t.doc
}
type ImageComponent struct {
doc *Document
name string
width float64
height float64
align string
}
func (i *ImageComponent) Width(w float64) *ImageComponent {
i.width = w
return i
}
func (i *ImageComponent) Height(h float64) *ImageComponent {
i.height = h
return i
}
func (i *ImageComponent) AlignCenter() *ImageComponent {
i.align = "C"
return i
}
func (i *ImageComponent) Draw() *Document {
// Logic to center image if needed
x := i.doc.internal.GetX()
y := i.doc.internal.GetY()
if i.align == "C" {
w, _ := i.doc.internal.GetPageSize()
lMargin, _, rMargin, _ := i.doc.internal.GetMargins()
pageWidth := w - lMargin - rMargin
// We need to know image width. If 0, fpdf calculates it.
// For centering we might need to know it beforehand or let fpdf handle it?
// fpdf.Image doesn't support alignment directly.
// We can use GetImageInfo to get dimensions.
info := i.doc.internal.GetImageInfo(i.name)
if info != nil {
// Calculate aspect ratio width if i.width is set
imgW := i.width
if imgW == 0 {
imgW = info.Width() // This returns width in user units (mm/pt)
if i.height != 0 {
imgW = i.height * info.Width() / info.Height()
}
}
x = lMargin + (pageWidth-imgW)/2
}
}
i.doc.internal.Image(i.name, x, y, i.width, i.height, false, "", 0, "")
return i.doc
}
// --- Page Header/Footer ---
type PageHeader struct {
doc *Document
leftText string
rightText string
}
func (d *Document) SetPageHeader() *PageHeader {
ph := &PageHeader{doc: d}
// Register the callback immediately, but it captures the struct so updates will reflect
d.internal.SetHeaderFunc(func() {
d.internal.SetY(10) // Standard header position
d.internal.SetFont("Arial", "I", 8)
if ph.leftText != "" {
d.internal.Cell(0, 10, ph.leftText)
}
if ph.rightText != "" {
// Align right
// Calculate width? Or use CellFormat with align R?
// Cell(0) goes to right margin.
d.internal.CellFormat(0, 10, ph.rightText, "", 0, "R", false, 0, "")
}
d.internal.Ln(20) // Space after header
})
return ph
}
func (ph *PageHeader) SetLeftText(t string) *PageHeader {
ph.leftText = t
return ph
}
func (ph *PageHeader) SetRightText(t string) *PageHeader {
ph.rightText = t
return ph
}
type PageFooter struct {
doc *Document
centerText string
pageTotal bool
}
func (d *Document) SetPageFooter() *PageFooter {
pf := &PageFooter{doc: d}
d.internal.SetFooterFunc(func() {
d.internal.SetY(-15) // Standard footer position
d.internal.SetFont("Arial", "I", 8)
if pf.centerText != "" {
d.internal.CellFormat(0, 10, pf.centerText, "", 0, "C", false, 0, "")
}
if pf.pageTotal {
// We can use alias for total pages if enabled
// d.internal.AliasNbPages("") should be called somewhere
pageStr := Convert(d.internal.PageNo()).String()
d.internal.CellFormat(0, 10, pageStr+" / {nb}", "", 0, "R", false, 0, "")
}
})
return pf
}
func (pf *PageFooter) SetCenterText(t string) *PageFooter {
pf.centerText = t
return pf
}
func (pf *PageFooter) WithPageTotal(align string) *PageFooter {
pf.pageTotal = true
pf.doc.internal.AliasNbPages("")
return pf
}
func (d *Document) SetFont(family string, size float64) *Document {
d.internal.SetFont(family, "", size)
return d
}
// --- Styles ---
type Style struct {
FillColor Color
TextColor Color
Font string // "B", "I", ""
FontSize float64
}
type Color struct {
R, G, B int
}
func ColorRGB(r, g, b int) Color {
return Color{r, g, b}
}
const (
FontBold = "B"
FontItalic = "I"
FontRegular = ""
)