/
font.go
361 lines (316 loc) · 8.96 KB
/
font.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
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
package giopdf
import (
"bytes"
"errors"
"fmt"
"io"
"gioui.org/f32"
"github.com/andybalholm/giopdf/cff"
"github.com/andybalholm/giopdf/pdf"
"github.com/benoitkugler/textlayout/fonts"
"github.com/benoitkugler/textlayout/fonts/simpleencodings"
"github.com/benoitkugler/textlayout/fonts/truetype"
"github.com/benoitkugler/textlayout/fonts/type1"
"golang.org/x/image/math/fixed"
)
// A Glyph represents a character from a font. It uses a coordinate system
// where the origin is at the left end of the baseline of the glyph, y
// increases vertically, and the font size is one unit.
type Glyph struct {
Outlines []PathElement
Width float32
}
// A Font converts text strings to slices of Glyphs, so that they can be
// displayed.
type Font interface {
ToGlyphs(s string) []Glyph
}
// A SimpleFont is a font with a simple 8-bit encoding.
type SimpleFont struct {
Glyphs [256]Glyph
}
func (f *SimpleFont) ToGlyphs(s string) []Glyph {
result := make([]Glyph, len(s))
for i := 0; i < len(s); i++ {
result[i] = f.Glyphs[s[i]]
}
return result
}
func scalePoint(p fixed.Point26_6, ppem fixed.Int26_6) f32.Point {
return f32.Pt(float32(p.X)/float32(ppem), -float32(p.Y)/float32(ppem))
}
// SimpleFontFromSFNT converts an SFNT (TrueType or OpenType) font to a
// SimpleFont with the specified encoding.
func SimpleFontFromSFNT(data []byte, enc simpleencodings.Encoding) (*SimpleFont, error) {
f, err := truetype.Parse(bytes.NewReader(data))
if err != nil {
return nil, err
}
ppem := f.Upem()
scale := 1 / float32(ppem)
fm := f32.Affine2D{}.Scale(f32.Pt(0, 0), f32.Pt(scale, scale))
var GIDEncoding [256]fonts.GID
if enc != (simpleencodings.Encoding{}) {
for b, r := range enc.ByteToRune() {
gi, ok := f.NominalGlyph(r)
if ok {
GIDEncoding[b] = gi
}
}
} else {
// The encoding in the font dictionary was missing, so use the font's
// builtin encoding.
fp, err := truetype.NewFontParser(bytes.NewReader(data))
if err != nil {
return nil, err
}
ct, err := fp.CmapTable()
if err != nil {
return nil, err
}
cmap3_0 := ct.FindSubtable(truetype.CmapID{3, 0})
if cmap3_0 != nil {
// If the font contains a (3, 0) subtable, the range of character codes must be one
// of the following: 0x0000 - 0x00FF, 0xF000 - 0xF0FF, 0xF100 - 0xF1FF, or
// 0xF200 - 0xF2FF. Depending on the range of codes, each byte from the string is
// prepended with the high byte of the range, to form a two-byte character, which
// is used to select the associated glyph description from the subtable.
iter := cmap3_0.Iter()
for iter.Next() {
code, gid := iter.Char()
switch code & 0xFF00 {
case 0x0000, 0xF000, 0xF100, 0xF200:
b := code & 0xFF
if GIDEncoding[b] == 0 {
GIDEncoding[b] = gid
}
}
}
}
cmap1_0 := ct.FindSubtable(truetype.CmapID{1, 0})
if cmap1_0 != nil {
// Otherwise, if the font contains a (1, 0) subtable, single bytes from the string are
// used to look up the associated glyph descriptions from the subtable.
iter := cmap1_0.Iter()
for iter.Next() {
code, gid := iter.Char()
if code > 255 {
continue
}
if GIDEncoding[code] == 0 {
GIDEncoding[code] = gid
}
}
}
}
simple := new(SimpleFont)
for i, gi := range GIDEncoding {
var g Glyph
g.Width = f.HorizontalAdvance(gi) * scale
gd := f.GlyphData(gi, ppem, ppem)
switch gd := gd.(type) {
case fonts.GlyphOutline:
g.Outlines = glyphOutline(gd, fm)
case fonts.GlyphSVG:
g.Outlines = glyphOutline(gd.Outline, fm)
case fonts.GlyphBitmap:
return nil, errors.New("bitmap fonts not supported")
}
simple.Glyphs[i] = g
}
return simple, nil
}
func getEncoding(e pdf.Value) (simpleencodings.Encoding, error) {
switch e.Kind() {
case pdf.Null:
return simpleencodings.Encoding{}, nil
case pdf.Name:
switch e.Name() {
case "MacRomanEncoding":
return simpleencodings.MacRoman, nil
case "MaxExpertEncoding":
return simpleencodings.MacExpert, nil
case "WinAnsiEncoding":
return simpleencodings.WinAnsi, nil
default:
return simpleencodings.Encoding{}, fmt.Errorf("unknown encoding: %v", e)
}
case pdf.Dict:
enc, err := getEncoding(e.Key("BaseEncoding"))
if err != nil {
return enc, err
}
diff := e.Key("Differences")
code := 0
for i := 0; i < diff.Len(); i++ {
item := diff.Index(i)
switch item.Kind() {
case pdf.Integer:
code = item.Int() - 1
case pdf.Name:
code++
enc[code] = item.Name()
}
}
return enc, nil
default:
return simpleencodings.Encoding{}, fmt.Errorf("invalid encoding: %v", e)
}
}
// SimpleFontFromType1 converts a Type 1 font to a SimpleFont, using the
// encoding provided.
func SimpleFontFromType1(data []byte, enc simpleencodings.Encoding) (*SimpleFont, error) {
f, err := type1.Parse(bytes.NewReader(data))
if err != nil {
return nil, err
}
nameToGID := map[string]fonts.GID{}
for i := fonts.GID(0); ; i++ {
name := f.GlyphName(i)
if name == "" {
break
}
nameToGID[name] = i
}
for i, name := range enc {
// Fill in the blanks with the font's builtin encoding.
if name == "" {
enc[i] = f.Encoding[i]
}
}
fm := f32.NewAffine2D(f.FontMatrix[0], f.FontMatrix[2], f.FontMatrix[4], f.FontMatrix[1], f.FontMatrix[3], f.FontMatrix[5])
simple := new(SimpleFont)
for i, name := range enc {
var g Glyph
gi, ok := nameToGID[name]
if !ok {
continue
}
width := f.HorizontalAdvance(gi)
g.Width = fm.Transform(f32.Pt(width, 0)).X
gd := f.GlyphData(gi, 0, 0)
if gd == nil {
continue
}
g.Outlines = glyphOutline(gd.(fonts.GlyphOutline), fm)
simple.Glyphs[i] = g
}
return simple, nil
}
// SimpleFontFromCFF converts a CFF font to a SimpleFont, using the
// encoding provided.
func SimpleFontFromCFF(data []byte, enc simpleencodings.Encoding) (*SimpleFont, error) {
f, err := cff.Parse(bytes.NewReader(data))
if err != nil {
return nil, err
}
nameToGID := map[string]fonts.GID{}
for i := fonts.GID(0); ; i++ {
name := f.GlyphName(i)
if name == "" {
break
}
nameToGID[name] = i
}
for i, name := range enc {
// Fill in the blanks with the font's builtin encoding.
if name == "" {
enc[i] = f.Encoding[i]
}
}
fm := f32.NewAffine2D(f.FontMatrix[0], f.FontMatrix[2], f.FontMatrix[4], f.FontMatrix[1], f.FontMatrix[3], f.FontMatrix[5])
simple := new(SimpleFont)
for i, name := range enc {
var g Glyph
gi, ok := nameToGID[name]
if !ok {
continue
}
gd, err := f.LoadGlyph(gi)
if err != nil {
return nil, err
}
g.Width = fm.Transform(f32.Pt(float32(gd.Width), 0)).X
g.Outlines = glyphOutline(fonts.GlyphOutline{Segments: gd.Outlines}, fm)
simple.Glyphs[i] = g
}
return simple, nil
}
// glyphOutline converts outline to our path format, transforming the points
// with fm.
func glyphOutline(outline fonts.GlyphOutline, fm f32.Affine2D) []PathElement {
var p PathBuilder
for _, seg := range outline.Segments {
p0 := fm.Transform(f32.Point(seg.Args[0]))
p1 := fm.Transform(f32.Point(seg.Args[1]))
p2 := fm.Transform(f32.Point(seg.Args[2]))
switch seg.Op {
case fonts.SegmentOpMoveTo:
p.ClosePath()
p.MoveTo(p0.X, p0.Y)
case fonts.SegmentOpLineTo:
p.LineTo(p0.X, p0.Y)
case fonts.SegmentOpQuadTo:
p.QuadraticCurveTo(p0.X, p0.Y, p1.X, p1.Y)
case fonts.SegmentOpCubeTo:
p.CurveTo(p0.X, p0.Y, p1.X, p1.Y, p2.X, p2.Y)
}
}
p.ClosePath()
return p.Path
}
func importPDFFont(f pdf.Font) (font Font, err error) {
enc, err := getEncoding(f.V.Key("Encoding"))
if err != nil {
return nil, err
}
switch f.V.Key("Subtype").Name() {
case "TrueType":
file := f.V.Key("FontDescriptor").Key("FontFile2")
if file.IsNull() {
return nil, fmt.Errorf("%v does not have embedded font data", f.V.Key("BaseFont"))
}
data, err := io.ReadAll(file.Reader())
if err != nil {
return nil, err
}
font, err = SimpleFontFromSFNT(data, enc)
case "Type1":
if f.V.Key("FontDescriptor").Key("FontFile3").Key("Subtype").Name() == "Type1C" {
file := f.V.Key("FontDescriptor").Key("FontFile3")
if file.IsNull() {
return nil, fmt.Errorf("%v does not have embedded font data", f.V.Key("BaseFont"))
}
data, err := io.ReadAll(file.Reader())
if err != nil {
return nil, err
}
font, err = SimpleFontFromCFF(data, enc)
} else {
file := f.V.Key("FontDescriptor").Key("FontFile")
if file.IsNull() {
return nil, fmt.Errorf("%v does not have embedded font data", f.V.Key("BaseFont"))
}
data, err := io.ReadAll(file.Reader())
if err != nil {
return nil, err
}
font, err = SimpleFontFromType1(data, enc)
}
default:
return nil, fmt.Errorf("%v is an unsupported font type (%v)", f.V.Key("BaseFont"), f.V.Key("Subtype"))
}
if err != nil {
return nil, err
}
// Glyph widths from the font dictionary override widths from the font itself.
if simple, ok := font.(*SimpleFont); ok {
firstChar := f.V.Key("FirstChar").Int()
lastChar := f.V.Key("LastChar").Int()
widths := f.V.Key("Widths")
for i := firstChar; i <= lastChar; i++ {
simple.Glyphs[i].Width = widths.Index(i-firstChar).Float32() / 1000
}
}
return font, nil
}