-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.go
More file actions
625 lines (541 loc) · 16.1 KB
/
Copy pathtable.go
File metadata and controls
625 lines (541 loc) · 16.1 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
package presspdf
import "strings"
// CellStyle configures the visual appearance of table cells.
// Unset color fields default to black (0,0,0).
type CellStyle struct {
FontFamily string // font family (e.g. "helvetica")
FontStyle string // font style ("", "B", "I", "BI")
FontSize float64 // font size in points
TextColor [3]int // text RGB (0-255)
FillColor [3]int // background fill RGB (0-255)
DrawColor [3]int // border/stroke RGB (0-255)
Fill bool // whether to fill the cell background
}
// TableCell represents a cell in a complex table row.
// Use with AddRow/AddHeader for colspan, rowspan, multi-line, and per-cell styling.
type TableCell struct {
Text string // cell text content (supports \n for explicit line breaks)
ColSpan int // columns to span (default 1)
RowSpan int // rows to span (default 1)
Align string // "L", "C", "R" — overrides column default
Style *CellStyle // per-cell style override (nil = use default)
}
// Table is a high-level helper for drawing tabular data.
// It manages column layout, header/body styling, alternating row colors,
// and automatic header repetition on page breaks.
//
// Two APIs are available:
//
// Simple (immediate drawing):
//
// tbl.Header("#", "Name", "Amount")
// tbl.Row("1", "Item", "100")
//
// Complex (buffered, supports colspan/rowspan/multi-line):
//
// tbl.AddHeader(presspdf.TableCell{Text: "Report", ColSpan: 3, Align: "C"})
// tbl.AddRow(presspdf.TableCell{Text: "1", RowSpan: 2}, presspdf.TableCell{Text: "Item"}, presspdf.TableCell{Text: "100"})
// tbl.AddRow(presspdf.TableCell{Text: "Sub-item"}, presspdf.TableCell{Text: "50"})
// tbl.Render()
type Table struct {
doc *Document
page *Page
x float64 // left edge of the table
widths []float64 // column widths in user units
aligns []string // per-column alignment ("L", "C", "R")
rowH float64 // row height in user units (also line height for multi-line)
border string // border style ("1", "LR", "", etc.)
// Header
header []string
repeatHeader bool
headerStyle CellStyle
hasHeaderStyle bool
// Body
bodyStyle CellStyle
hasBodyStyle bool
// Alternating row fills: [even, odd]
altFills [2][3]int
hasAlt bool
rowIndex int
// Complex table support (buffered rendering)
buffered []bufferedRow
headerCount int // number of header rows in buffered
cellPadding float64 // inner cell padding in user units
lineH float64 // line height for multi-line text (0 = use rowH)
}
// bufferedRow stores a row for deferred rendering.
type bufferedRow struct {
cells []TableCell
isHeader bool
}
// cellPlacement tracks which TableCell occupies each grid position.
type cellPlacement struct {
cell TableCell
originR int // row index of the cell's origin
originC int // column index of the cell's origin
}
// NewTable creates a table helper bound to the given document and page.
// The table's left edge is set to the page's current X position.
// Defaults: row height 8, border "1", header repetition on.
func NewTable(doc *Document, page *Page) *Table {
return &Table{
doc: doc,
page: page,
x: page.GetX(),
rowH: 8,
border: "1",
repeatHeader: true,
}
}
// SetWidths sets column widths in user units.
func (t *Table) SetWidths(widths ...float64) { t.widths = widths }
// SetAligns sets per-column text alignment ("L", "C", or "R").
// Columns without an alignment default to "L".
func (t *Table) SetAligns(aligns ...string) { t.aligns = aligns }
// SetRowHeight sets the height of each row in user units.
func (t *Table) SetRowHeight(h float64) { t.rowH = h }
// SetBorder sets the border style for all cells (e.g. "1", "LR", "").
func (t *Table) SetBorder(border string) { t.border = border }
// SetHeaderStyle sets the visual style for the header row.
func (t *Table) SetHeaderStyle(s CellStyle) {
t.headerStyle = s
t.hasHeaderStyle = true
}
// SetBodyStyle sets the visual style for body rows.
func (t *Table) SetBodyStyle(s CellStyle) {
t.bodyStyle = s
t.hasBodyStyle = true
}
// SetAlternateRows enables alternating row fill colors.
// even is used for rows 0, 2, 4, … and odd for rows 1, 3, 5, …
func (t *Table) SetAlternateRows(even, odd [3]int) {
t.altFills = [2][3]int{even, odd}
t.hasAlt = true
}
// SetRepeatHeader controls whether the header is redrawn after page breaks.
// Default is true.
func (t *Table) SetRepeatHeader(repeat bool) { t.repeatHeader = repeat }
// SetCellPadding sets inner cell padding in user units for complex tables.
// Applies to cells rendered via AddRow/AddHeader + Render.
func (t *Table) SetCellPadding(padding float64) { t.cellPadding = padding }
// SetLineHeight sets the line height for multi-line text within cells.
// If not set, defaults to the row height.
func (t *Table) SetLineHeight(h float64) { t.lineH = h }
// ---- Simple API (immediate drawing) ----
// Header draws the header row and stores the values for repetition on
// subsequent pages.
func (t *Table) Header(values ...string) {
t.header = values
t.drawHeader()
}
// Row draws a body row. When auto page break is enabled and the row would
// overflow, a new page is created and the header is repeated (if enabled).
func (t *Table) Row(values ...string) {
p := t.page.active()
d := t.doc
// Table-level page break: detect overflow and handle header repetition
// before drawing the row.
if d.autoPageBreak && !d.inHeader && !d.inFooter {
if p.y+t.rowH > p.h-d.bMargin && p.y > d.tMargin {
np := d.AddPage(p.size)
p.next = np
if t.repeatHeader && t.header != nil {
t.drawHeader()
}
}
}
// Apply body style.
if t.hasBodyStyle {
t.applyStyle(t.bodyStyle)
}
// Alternating row fill.
fill := false
if t.hasAlt {
fc := t.altFills[t.rowIndex%2]
d.SetFillColor(fc[0], fc[1], fc[2])
fill = true
} else if t.hasBodyStyle && t.bodyStyle.Fill {
fill = true
}
t.drawCells(values, fill)
t.rowIndex++
}
// drawHeader draws the header row with its styling, then re-applies
// body styling for subsequent rows.
func (t *Table) drawHeader() {
if t.hasHeaderStyle {
t.applyStyle(t.headerStyle)
}
fill := t.hasHeaderStyle && t.headerStyle.Fill
t.drawCells(t.header, fill)
if t.hasBodyStyle {
t.applyStyle(t.bodyStyle)
}
}
// drawCells draws a single row of cells using the current document state.
func (t *Table) drawCells(values []string, fill bool) {
p := t.page.active()
y := p.GetY()
p.SetX(t.x)
for i := range t.widths {
val := ""
if i < len(values) {
val = values[i]
}
align := "L"
if i < len(t.aligns) {
align = t.aligns[i]
}
p.Cell(t.widths[i], t.rowH, val, t.border, align, fill, 0)
}
p = t.page.active()
p.SetXY(t.x, y+t.rowH)
}
// ---- Complex API (buffered rendering) ----
// AddHeader buffers a header row for complex table rendering.
// Call Render() after all rows are added.
func (t *Table) AddHeader(cells ...TableCell) {
t.buffered = append(t.buffered, bufferedRow{cells: cells, isHeader: true})
t.headerCount++
}
// AddRow buffers a body row for complex table rendering.
// Call Render() after all rows are added.
func (t *Table) AddRow(cells ...TableCell) {
t.buffered = append(t.buffered, bufferedRow{cells: cells, isHeader: false})
}
// Render draws all buffered rows with full support for colspan, rowspan,
// multi-line text wrapping, and per-cell styling.
func (t *Table) Render() {
if len(t.buffered) == 0 || len(t.widths) == 0 {
return
}
numCols := len(t.widths)
numRows := len(t.buffered)
// Phase 1: Build cell placement grid.
grid := make([][]*cellPlacement, numRows)
for r := range grid {
grid[r] = make([]*cellPlacement, numCols)
}
for r, row := range t.buffered {
colIdx := 0
for _, cell := range row.cells {
// Skip columns occupied by a previous rowspan.
for colIdx < numCols && grid[r][colIdx] != nil {
colIdx++
}
if colIdx >= numCols {
break
}
cs := cell.ColSpan
if cs < 1 {
cs = 1
}
rs := cell.RowSpan
if rs < 1 {
rs = 1
}
p := &cellPlacement{cell: cell, originR: r, originC: colIdx}
// Mark all covered grid positions.
for dr := 0; dr < rs && r+dr < numRows; dr++ {
for dc := 0; dc < cs && colIdx+dc < numCols; dc++ {
grid[r+dr][colIdx+dc] = p
}
}
colIdx += cs
}
}
// Phase 2: Calculate row heights.
lineH := t.lineH
if lineH <= 0 {
lineH = t.rowH
}
rowHeights := make([]float64, numRows)
for r := range rowHeights {
rowHeights[r] = t.rowH // minimum height
}
// First pass: non-rowspan cells determine row heights.
for r := 0; r < numRows; r++ {
for c := 0; c < numCols; c++ {
p := grid[r][c]
if p == nil || p.originR != r || p.originC != c {
continue
}
rs := p.cell.RowSpan
if rs < 1 {
rs = 1
}
if rs > 1 {
continue // handled in second pass
}
cellW := t.cellSpanWidth(c, p.cell.ColSpan)
textW := cellW - 2*t.cellPadding
lines := t.wrapText(p.cell.Text, textW)
needed := float64(len(lines))*lineH + 2*t.cellPadding
if needed > rowHeights[r] {
rowHeights[r] = needed
}
}
}
// Second pass: rowspan cells — add extra height to the last spanned row if needed.
for r := 0; r < numRows; r++ {
for c := 0; c < numCols; c++ {
p := grid[r][c]
if p == nil || p.originR != r || p.originC != c {
continue
}
rs := p.cell.RowSpan
if rs < 1 {
rs = 1
}
if rs == 1 {
continue
}
cellW := t.cellSpanWidth(c, p.cell.ColSpan)
textW := cellW - 2*t.cellPadding
lines := t.wrapText(p.cell.Text, textW)
needed := float64(len(lines))*lineH + 2*t.cellPadding
totalH := 0.0
lastRow := r + rs - 1
if lastRow >= numRows {
lastRow = numRows - 1
}
for dr := r; dr <= lastRow; dr++ {
totalH += rowHeights[dr]
}
if needed > totalH {
rowHeights[lastRow] += needed - totalH
}
}
}
// Phase 3: Draw all rows.
d := t.doc
pg := t.page.active()
y := pg.GetY()
for r := 0; r < numRows; r++ {
// Page break check (body rows only).
if !t.buffered[r].isHeader && d.autoPageBreak && !d.inHeader && !d.inFooter {
pg = t.page.active()
if y+rowHeights[r] > pg.h-d.bMargin && y > d.tMargin {
np := d.AddPage(pg.size)
pg.next = np
pg = t.page.active()
y = d.tMargin
// Repeat header rows.
if t.repeatHeader && t.headerCount > 0 {
for hr := 0; hr < t.headerCount && hr < numRows; hr++ {
x := t.x
for c := 0; c < numCols; c++ {
pl := grid[hr][c]
if pl != nil && pl.originR == hr && pl.originC == c {
cw := t.cellSpanWidth(c, pl.cell.ColSpan)
ch := t.rowSpanHeight(rowHeights, hr, pl.cell.RowSpan)
t.drawComplexCell(x, y, cw, ch, pl.cell, true, c)
}
x += t.widths[c]
}
y += rowHeights[hr]
}
}
}
}
// Draw cells whose origin is this row.
x := t.x
for c := 0; c < numCols; c++ {
pl := grid[r][c]
if pl != nil && pl.originR == r && pl.originC == c {
cw := t.cellSpanWidth(c, pl.cell.ColSpan)
ch := t.rowSpanHeight(rowHeights, r, pl.cell.RowSpan)
t.drawComplexCell(x, y, cw, ch, pl.cell, t.buffered[r].isHeader, c)
}
x += t.widths[c]
}
y += rowHeights[r]
}
// Update cursor.
pg = t.page.active()
pg.SetXY(t.x, y)
}
// cellSpanWidth returns the total width for a cell spanning multiple columns.
func (t *Table) cellSpanWidth(startCol, colspan int) float64 {
if colspan < 1 {
colspan = 1
}
w := 0.0
for i := 0; i < colspan && startCol+i < len(t.widths); i++ {
w += t.widths[startCol+i]
}
return w
}
// rowSpanHeight returns the total height for a cell spanning multiple rows.
func (t *Table) rowSpanHeight(rowHeights []float64, startRow, rowspan int) float64 {
if rowspan < 1 {
rowspan = 1
}
h := 0.0
for i := 0; i < rowspan && startRow+i < len(rowHeights); i++ {
h += rowHeights[startRow+i]
}
return h
}
// drawComplexCell draws a single cell at absolute coordinates with full
// support for multi-line text, alignment, borders, and per-cell styling.
func (t *Table) drawComplexCell(x, y, w, h float64, cell TableCell, isHeader bool, colIdx int) {
d := t.doc
pg := t.page.active()
// Determine effective style.
var style *CellStyle
if cell.Style != nil {
style = cell.Style
} else if isHeader && t.hasHeaderStyle {
style = &t.headerStyle
} else if !isHeader && t.hasBodyStyle {
style = &t.bodyStyle
}
// Save document state (font + colors).
savedFont := d.GetFontFamily()
savedStyle := d.GetFontStyle()
savedSize := d.GetFontSize()
savedTextColor := d.textColor
savedDrawColor := d.drawColor
// Apply style.
if style != nil {
if style.FontFamily != "" {
d.SetFont(style.FontFamily, style.FontStyle, style.FontSize)
}
d.SetTextColor(style.TextColor[0], style.TextColor[1], style.TextColor[2])
d.SetDrawColor(style.DrawColor[0], style.DrawColor[1], style.DrawColor[2])
}
// Alternating row fill for body cells without explicit style.
fill := false
if style != nil && style.Fill {
d.SetFillColor(style.FillColor[0], style.FillColor[1], style.FillColor[2])
fill = true
} else if !isHeader && t.hasAlt {
// Use body row index for alternating colors.
// (Not perfect with rowspan, but reasonable.)
}
// Draw fill.
if fill {
pg.Rect(x, y, w, h, "F")
}
// Draw border.
if t.border == "1" {
pg.Rect(x, y, w, h, "D")
} else if t.border != "" {
if strings.Contains(t.border, "L") {
pg.Line(x, y, x, y+h)
}
if strings.Contains(t.border, "T") {
pg.Line(x, y, x+w, y)
}
if strings.Contains(t.border, "R") {
pg.Line(x+w, y, x+w, y+h)
}
if strings.Contains(t.border, "B") {
pg.Line(x, y+h, x+w, y+h)
}
}
// Draw text.
if cell.Text != "" {
lineH := t.lineH
if lineH <= 0 {
lineH = t.rowH
}
padding := t.cellPadding
if padding <= 0 {
// Use document's cell margin as default.
padding = d.cMargin
}
textW := w - 2*padding
lines := t.wrapText(cell.Text, textW)
// Vertical centering of text block.
textBlockH := float64(len(lines)) * lineH
startY := y + (h-textBlockH)/2
// Determine alignment.
align := cell.Align
if align == "" && colIdx < len(t.aligns) {
align = t.aligns[colIdx]
}
if align == "" {
align = "L"
}
// Cell internally adds cMargin to the text position. Subtract
// it so our dx calculation is the final word.
cm := d.cMargin
for i, line := range lines {
lineY := startY + float64(i)*lineH
pg = t.page.active()
pg.SetXY(x, lineY)
var dx float64
sw := pg.GetStringWidth(line)
switch strings.ToUpper(align) {
case "C":
dx = (w-sw)/2 - cm
case "R":
dx = w - padding - sw - cm
default:
dx = padding - cm
}
pg.SetX(x + dx)
pg.Cell(w, lineH, line, "", "", false, 0)
}
}
// Restore all styled state.
if style != nil {
if style.FontFamily != "" && savedFont != "" {
d.SetFont(savedFont, savedStyle, savedSize)
}
tc := savedTextColor
d.SetTextColor(int(tc.R*255+0.5), int(tc.G*255+0.5), int(tc.B*255+0.5))
dc := savedDrawColor
d.SetDrawColor(int(dc.R*255+0.5), int(dc.G*255+0.5), int(dc.B*255+0.5))
}
}
// wrapText splits text into lines that fit within maxWidth user units.
// Handles explicit \n newlines and word-wrapping.
func (t *Table) wrapText(text string, maxWidth float64) []string {
if text == "" {
return []string{""}
}
pg := t.page.active()
paragraphs := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
var lines []string
for _, para := range paragraphs {
if para == "" {
lines = append(lines, "")
continue
}
if maxWidth <= 0 {
lines = append(lines, para)
continue
}
words := strings.Fields(para)
if len(words) == 0 {
lines = append(lines, "")
continue
}
currentLine := words[0]
for _, word := range words[1:] {
test := currentLine + " " + word
if pg.GetStringWidth(test) > maxWidth {
lines = append(lines, currentLine)
currentLine = word
} else {
currentLine = test
}
}
lines = append(lines, currentLine)
}
return lines
}
// applyStyle applies a CellStyle to the document.
func (t *Table) applyStyle(s CellStyle) {
if s.FontFamily != "" {
t.doc.SetFont(s.FontFamily, s.FontStyle, s.FontSize)
}
t.doc.SetTextColor(s.TextColor[0], s.TextColor[1], s.TextColor[2])
t.doc.SetDrawColor(s.DrawColor[0], s.DrawColor[1], s.DrawColor[2])
if s.Fill {
t.doc.SetFillColor(s.FillColor[0], s.FillColor[1], s.FillColor[2])
}
}