-
Notifications
You must be signed in to change notification settings - Fork 0
/
cid.go
366 lines (313 loc) · 9.68 KB
/
cid.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
// 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 cff
import (
"bytes"
"fmt"
"io"
"math"
pscid "seehuhn.de/go/postscript/cid"
"seehuhn.de/go/postscript/funit"
"seehuhn.de/go/sfnt/cff"
"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/subset"
"seehuhn.de/go/pdf/font/widths"
)
type embeddedComposite struct {
embedded
cmap.GIDToCID
cmap.CIDEncoder
}
func (f *embeddedComposite) WritingMode() int {
return 0 // TODO(voss): implement
}
func (f *embeddedComposite) ForeachWidth(s pdf.String, yield func(float64, bool)) {
f.AllCIDs(s)(func(code []byte, cid pscid.CID) bool {
gid := f.GID(cid)
// TODO(voss): deal with different Font Matrices for different private dicts.
width := float64(f.sfnt.GlyphWidth(gid)) * f.sfnt.FontMatrix[0]
yield(width, len(code) == 1 && code[0] == ' ')
return true
})
}
func (f *embeddedComposite) CodeAndWidth(s pdf.String, gid glyph.ID, rr []rune) (pdf.String, float64, bool) {
// TODO(voss): deal with different Font Matrices for different private dicts.
width := float64(f.sfnt.GlyphWidth(gid)) * f.sfnt.FontMatrix[0]
k := len(s)
s = f.CIDEncoder.AppendEncoded(s, gid, rr)
return s, width, len(s) == k+1 && s[k] == ' '
}
func (f *embeddedComposite) 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/CFF font subset: %w", err)
}
origGIDToCID := f.GIDToCID.GIDToCID(origOTF.NumGlyphs())
gidToCID := make([]pscid.CID, subsetOTF.NumGlyphs())
for i, gid := range subsetGID {
gidToCID[i] = origGIDToCID[gid]
}
ros := f.ROS()
toUnicode := f.ToUnicode()
cmapInfo := f.CMap()
// If the CFF font is CID-keyed, *i.e.* if it contain a `ROS` operator,
// then the `charset` table in the CFF font describes the mapping from CIDs
// to glyphs. Otherwise, the CID is used as the glyph index directly.
isIdentity := true
for gid, cid := range gidToCID {
if cid != 0 && cid != pscid.CID(gid) {
isIdentity = false
break
}
}
subsetCFF := subsetOTF.AsCFF().Clone()
mustUseCID := len(subsetCFF.Private) > 1
if isIdentity && !mustUseCID { // Make the font non-CID-keyed.
subsetCFF.Encoding = cff.StandardEncoding(subsetCFF.Glyphs)
subsetCFF.ROS = nil
subsetCFF.GIDToCID = nil
} else { // Make the font CID-keyed.
subsetCFF.Encoding = nil
subsetCFF.ROS = ros
subsetCFF.GIDToCID = gidToCID
}
info := FontDictComposite{
Font: subsetCFF,
SubsetTag: subsetTag,
CMap: cmapInfo,
ToUnicode: toUnicode,
UnitsPerEm: subsetOTF.UnitsPerEm,
Ascent: subsetOTF.Ascent,
Descent: subsetOTF.Descent,
CapHeight: subsetOTF.CapHeight,
IsSerif: subsetOTF.IsSerif,
IsScript: subsetOTF.IsScript,
}
return info.Embed(f.w, f.Data.(pdf.Reference))
}
// FontDictComposite is the information needed to embed a CFF font as a composite PDF font.
type FontDictComposite struct {
// Font is the font to embed (already subsetted, if needed).
Font *cff.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
UnitsPerEm uint16 // TODO(voss): get this from the font matrix instead?
Ascent funit.Int16
Descent funit.Int16
CapHeight funit.Int16
IsSerif bool
IsScript bool
IsAllCap bool
IsSmallCap bool
// ToUnicode (optional) is a map from character codes to unicode strings.
ToUnicode *cmap.ToUnicode
}
// ExtractComposite extracts information about a composite CFF font from a PDF file.
// This is the reverse of [FontDictComposite.Embed].
func ExtractComposite(r pdf.Getter, dicts *font.Dicts) (*FontDictComposite, error) {
if err := dicts.Type.MustBe(font.CFFComposite); err != nil {
return nil, err
}
res := &FontDictComposite{}
stmObj, err := pdf.GetStream(r, dicts.FontProgram)
if err != nil {
return nil, err
}
stm, err := pdf.DecodeStream(r, stmObj, 0)
if err != nil {
return nil, err
}
data, err := io.ReadAll(stm)
if err != nil {
return nil, err
}
cff, err := cff.Read(bytes.NewReader(data))
if err != nil {
return nil, err
}
res.Font = cff
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
// TODO(voss): be more robust here
unitsPerEm := uint16(math.Round(1 / float64(cff.FontMatrix[0])))
q := 1000 / float64(unitsPerEm)
res.UnitsPerEm = unitsPerEm
res.Ascent = funit.Int16(math.Round(dicts.FontDescriptor.Ascent / q))
res.Descent = funit.Int16(math.Round(dicts.FontDescriptor.Descent / q))
res.CapHeight = funit.Int16(math.Round(dicts.FontDescriptor.CapHeight / q))
res.IsSerif = dicts.FontDescriptor.IsSerif
res.IsScript = dicts.FontDescriptor.IsScript
res.IsAllCap = dicts.FontDescriptor.IsAllCap
res.IsSmallCap = dicts.FontDescriptor.IsSmallCap
if info, _ := cmap.ExtractToUnicode(r, dicts.FontDict["ToUnicode"], cmapInfo.CodeSpaceRange); info != nil {
res.ToUnicode = info
}
return res, nil
}
// Embed adds a composite CFF font to a PDF file.
// This implements the [font.Dict] interface.
// This is the reverse of [ExtractComposite]
func (info *FontDictComposite) Embed(w pdf.Putter, fontDictRef pdf.Reference) error {
err := pdf.CheckVersion(w, "composite CFF fonts", pdf.V1_3)
if err != nil {
return err
}
cff := info.Font
cidFontName := cff.FontInfo.FontName
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 := info.UnitsPerEm
q := 1000 / float64(unitsPerEm)
ww := make(map[pscid.CID]float64)
glyphWidths := cff.Widths()
if cff.GIDToCID != nil {
for gid, w := range glyphWidths {
ww[cff.GIDToCID[gid]] = w.AsFloat(q)
}
} else {
for gid, w := range glyphWidths {
ww[pscid.CID(gid)] = w.AsFloat(q)
}
}
DW, W := widths.EncodeComposite(ww, pdf.GetVersion(w))
bbox := cff.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 := true // TODO(voss): try to set this correctly
cidFontRef := w.Alloc()
fontDescriptorRef := w.Alloc()
fontFileRef := w.Alloc()
fontDict := pdf.Dict{
"Type": pdf.Name("Font"),
"Subtype": pdf.Name("Type0"),
"BaseFont": pdf.Name(cidFontName + "-" + cmapInfo.Name),
"Encoding": encoding,
"DescendantFonts": pdf.Array{cidFontRef},
}
var toUnicodeRef pdf.Reference
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("CIDFontType0"),
"BaseFont": pdf.Name(cidFontName),
"CIDSystemInfo": ROS,
"FontDescriptor": fontDescriptorRef,
}
if DW != 1000 {
cidFontDict["DW"] = pdf.Number(DW)
}
if W != nil {
cidFontDict["W"] = W
}
fd := &font.Descriptor{
FontName: cidFontName,
IsFixedPitch: cff.IsFixedPitch,
IsSerif: info.IsSerif,
IsSymbolic: isSymbolic,
IsScript: info.IsScript,
IsItalic: cff.ItalicAngle != 0,
IsAllCap: info.IsAllCap,
IsSmallCap: info.IsSmallCap,
ForceBold: cff.Private[0].ForceBold,
FontBBox: fontBBox,
ItalicAngle: cff.ItalicAngle,
Ascent: info.Ascent.AsFloat(q),
Descent: info.Descent.AsFloat(q),
CapHeight: info.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 CFF font dicts")
}
// See section 9.9 of PDF 32000-1:2008 for details.
fontFileDict := pdf.Dict{
"Subtype": pdf.Name("CIDFontType0C"),
}
fontFileStream, err := w.OpenStream(fontFileRef, fontFileDict, pdf.FilterCompress{})
if err != nil {
return err
}
err = cff.Write(fontFileStream)
if err != nil {
return fmt.Errorf("CFF font program %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
}
}
return nil
}