forked from unidoc/unipdf
/
clean_fonts.go
353 lines (311 loc) · 8.76 KB
/
clean_fonts.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
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.md', which is part of this source code package.
*/
package optimize
import (
"bytes"
"errors"
"github.com/unidoc/unitype"
"github.com/oliverpool/unipdf/v3/common"
"github.com/oliverpool/unipdf/v3/core"
"github.com/oliverpool/unipdf/v3/extractor"
"github.com/oliverpool/unipdf/v3/internal/textencoding"
"github.com/oliverpool/unipdf/v3/model"
)
// CleanFonts cleans up embedded fonts, reducing font sizes.
type CleanFonts struct {
// Subset embedded fonts if encountered (if true).
// Otherwise attempts to reduce the font program.
Subset bool
}
func optimizeFontsWithSubsetting(objects []core.PdfObject) (processed map[*core.PdfObjectStream]struct{}, err error) {
// 1. Identify all fonts.
// 2. Identify content streams and their Resources dictionaries (both via page, forms and annotations).
// 3. Process content streams.
processed = map[*core.PdfObjectStream]struct{}{}
fontMap := map[*model.PdfFont]struct{}{}
objstr := getObjectStructure(objects)
for _, p := range objstr.pages {
pdict, ok := core.GetDict(p.PdfObject)
if !ok {
continue
}
resourcesDict, ok := core.GetDict(pdict.Get("Resources"))
if !ok {
continue
}
contents, _ := getPageContents(pdict.Get("Contents"))
resources, err := model.NewPdfPageResourcesFromDict(resourcesDict)
if err != nil {
return nil, err
}
allContents := []content{
{
content: contents,
resources: resources,
},
}
annotContents := getAnnotationContents(pdict.Get("Annots"))
if annotContents != nil {
allContents = append(allContents, annotContents...)
}
for _, cont := range allContents {
e, err := extractor.NewFromContents(cont.content, cont.resources)
if err != nil {
return nil, err
}
pt, _, _, err := e.ExtractPageText()
if err != nil {
return nil, err
}
for _, el := range pt.Marks().Elements() {
if el.Font == nil {
continue
}
if _, has := fontMap[el.Font]; !has {
fontMap[el.Font] = struct{}{}
}
}
}
}
// Map of font program stream to font. Multiple fonts can use the same font program.
fontFileMap := map[*core.PdfObjectStream][]*model.PdfFont{}
for font := range fontMap {
fontDesc := font.FontDescriptor()
if fontDesc == nil || fontDesc.FontFile2 == nil {
continue
}
stream, ok := core.GetStream(fontDesc.FontFile2)
if !ok {
continue
}
fontFileMap[stream] = append(fontFileMap[stream], font)
}
for stream := range fontFileMap {
var allRunes []rune
var allIndices []unitype.GlyphIndex
for _, font := range fontFileMap[stream] {
switch t := font.Encoder().(type) {
case *textencoding.IdentityEncoder:
// TODO: This terminology is wrong as those are not runes, just charcodes cast as runes.
// Identity encoder maps via 2-byte encoding directly from 2byte charcode to glyph index.
runes := t.RegisteredRunes()
indices := make([]unitype.GlyphIndex, len(runes))
for i, r := range runes {
indices[i] = unitype.GlyphIndex(r)
}
allIndices = append(allIndices, indices...)
case *textencoding.TrueTypeFontEncoder:
runes := t.RegisteredRunes()
allRunes = append(allRunes, runes...)
case textencoding.SimpleEncoder:
charcodes := t.Charcodes()
for _, c := range charcodes {
r, ok := t.CharcodeToRune(c)
if !ok {
common.Log.Debug("Charcode<->rune not found: %d", c)
continue
}
allRunes = append(allRunes, r)
}
}
}
err = subsetFontStream(stream, allRunes, allIndices)
if err != nil {
common.Log.Debug("ERROR subsetting font stream: %v", err)
return nil, err
}
processed[stream] = struct{}{}
}
return processed, nil
}
// Subsets the font program in `stream` with the subset based on the `runes` and glyph `indices`.
func subsetFontStream(stream *core.PdfObjectStream, runes []rune, indices []unitype.GlyphIndex) error {
stream, ok := core.GetStream(stream)
if !ok {
common.Log.Debug("Embedded font object not found -- ABORT subsetting")
return errors.New("fontfile2 not found")
}
decoded, err := core.DecodeStream(stream)
if err != nil {
common.Log.Debug("Decode error: %v", err)
return err
}
fnt, err := unitype.Parse(bytes.NewReader(decoded))
if err != nil {
common.Log.Debug("Error parsing %d byte font", len(stream.Stream))
return err
}
allIndices := indices
if len(runes) > 0 {
indices := fnt.LookupRunes(runes)
allIndices = append(allIndices, indices...)
}
fnt, err = fnt.SubsetKeepIndices(allIndices)
if err != nil {
common.Log.Debug("ERROR subsetting font: %v", err)
return err
}
var buf bytes.Buffer
err = fnt.Write(&buf)
if err != nil {
common.Log.Debug("ERROR Writing font: %v", err)
return err
}
if buf.Len() > len(decoded) {
common.Log.Debug("Re-written font is larger than original - skip")
return nil
}
newstream, err := core.MakeStream(buf.Bytes(), core.NewFlateEncoder())
if err != nil {
common.Log.Debug("ERROR Writing font: %v", err)
return err
}
// Overwrite.
*stream = *newstream
stream.Set("Length1", core.MakeInteger(int64(buf.Len())))
return nil
}
// Optimize optimizes PDF objects to decrease PDF size.
func (c *CleanFonts) Optimize(objects []core.PdfObject) (optimizedObjects []core.PdfObject, err error) {
var processed map[*core.PdfObjectStream]struct{}
if c.Subset {
var err error
processed, err = optimizeFontsWithSubsetting(objects)
if err != nil {
return nil, err
}
}
// Clean font streams by loading and rewriting with minimal needed tables.
for _, obj := range objects {
stream, isStreamObj := core.GetStream(obj)
if !isStreamObj {
continue
}
if _, has := processed[stream]; has {
// Skip - has been processed.
continue
}
encoder, err := core.NewEncoderFromStream(stream)
if err != nil {
common.Log.Debug("ERROR getting encoder: %v - ignoring", err)
continue
}
decoded, err := encoder.DecodeStream(stream)
if err != nil {
common.Log.Debug("Decoding error : %v - ignoring", err)
continue
}
if len(decoded) < 4 {
continue
}
version := string(decoded[:4])
if version == "OTTO" {
// Fonts based on PostScript outlines not supported yet.
// See https://docs.microsoft.com/en-us/typography/opentype/spec/otff
continue
}
if version != "\x00\x01\x00\x00" && version != "true" {
continue
}
fnt, err := unitype.Parse(bytes.NewReader(decoded))
if err != nil {
common.Log.Debug("ERROR Parsing font: %v - ignoring", err)
continue
}
err = fnt.Optimize()
if err != nil {
continue
}
var buf bytes.Buffer
err = fnt.Write(&buf)
if err != nil {
common.Log.Debug("ERROR Writing font: %v - ignoring", err)
continue
}
if buf.Len() > len(decoded) {
common.Log.Debug("Re-written font is larger than original - skip")
continue
}
newstream, err := core.MakeStream(buf.Bytes(), core.NewFlateEncoder())
if err != nil {
continue
}
// Overwrite.
*stream = *newstream
stream.Set("Length1", core.MakeInteger(int64(buf.Len())))
}
return objects, nil
}
// content describes page or font contents which is a content stream along with resources.
type content struct {
content string
resources *model.PdfPageResources
}
// Best effort to get annotation contents.
func getAnnotationContents(annotsObj core.PdfObject) []content {
if annotsObj == nil {
return nil
}
annotsArr, ok := core.GetArray(annotsObj)
if !ok {
common.Log.Debug("Annots not an array")
return nil
}
var annotContents []content
for _, obj := range annotsArr.Elements() {
annotDict, ok := core.GetDict(obj)
if !ok {
// Ignore any non dict elements.
common.Log.Debug("Ignoring non-dict element in Annots")
continue
}
// Appearance.
appDict, ok := core.GetDict(annotDict.Get("AP"))
if !ok {
common.Log.Debug("No AP entry - skipping")
continue
}
normal := core.TraceToDirectObject(appDict.Get("N"))
if normal == nil {
common.Log.Debug("No N entry - skipping")
continue
}
var stream *core.PdfObjectStream
switch t := normal.(type) {
case *core.PdfObjectDictionary:
appState, ok := core.GetName(annotDict.Get("AS"))
if !ok {
common.Log.Debug("No AS entry - skipping")
continue
}
stream, ok = core.GetStream(t.Get(*appState))
if !ok {
common.Log.Debug("Form not found - skipping")
continue
}
case *core.PdfObjectStream:
stream = t
}
if stream == nil {
common.Log.Debug("Form not found (nil) - skipping")
continue
}
xform, err := model.NewXObjectFormFromStream(stream)
if err != nil {
common.Log.Debug("Error loading form: %v - ignoring", err)
continue
}
contents, err := xform.GetContentStream()
if err != nil {
common.Log.Debug("Error decoding contents: %v", err)
continue
}
annotContents = append(annotContents, content{
content: string(contents),
resources: xform.Resources,
})
}
return annotContents
}