-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple.go
344 lines (292 loc) · 9.3 KB
/
simple.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
// 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"
"errors"
"fmt"
"io"
"math"
"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/charcode"
"seehuhn.de/go/pdf/font/cmap"
"seehuhn.de/go/pdf/font/encoding"
"seehuhn.de/go/pdf/font/subset"
"seehuhn.de/go/pdf/font/widths"
)
type embeddedSimple struct {
embedded
*encoding.SimpleEncoder
}
func (f *embeddedSimple) ForeachWidth(s pdf.String, yield func(width float64, is_space bool)) {
for _, c := range s {
gid := f.Encoding[c]
yield(f.sfnt.GlyphWidthPDF(gid), c == ' ')
}
}
func (f *embeddedSimple) CodeAndWidth(s pdf.String, gid glyph.ID, rr []rune) (pdf.String, float64, bool) {
width := f.sfnt.GlyphWidthPDF(gid)
c := f.SimpleEncoder.GIDToCode(gid, rr)
return append(s, c), width, c == ' '
}
func (f *embeddedSimple) Close() error {
if f.closed {
return nil
}
f.closed = true
if f.SimpleEncoder.Overflow() {
return fmt.Errorf("too many distinct glyphs used in font %q (%s)",
f.DefName, f.sfnt.PostScriptName())
}
origSfnt := f.sfnt.Clone()
origSfnt.CMapTable = nil
origSfnt.Gdef = nil
origSfnt.Gsub = nil
origSfnt.Gpos = nil
// Make our encoding the built-in encoding of the font.
outlines := origSfnt.Outlines.(*cff.Outlines)
outlines.Encoding = f.SimpleEncoder.Encoding
outlines.ROS = nil
outlines.GIDToCID = nil
// subset the font
subsetGID := f.SimpleEncoder.Subset()
subsetTag := subset.Tag(subsetGID, origSfnt.NumGlyphs())
subsetSfnt, err := origSfnt.Subset(subsetGID)
if err != nil {
return fmt.Errorf("CFF font subset: %w", err)
}
// convert the font to a simple font, if needed
subsetSfnt.EnsureGlyphNames()
subsetCFF := subsetSfnt.AsCFF()
if len(subsetCFF.Private) != 1 {
return fmt.Errorf("need exactly one private dict for a simple font")
}
m := f.SimpleEncoder.ToUnicode()
toUnicode := cmap.NewToUnicode(charcode.Simple, m)
// TODO(voss): check whether a ToUnicode CMap is actually needed
info := FontDictSimple{
Font: subsetCFF,
SubsetTag: subsetTag,
Encoding: subsetCFF.Encoding, // we use the built-in encoding
ToUnicode: toUnicode,
Ascent: subsetSfnt.Ascent,
Descent: subsetSfnt.Descent,
CapHeight: subsetSfnt.CapHeight,
IsSerif: subsetSfnt.IsScript,
IsScript: subsetSfnt.IsScript,
}
return info.Embed(f.w, f.Data.(pdf.Reference))
}
// FontDictSimple is the information needed to embed a simple CFF font.
type FontDictSimple 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
// Encoding is the encoding vector used by the client (a slice of length 256).
// This may be different from the font's built-in encoding.
Encoding []glyph.ID
// TODO(voss): use PDF text space units
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
}
// ExtractSimple extracts information about a simple CFF font from a PDF file.
// This is the inverse of [FontDictSimple.Embed].
func ExtractSimple(r pdf.Getter, dicts *font.Dicts) (*FontDictSimple, error) {
if err := dicts.Type.MustBe(font.CFFSimple); err != nil {
return nil, err
}
res := &FontDictSimple{}
baseFont, _ := pdf.GetName(r, dicts.FontDict["BaseFont"])
if m := subset.TagRegexp.FindStringSubmatch(string(baseFont)); m != nil {
res.SubsetTag = m[1]
}
if dicts.FontProgram != nil {
stm, err := pdf.DecodeStream(r, dicts.FontProgram, 0)
if err != nil {
return nil, pdf.Wrap(err, "CFF font stream")
}
data, err := io.ReadAll(stm)
if err != nil {
return nil, pdf.Wrap(err, "reading CFF font stream")
}
cff, err := cff.Read(bytes.NewReader(data))
if err != nil {
return nil, pdf.Wrap(err, "decoding CFF font")
}
// TODO(voss): use the glyph widths from the font dictionaries.
res.Font = cff
}
if cff := res.Font; cff != nil {
nameEncoding, err := encoding.UndescribeEncodingType1(
r, dicts.FontDict["Encoding"], cff.BuiltinEncoding())
if err != nil {
return nil, pdf.Wrap(err, "font encoding")
}
rev := make(map[string]glyph.ID)
for i, g := range cff.Glyphs {
rev[g.Name] = glyph.ID(i)
}
encoding := make([]glyph.ID, 256)
for i, name := range nameEncoding {
encoding[i] = rev[name]
}
res.Encoding = encoding
}
q := 1.0
if res.Font != nil {
cff := res.Font
if cff.FontMatrix[0] != 0 {
q = 1000 * cff.FontMatrix[0]
}
}
// If the font is non-symbolic and not embedded, we could still get
// the glyphnames for the encoding, but not the GIDs.
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"], charcode.Simple); info != nil {
res.ToUnicode = info
}
return res, nil
}
// Embed adds the font to a PDF file.
// This implements the [font.Dict] interface.
// This is the reverse of [ExtractSimple]
func (info *FontDictSimple) Embed(w pdf.Putter, fontDictRef pdf.Reference) error {
err := pdf.CheckVersion(w, "simple CFF fonts", pdf.V1_2)
if err != nil {
return err
}
cff := info.Font
if len(cff.Encoding) != 256 ||
len(cff.Private) != 1 ||
len(cff.Glyphs) == 0 ||
cff.Glyphs[0].Name == "" {
return errors.New("not a simple CFF font")
}
fontName := cff.FontInfo.FontName
if info.SubsetTag != "" {
fontName = info.SubsetTag + "+" + fontName
}
ww := make([]float64, 256)
q := 1000 * cff.FontMatrix[0]
for i := range ww {
ww[i] = float64(cff.Glyphs[info.Encoding[i]].Width) * q
}
widthsInfo := widths.EncodeSimple(ww)
clientEnc := make([]string, 256)
builtinEnc := make([]string, 256)
for i := 0; i < 256; i++ {
clientEnc[i] = cff.Glyphs[info.Encoding[i]].Name
builtinEnc[i] = cff.Glyphs[cff.Encoding[i]].Name
}
bbox := cff.BBox()
// TODO(voss): use the full font matrix
fontBBox := &pdf.Rectangle{
LLx: bbox.LLx.AsFloat(q),
LLy: bbox.LLy.AsFloat(q),
URx: bbox.URx.AsFloat(q),
URy: bbox.URy.AsFloat(q),
}
widthsRef := w.Alloc()
fontDescriptorRef := w.Alloc()
fontFileRef := w.Alloc()
// See section 9.6.2.1 of PDF 32000-1:2008.
fontDict := pdf.Dict{
"Type": pdf.Name("Font"),
"Subtype": pdf.Name("Type1"),
"BaseFont": pdf.Name(fontName),
"FirstChar": widthsInfo.FirstChar,
"LastChar": widthsInfo.LastChar,
"Widths": widthsRef,
"FontDescriptor": fontDescriptorRef,
}
if enc := encoding.DescribeEncodingType1(clientEnc, builtinEnc); enc != nil {
fontDict["Encoding"] = enc
}
var toUnicodeRef pdf.Reference
if info.ToUnicode != nil {
toUnicodeRef = w.Alloc()
fontDict["ToUnicode"] = toUnicodeRef
}
isSymbolic := true // TODO(voss): try to set this correctly?
fd := &font.Descriptor{
FontName: fontName,
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),
StemV: cff.Private[0].StdVW * q,
MissingWidth: widthsInfo.MissingWidth,
}
fontDescriptor := fd.AsDict()
fontDescriptor["FontFile3"] = fontFileRef
compressedRefs := []pdf.Reference{fontDictRef, fontDescriptorRef, widthsRef}
compressedObjects := []pdf.Object{fontDict, fontDescriptor, widthsInfo.Widths}
err = w.WriteCompressed(compressedRefs, compressedObjects...)
if err != nil {
return pdf.Wrap(err, "simple CFF font dicts")
}
// See section 9.9 of PDF 32000-1:2008 for details.
fontFileDict := pdf.Dict{
"Subtype": pdf.Name("Type1C"),
}
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", fontName, err)
}
err = fontFileStream.Close()
if err != nil {
return err
}
if toUnicodeRef != 0 {
err = info.ToUnicode.Embed(w, toUnicodeRef)
if err != nil {
return err
}
}
return nil
}