forked from ledongthuc/pdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
116 lines (101 loc) · 2.5 KB
/
builder.go
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
package text
import (
"strings"
"unicode"
)
// Builder builds Text
type Builder struct {
// location on the page of the last text rendered.
x, y float64
text Text
}
// Add adds the Text content to the buffer, merging text parts if possible.
func (b *Builder) Add(t Text) {
for _, part := range t {
b.add(part.Size, part.Weight, part.Content, noWhitespace)
}
}
func (b *Builder) WriteNewline() {
if len(b.text) == 0 {
return
}
b.append("", newLine)
}
// Render adds the content with the given dimensions and font to the text builder.
// Text blocks are sectioned into lines and paragraphs based on their relative location
// on the page.
func (b *Builder) Render(x, y, w, h float64, font, content string) {
if len(content) == 0 {
return
}
var ws whitespace
switch {
case len(b.text) == 0:
case y > b.y+0.9*h, // Significantly above previous write.
y < b.y-2*h: // More than 2 lines below previous write.
// Next paragraph.
ws = newParagraph
// fmt.Println(b.y, y, h, content)
case y < b.y-0.9*h, // Significantly below previous write.
x > b.x+3*h: // Potentially new table column.
// Next line.
ws = newLine
case x > b.x+h:
ws = newWord
}
b.x = x + w
b.y = y
var weight int
if strings.HasSuffix(font, "-Bold") {
weight = 1
}
b.add(h, weight, content, ws)
}
type whitespace int
const (
noWhitespace whitespace = iota
newWord
newLine
newParagraph
)
func (b *Builder) add(size float64, weight int, content string, w whitespace) {
isWhitespace := len(strings.TrimSpace(content)) == 0
if l := len(b.text); l > 0 {
last := &b.text[l-1]
if isWhitespace || (last.Size == size && last.Weight == weight) {
b.append(content, w)
return
}
}
b.text = append(b.text, Part{Size: size, Weight: weight})
b.append(content, w)
}
// The Builder must be non-empty to call append, or else it will panic.
func (b *Builder) append(s string, w whitespace) {
last := &b.text[len(b.text)-1]
n := len(last.Content)
m := len(s)
switch w {
case noWhitespace:
case newWord:
switch {
case n > 0 && unicode.IsSpace(rune(last.Content[n-1])):
case m > 0 && unicode.IsSpace(rune(s[0])):
default:
last.Content += " "
}
case newLine:
switch {
case n > 0 && last.Content[n-1] == '\n':
case m > 0 && s[0] == '\n':
default:
last.Content += "\n"
}
case newParagraph:
last.Content = strings.TrimRightFunc(last.Content, unicode.IsSpace)
s = strings.TrimLeftFunc(s, unicode.IsSpace)
last.Content += "\n\n"
}
last.Content += s
}
func (b Builder) Text() Text { return b.text }