-
Notifications
You must be signed in to change notification settings - Fork 0
/
cidglyf.go
464 lines (408 loc) · 12 KB
/
cidglyf.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
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
// seehuhn.de/go/pdf - a library for reading and writing PDF files
// Copyright (C) 2023 Jochen Voss <voss@seehuhn.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package opentype
import (
"fmt"
"io"
"math"
"slices"
pscid "seehuhn.de/go/postscript/cid"
"seehuhn.de/go/postscript/funit"
"seehuhn.de/go/sfnt"
"seehuhn.de/go/sfnt/glyf"
"seehuhn.de/go/sfnt/glyph"
"seehuhn.de/go/pdf"
"seehuhn.de/go/pdf/font"
"seehuhn.de/go/pdf/font/cmap"
"seehuhn.de/go/pdf/font/pdfenc"
"seehuhn.de/go/pdf/font/subset"
"seehuhn.de/go/pdf/font/widths"
)
type embeddedGlyfComposite struct {
w pdf.Putter
pdf.Res
*font.Geometry
sfnt *sfnt.Font
layouter *sfnt.Layouter
cmap.GIDToCID
cmap.CIDEncoder
closed bool
}
// Layout implements the [font.Layouter] interface.
func (f *embeddedGlyfComposite) Layout(seq *font.GlyphSeq, ptSize float64, s string) *font.GlyphSeq {
if seq == nil {
seq = &font.GlyphSeq{}
}
buf := f.layouter.Layout(s)
seq.Seq = slices.Grow(seq.Seq, len(buf))
for _, g := range buf {
xOffset := float64(g.XOffset) * ptSize * f.sfnt.FontMatrix[0]
if len(seq.Seq) == 0 {
seq.Skip += xOffset
} else {
seq.Seq[len(seq.Seq)-1].Advance += xOffset
}
seq.Seq = append(seq.Seq, font.Glyph{
GID: g.GID,
Advance: float64(g.Advance) * ptSize * f.sfnt.FontMatrix[0],
Rise: float64(g.YOffset) * ptSize * f.sfnt.FontMatrix[3],
Text: g.Text,
})
}
return seq
}
func (f *embeddedGlyfComposite) WritingMode() int {
return 0 // TODO(voss): implement vertical writing mode
}
func (f *embeddedGlyfComposite) ForeachWidth(s pdf.String, yield func(width float64, is_space bool)) {
f.AllCIDs(s)(func(code []byte, cid pscid.CID) bool {
gid := f.GID(cid)
width := float64(f.sfnt.GlyphWidth(gid)) / float64(f.sfnt.UnitsPerEm)
yield(width, len(code) == 1 && code[0] == ' ')
return true
})
}
func (f *embeddedGlyfComposite) CodeAndWidth(s pdf.String, gid glyph.ID, rr []rune) (pdf.String, float64, bool) {
width := float64(f.sfnt.GlyphWidth(gid)) / float64(f.sfnt.UnitsPerEm)
k := len(s)
s = f.CIDEncoder.AppendEncoded(s, gid, rr)
return s, width, len(s) == k+1 && s[k] == ' '
}
func (f *embeddedGlyfComposite) Close() error {
if f.closed {
return nil
}
f.closed = true
origOTF := f.sfnt.Clone()
origOTF.CMapTable = nil
origOTF.Gdef = nil
origOTF.Gsub = nil
origOTF.Gpos = nil
// subset the font
subsetGID := f.CIDEncoder.Subset()
subsetTag := subset.Tag(subsetGID, origOTF.NumGlyphs())
subsetOTF, err := origOTF.Subset(subsetGID)
if err != nil {
return fmt.Errorf("OpenType/glyf font subset: %w", err)
}
toUnicode := f.ToUnicode()
cmapInfo := f.CMap()
// The `CIDToGIDMap` entry in the CIDFont dictionary specifies the mapping
// from CIDs to glyphs.
m := make(map[glyph.ID]pscid.CID)
origGIDToCID := f.GIDToCID.GIDToCID(origOTF.NumGlyphs())
for origGID, cid := range origGIDToCID {
m[glyph.ID(origGID)] = cid
}
var maxCID pscid.CID
for _, origGID := range subsetGID {
cid := m[origGID]
if cid > maxCID {
maxCID = cid
}
}
cidToGID := make([]glyph.ID, maxCID+1)
for subsetGID, origGID := range subsetGID {
cidToGID[m[origGID]] = glyph.ID(subsetGID)
}
info := FontDictGlyfComposite{
Font: subsetOTF,
SubsetTag: subsetTag,
CMap: cmapInfo,
CIDToGID: cidToGID,
ToUnicode: toUnicode,
}
return info.Embed(f.w, f.Data.(pdf.Reference))
}
// FontDictGlyfComposite is the information needed to embed a composite OpenType/glyf font.
type FontDictGlyfComposite struct {
// Font is the font to embed (already subsetted, if needed).
Font *sfnt.Font
// SubsetTag should be a unique tag for the font subset,
// or the empty string if this is the full font.
SubsetTag string
CMap *cmap.Info
CIDToGID []glyph.ID
ForceBold bool
IsAllCap bool
IsSmallCap bool
// ToUnicode (optional) is a map from character codes to unicode strings.
ToUnicode *cmap.ToUnicode
}
// Embed adds the font to the PDF file.
//
// This implements the [font.Dict] interface.
func (info *FontDictGlyfComposite) Embed(w pdf.Putter, fontDictRef pdf.Reference) error {
err := pdf.CheckVersion(w, "composite OpenType/glyf fonts", pdf.V1_6)
if err != nil {
return err
}
if !info.Font.IsGlyf() {
return fmt.Errorf("not a glyf-based OpenType font")
}
otf := info.Font.Clone()
otf.CMapTable = nil
outlines := otf.Outlines.(*glyf.Outlines)
// CidFontName shall be the value of the CIDFontName entry in the CIDFont program.
// The name may have a subset prefix if appropriate.
cidFontName := otf.PostScriptName()
if info.SubsetTag != "" {
cidFontName = info.SubsetTag + "+" + cidFontName
}
// make a PDF CMap
cmapInfo := info.CMap
var encoding pdf.Object
if cmapInfo.IsPredefined() {
encoding = pdf.Name(cmapInfo.Name)
} else {
encoding = w.Alloc()
}
unitsPerEm := otf.UnitsPerEm
q := 1000 / float64(unitsPerEm)
glyphWidths := outlines.Widths
ww := make(map[pscid.CID]float64, len(glyphWidths))
for cid, gid := range info.CIDToGID {
ww[pscid.CID(cid)] = glyphWidths[gid].AsFloat(q)
}
DW, W := widths.EncodeComposite(ww, pdf.GetVersion(w))
var CIDToGIDMap pdf.Object
isIdentity := true
for cid, gid := range info.CIDToGID {
if int(gid) != cid && gid != 0 {
isIdentity = false
break
}
}
if isIdentity {
CIDToGIDMap = pdf.Name("Identity")
} else {
CIDToGIDMap = w.Alloc()
}
bbox := otf.BBox()
fontBBox := &pdf.Rectangle{
LLx: bbox.LLx.AsFloat(q),
LLy: bbox.LLy.AsFloat(q),
URx: bbox.URx.AsFloat(q),
URy: bbox.URy.AsFloat(q),
}
isSymbolic := !pdfenc.IsNonSymbolic(otf.MakeGlyphNames())
cidFontRef := w.Alloc()
var toUnicodeRef pdf.Reference
fontDescriptorRef := w.Alloc()
fontFileRef := w.Alloc()
fontDict := pdf.Dict{
"Type": pdf.Name("Font"),
"Subtype": pdf.Name("Type0"),
"BaseFont": pdf.Name(cidFontName),
"Encoding": encoding,
"DescendantFonts": pdf.Array{cidFontRef},
}
if info.ToUnicode != nil {
toUnicodeRef = w.Alloc()
fontDict["ToUnicode"] = toUnicodeRef
}
ROS := pdf.Dict{
"Registry": pdf.String(info.CMap.ROS.Registry),
"Ordering": pdf.String(info.CMap.ROS.Ordering),
"Supplement": pdf.Integer(info.CMap.ROS.Supplement),
}
cidFontDict := pdf.Dict{
"Type": pdf.Name("Font"),
"Subtype": pdf.Name("CIDFontType2"),
"BaseFont": pdf.Name(cidFontName),
"CIDSystemInfo": ROS,
"FontDescriptor": fontDescriptorRef,
"CIDToGIDMap": CIDToGIDMap,
}
if DW != 1000 {
cidFontDict["DW"] = pdf.Number(DW)
}
if W != nil {
cidFontDict["W"] = W
}
fd := &font.Descriptor{
FontName: cidFontName,
IsFixedPitch: otf.IsFixedPitch(),
IsSerif: otf.IsSerif,
IsSymbolic: isSymbolic,
IsScript: otf.IsScript,
IsItalic: otf.IsItalic,
IsAllCap: info.IsAllCap,
IsSmallCap: info.IsSmallCap,
ForceBold: info.ForceBold,
FontBBox: fontBBox,
ItalicAngle: otf.ItalicAngle,
Ascent: otf.Ascent.AsFloat(q),
Descent: otf.Descent.AsFloat(q),
CapHeight: otf.CapHeight.AsFloat(q),
}
fontDescriptor := fd.AsDict()
fontDescriptor["FontFile3"] = fontFileRef
compressedRefs := []pdf.Reference{fontDictRef, cidFontRef, fontDescriptorRef}
compressedObjects := []pdf.Object{fontDict, cidFontDict, fontDescriptor}
err = w.WriteCompressed(compressedRefs, compressedObjects...)
if err != nil {
return pdf.Wrap(err, "composite OpenType/glyf font dicts")
}
// See section 9.9 of PDF 32000-1:2008 for details.
fontFileDict := pdf.Dict{
"Subtype": pdf.Name("OpenType"),
}
fontFileStream, err := w.OpenStream(fontFileRef, fontFileDict, pdf.FilterCompress{})
if err != nil {
return err
}
_, err = otf.WriteTrueTypePDF(fontFileStream)
if err != nil {
return fmt.Errorf("embedding OpenType/glyf CIDFont %q: %w", cidFontName, err)
}
err = fontFileStream.Close()
if err != nil {
return err
}
if ref, ok := encoding.(pdf.Reference); ok {
err = cmapInfo.Embed(w, ref, nil)
if err != nil {
return err
}
}
if toUnicodeRef != 0 {
err = info.ToUnicode.Embed(w, toUnicodeRef)
if err != nil {
return err
}
}
if ref, ok := CIDToGIDMap.(pdf.Reference); ok {
cid2gidStream, err := w.OpenStream(ref, nil,
pdf.FilterCompress{
"Predictor": pdf.Integer(12),
"Columns": pdf.Integer(2),
})
if err != nil {
return err
}
cid2gid := make([]byte, 2*len(info.CIDToGID))
for cid, gid := range info.CIDToGID {
cid2gid[2*cid] = byte(gid >> 8)
cid2gid[2*cid+1] = byte(gid)
}
_, err = cid2gidStream.Write(cid2gid)
if err != nil {
return err
}
err = cid2gidStream.Close()
if err != nil {
return err
}
}
return nil
}
// ExtractGlyfComposite extracts information for a composite OpenType/glyf font.
func ExtractGlyfComposite(r pdf.Getter, dicts *font.Dicts) (*FontDictGlyfComposite, error) {
if err := dicts.Type.MustBe(font.OpenTypeGlyfComposite); err != nil {
return nil, err
}
res := &FontDictGlyfComposite{}
stmObj, err := pdf.GetStream(r, dicts.FontProgram)
if err != nil {
return nil, err
}
stmData, err := pdf.DecodeStream(r, stmObj, 0)
if err != nil {
return nil, err
}
otf, err := sfnt.Read(stmData)
if err != nil {
return nil, err
}
if _, ok := otf.Outlines.(*glyf.Outlines); !ok {
return nil, fmt.Errorf("expected glyf outlines, got %T", otf.Outlines)
}
// Most OpenType tables will be missing, so we fill in information from
// the font descriptor instead.
if otf.FamilyName == "" {
otf.FamilyName = dicts.FontDescriptor.FontFamily
}
if otf.Width == 0 {
otf.Width = dicts.FontDescriptor.FontStretch
}
if otf.Weight == 0 {
otf.Weight = dicts.FontDescriptor.FontWeight
}
otf.IsItalic = dicts.FontDescriptor.IsItalic
otf.IsSerif = dicts.FontDescriptor.IsSerif
otf.IsScript = dicts.FontDescriptor.IsScript
q := 1000 / float64(otf.UnitsPerEm)
if otf.CapHeight == 0 {
capHeight := dicts.FontDescriptor.CapHeight
otf.CapHeight = funit.Int16(math.Round(float64(capHeight) / q))
}
if otf.XHeight == 0 {
xHeight := dicts.FontDescriptor.XHeight
otf.XHeight = funit.Int16(math.Round(float64(xHeight) / q))
}
res.Font = otf
postScriptName, _ := pdf.GetName(r, dicts.CIDFontDict["BaseFont"])
if m := subset.TagRegexp.FindStringSubmatch(string(postScriptName)); m != nil {
res.SubsetTag = m[1]
}
cmapInfo, err := cmap.Extract(r, dicts.FontDict["Encoding"])
if err != nil {
return nil, err
}
res.CMap = cmapInfo
CID2GIDObj, err := pdf.Resolve(r, dicts.CIDFontDict["CIDToGIDMap"])
if err != nil {
return nil, err
}
switch CID2GID := CID2GIDObj.(type) {
case pdf.Name:
if CID2GID != "Identity" {
return nil, fmt.Errorf("unsupported CIDToGIDMap: %q", CID2GID)
}
numCIDs := int(cmapInfo.MaxCID()) + 1
if numCIDs > otf.NumGlyphs() {
numCIDs = otf.NumGlyphs()
}
res.CIDToGID = make([]glyph.ID, numCIDs)
for i := range res.CIDToGID {
res.CIDToGID[i] = glyph.ID(i)
}
case *pdf.Stream:
in, err := pdf.DecodeStream(r, CID2GID, 0)
if err != nil {
return nil, err
}
cidToGIDData, err := io.ReadAll(in)
if err == nil && len(cidToGIDData)%2 != 0 {
err = fmt.Errorf("odd length CIDToGIDMap")
}
if err != nil {
return nil, err
}
res.CIDToGID = make([]glyph.ID, len(cidToGIDData)/2)
for i := range res.CIDToGID {
res.CIDToGID[i] = glyph.ID(cidToGIDData[2*i])<<8 | glyph.ID(cidToGIDData[2*i+1])
}
}
if info, _ := cmap.ExtractToUnicode(r, dicts.FontDict["ToUnicode"], cmapInfo.CodeSpaceRange); info != nil {
res.ToUnicode = info
}
res.IsAllCap = dicts.FontDescriptor.IsAllCap
res.IsSmallCap = dicts.FontDescriptor.IsSmallCap
res.ForceBold = dicts.FontDescriptor.ForceBold
return res, nil
}