forked from pdfcpu/pdfcpu
/
context.go
624 lines (484 loc) · 19.4 KB
/
context.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
/*
Copyright 2018 The pdfcpu Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pdfcpu
import (
"bufio"
"fmt"
"io"
"sort"
"strings"
"github.com/hhrutter/pdfcpu/pkg/log"
)
// Context represents an environment for processing PDF files.
type Context struct {
*Configuration
*XRefTable
Read *ReadContext
Optimize *OptimizationContext
Write *WriteContext
}
// NewContext initializes a new Context.
func NewContext(rs io.ReadSeeker, fileName string, fileSize int64, config *Configuration) (*Context, error) {
if config == nil {
config = NewDefaultConfiguration()
}
ctx := &Context{
config,
newXRefTable(config.ValidationMode),
newReadContext(rs, fileName, fileSize),
newOptimizationContext(),
NewWriteContext(config.Eol),
}
return ctx, nil
}
// ResetWriteContext prepares an existing WriteContext for a new file to be written.
func (ctx *Context) ResetWriteContext() {
ctx.Write = NewWriteContext(ctx.Write.Eol)
}
func (ctx *Context) String() string {
var logStr []string
logStr = append(logStr, "*************************************************************************************************\n")
logStr = append(logStr, fmt.Sprintf("HeaderVersion: %s\n", ctx.HeaderVersion))
if ctx.RootVersion != nil {
logStr = append(logStr, fmt.Sprintf("RootVersion: %s\n", ctx.RootVersion))
}
logStr = append(logStr, fmt.Sprintf("has %d pages\n", ctx.PageCount))
if ctx.Read.UsingObjectStreams {
logStr = append(logStr, "using object streams\n")
}
if ctx.Read.UsingXRefStreams {
logStr = append(logStr, "using xref streams\n")
}
if ctx.Read.Linearized {
logStr = append(logStr, "is linearized file\n")
}
if ctx.Read.Hybrid {
logStr = append(logStr, "is hybrid reference file\n")
}
if ctx.Tagged {
logStr = append(logStr, "is tagged file\n")
}
logStr = append(logStr, "XRefTable:\n")
logStr = append(logStr, fmt.Sprintf(" Size: %d\n", *ctx.XRefTable.Size))
logStr = append(logStr, fmt.Sprintf(" Root object: %s\n", *ctx.Root))
if ctx.Info != nil {
logStr = append(logStr, fmt.Sprintf(" Info object: %s\n", *ctx.Info))
}
if ctx.ID != nil {
logStr = append(logStr, fmt.Sprintf(" ID object: %s\n", ctx.ID))
}
if ctx.Encrypt != nil {
logStr = append(logStr, fmt.Sprintf(" Encrypt object: %s\n", *ctx.Encrypt))
}
if ctx.AdditionalStreams != nil && len(*ctx.AdditionalStreams) > 0 {
var objectNumbers []string
for _, k := range *ctx.AdditionalStreams {
indRef, _ := k.(IndirectRef)
objectNumbers = append(objectNumbers, fmt.Sprintf("%d", int(indRef.ObjectNumber)))
}
sort.Strings(objectNumbers)
logStr = append(logStr, fmt.Sprintf(" AdditionalStreams: %s\n\n", strings.Join(objectNumbers, ",")))
}
logStr = append(logStr, fmt.Sprintf("XRefTable with %d entres:\n", len(ctx.Table)))
// Print sorted object list.
logStr = ctx.list(logStr)
// Print free list.
logStr, err := ctx.freeList(logStr)
if err != nil {
log.Info.Fatalln(err)
}
// Print list of any missing objects.
if len(ctx.XRefTable.Table) != *ctx.XRefTable.Size {
missing, s := ctx.MissingObjects()
logStr = append(logStr, fmt.Sprintf("%d missing objects: %s\n", missing, *s))
}
logStr = append(logStr, fmt.Sprintf("\nTotal pages: %d\n", ctx.PageCount))
logStr = ctx.Optimize.collectFontInfo(logStr)
logStr = ctx.Optimize.collectImageInfo(logStr)
logStr = append(logStr, "\n")
return strings.Join(logStr, "")
}
// ReadContext represents the context for reading a PDF file.
type ReadContext struct {
FileName string // The input PDF-File.
FileSize int64
rs io.ReadSeeker
BinaryTotalSize int64 // total stream data
BinaryImageSize int64 // total image stream data
BinaryFontSize int64 // total font stream data (fontfiles)
BinaryImageDuplSize int64 // total obsolet image stream data after optimization
BinaryFontDuplSize int64 // total obsolet font stream data after optimization
Linearized bool // File is linearized.
Hybrid bool // File is a hybrid PDF file.
UsingObjectStreams bool // File is using object streams.
ObjectStreams IntSet // All object numbers of any object streams found which need to be decoded.
UsingXRefStreams bool // File is using xref streams.
XRefStreams IntSet // All object numbers of any xref streams found.
}
func newReadContext(rs io.ReadSeeker, fileName string, fileSize int64) *ReadContext {
return &ReadContext{
rs: rs,
FileName: fileName,
FileSize: fileSize,
ObjectStreams: IntSet{},
XRefStreams: IntSet{},
}
}
// IsObjectStreamObject returns true if object i is a an object stream.
// All compressed objects are object streams.
func (rc *ReadContext) IsObjectStreamObject(i int) bool {
return rc.ObjectStreams[i]
}
// ObjectStreamsString returns a formatted string and the number of object stream objects.
func (rc *ReadContext) ObjectStreamsString() (int, string) {
var objs []int
for k := range rc.ObjectStreams {
if rc.ObjectStreams[k] {
objs = append(objs, k)
}
}
sort.Ints(objs)
var objStreams []string
for _, i := range objs {
objStreams = append(objStreams, fmt.Sprintf("%d", i))
}
return len(objStreams), strings.Join(objStreams, ",")
}
// IsXRefStreamObject returns true if object #i is a an xref stream.
func (rc *ReadContext) IsXRefStreamObject(i int) bool {
return rc.XRefStreams[i]
}
// XRefStreamsString returns a formatted string and the number of xref stream objects.
func (rc *ReadContext) XRefStreamsString() (int, string) {
var objs []int
for k := range rc.XRefStreams {
if rc.XRefStreams[k] {
objs = append(objs, k)
}
}
sort.Ints(objs)
var xrefStreams []string
for _, i := range objs {
xrefStreams = append(xrefStreams, fmt.Sprintf("%d", i))
}
return len(xrefStreams), strings.Join(xrefStreams, ",")
}
// LogStats logs stats for read file.
func (rc *ReadContext) LogStats(optimized bool) {
log := log.Stats
textSize := rc.FileSize - rc.BinaryTotalSize // = non binary content = non stream data
log.Println("Original:")
log.Printf("File Size : %s (%d bytes)\n", ByteSize(rc.FileSize), rc.FileSize)
log.Printf("Total Binary Data : %s (%d bytes) %4.1f%%\n", ByteSize(rc.BinaryTotalSize), rc.BinaryTotalSize, float32(rc.BinaryTotalSize)/float32(rc.FileSize)*100)
log.Printf("Total Text Data : %s (%d bytes) %4.1f%%\n\n", ByteSize(textSize), textSize, float32(textSize)/float32(rc.FileSize)*100)
// Only when optimizing we get details about resource data usage.
if optimized {
// Image stream data of original file.
binaryImageSize := rc.BinaryImageSize + rc.BinaryImageDuplSize
// Font stream data of original file. (just font files)
binaryFontSize := rc.BinaryFontSize + rc.BinaryFontDuplSize
// Content stream data, other font related stream data.
binaryOtherSize := rc.BinaryTotalSize - binaryImageSize - binaryFontSize
log.Println("Breakup of binary data:")
log.Printf("images : %s (%d bytes) %4.1f%%\n", ByteSize(binaryImageSize), binaryImageSize, float32(binaryImageSize)/float32(rc.BinaryTotalSize)*100)
log.Printf("fonts : %s (%d bytes) %4.1f%%\n", ByteSize(binaryFontSize), binaryFontSize, float32(binaryFontSize)/float32(rc.BinaryTotalSize)*100)
log.Printf("other : %s (%d bytes) %4.1f%%\n\n", ByteSize(binaryOtherSize), binaryOtherSize, float32(binaryOtherSize)/float32(rc.BinaryTotalSize)*100)
}
}
// ReadFileSize returns the size of the input file, if there is one.
func (rc *ReadContext) ReadFileSize() int {
if rc == nil {
return 0
}
return int(rc.FileSize)
}
// OptimizationContext represents the context for the optimiziation of a PDF file.
type OptimizationContext struct {
// Font section
PageFonts []IntSet // For each page a registry of font object numbers.
FontObjects map[int]*FontObject // FontObject lookup table by font object number.
Fonts map[string][]int // All font object numbers registered for a font name.
DuplicateFonts map[int]Dict // Registry of duplicate font dicts.
DuplicateFontObjs IntSet // The set of objects that represents the union of the object graphs of all duplicate font dicts.
// Image section
PageImages []IntSet // For each page a registry of image object numbers.
ImageObjects map[int]*ImageObject // ImageObject lookup table by image object number.
DuplicateImages map[int]*StreamDict // Registry of duplicate image dicts.
DuplicateImageObjs IntSet // The set of objects that represents the union of the object graphs of all duplicate image dicts.
DuplicateInfoObjects IntSet // Possible result of manual info dict modification.
NonReferencedObjs []int // Objects that are not referenced.
}
func newOptimizationContext() *OptimizationContext {
return &OptimizationContext{
FontObjects: map[int]*FontObject{},
Fonts: map[string][]int{},
DuplicateFonts: map[int]Dict{},
DuplicateFontObjs: IntSet{},
ImageObjects: map[int]*ImageObject{},
DuplicateImages: map[int]*StreamDict{},
DuplicateImageObjs: IntSet{},
DuplicateInfoObjects: IntSet{},
}
}
// IsDuplicateFontObject returns true if object #i is a duplicate font object.
func (oc *OptimizationContext) IsDuplicateFontObject(i int) bool {
return oc.DuplicateFontObjs[i]
}
// DuplicateFontObjectsString returns a formatted string and the number of objs.
func (oc *OptimizationContext) DuplicateFontObjectsString() (int, string) {
var objs []int
for k := range oc.DuplicateFontObjs {
if oc.DuplicateFontObjs[k] {
objs = append(objs, k)
}
}
sort.Ints(objs)
var dupFonts []string
for _, i := range objs {
dupFonts = append(dupFonts, fmt.Sprintf("%d", i))
}
return len(dupFonts), strings.Join(dupFonts, ",")
}
// IsDuplicateImageObject returns true if object #i is a duplicate image object.
func (oc *OptimizationContext) IsDuplicateImageObject(i int) bool {
return oc.DuplicateImageObjs[i]
}
// DuplicateImageObjectsString returns a formatted string and the number of objs.
func (oc *OptimizationContext) DuplicateImageObjectsString() (int, string) {
var objs []int
for k := range oc.DuplicateImageObjs {
if oc.DuplicateImageObjs[k] {
objs = append(objs, k)
}
}
sort.Ints(objs)
var dupImages []string
for _, i := range objs {
dupImages = append(dupImages, fmt.Sprintf("%d", i))
}
return len(dupImages), strings.Join(dupImages, ",")
}
// IsDuplicateInfoObject returns true if object #i is a duplicate info object.
func (oc *OptimizationContext) IsDuplicateInfoObject(i int) bool {
return oc.DuplicateInfoObjects[i]
}
// DuplicateInfoObjectsString returns a formatted string and the number of objs.
func (oc *OptimizationContext) DuplicateInfoObjectsString() (int, string) {
var objs []int
for k := range oc.DuplicateInfoObjects {
if oc.DuplicateInfoObjects[k] {
objs = append(objs, k)
}
}
sort.Ints(objs)
var dupInfos []string
for _, i := range objs {
dupInfos = append(dupInfos, fmt.Sprintf("%d", i))
}
return len(dupInfos), strings.Join(dupInfos, ",")
}
// NonReferencedObjsString returns a formatted string and the number of objs.
func (oc *OptimizationContext) NonReferencedObjsString() (int, string) {
var s []string
for _, o := range oc.NonReferencedObjs {
s = append(s, fmt.Sprintf("%d", o))
}
return len(oc.NonReferencedObjs), strings.Join(s, ",")
}
// Prepare info gathered about font usage in form of a string array.
func (oc *OptimizationContext) collectFontInfo(logStr []string) []string {
// Print available font info.
if len(oc.Fonts) == 0 || len(oc.PageFonts) == 0 {
return append(logStr, "No font info available.\n")
}
fontHeader := "obj prefix Fontname Subtype Encoding Embedded ResourceIds\n"
// Log fonts usage per page.
for i, fontObjectNumbers := range oc.PageFonts {
if len(fontObjectNumbers) == 0 {
continue
}
logStr = append(logStr, fmt.Sprintf("\nFonts for page %d:\n", i+1))
logStr = append(logStr, fontHeader)
var objectNumbers []int
for k := range fontObjectNumbers {
objectNumbers = append(objectNumbers, k)
}
sort.Ints(objectNumbers)
for _, objectNumber := range objectNumbers {
fontObject := oc.FontObjects[objectNumber]
logStr = append(logStr, fmt.Sprintf("#%-6d %s", objectNumber, fontObject))
}
}
// Log all fonts sorted by object number.
logStr = append(logStr, fmt.Sprintf("\nFontobjects:\n"))
logStr = append(logStr, fontHeader)
var objectNumbers []int
for k := range oc.FontObjects {
objectNumbers = append(objectNumbers, k)
}
sort.Ints(objectNumbers)
for _, objectNumber := range objectNumbers {
fontObject := oc.FontObjects[objectNumber]
logStr = append(logStr, fmt.Sprintf("#%-6d %s", objectNumber, fontObject))
}
// Log all fonts sorted by fontname.
logStr = append(logStr, fmt.Sprintf("\nFonts:\n"))
logStr = append(logStr, fontHeader)
var fontNames []string
for k := range oc.Fonts {
fontNames = append(fontNames, k)
}
sort.Strings(fontNames)
for _, fontName := range fontNames {
for _, objectNumber := range oc.Fonts[fontName] {
fontObject := oc.FontObjects[objectNumber]
logStr = append(logStr, fmt.Sprintf("#%-6d %s", objectNumber, fontObject))
}
}
logStr = append(logStr, fmt.Sprintf("\nDuplicate Fonts:\n"))
// Log any duplicate fonts.
if len(oc.DuplicateFonts) > 0 {
var objectNumbers []int
for k := range oc.DuplicateFonts {
objectNumbers = append(objectNumbers, k)
}
sort.Ints(objectNumbers)
var f []string
for _, i := range objectNumbers {
f = append(f, fmt.Sprintf("%d", i))
}
logStr = append(logStr, strings.Join(f, ","))
}
return append(logStr, "\n")
}
// Prepare info gathered about image usage in form of a string array.
func (oc *OptimizationContext) collectImageInfo(logStr []string) []string {
// Print available image info.
if len(oc.ImageObjects) == 0 {
return append(logStr, "\nNo image info available.\n")
}
imageHeader := "obj ResourceIds\n"
// Log images per page.
for i, imageObjectNumbers := range oc.PageImages {
if len(imageObjectNumbers) == 0 {
continue
}
logStr = append(logStr, fmt.Sprintf("\nImages for page %d:\n", i+1))
logStr = append(logStr, imageHeader)
var objectNumbers []int
for k := range imageObjectNumbers {
objectNumbers = append(objectNumbers, k)
}
sort.Ints(objectNumbers)
for _, objectNumber := range objectNumbers {
imageObject := oc.ImageObjects[objectNumber]
logStr = append(logStr, fmt.Sprintf("#%-6d %s\n", objectNumber, imageObject.ResourceNamesString()))
}
}
// Log all images sorted by object number.
logStr = append(logStr, fmt.Sprintf("\nImageobjects:\n"))
logStr = append(logStr, imageHeader)
var objectNumbers []int
for k := range oc.ImageObjects {
objectNumbers = append(objectNumbers, k)
}
sort.Ints(objectNumbers)
for _, objectNumber := range objectNumbers {
imageObject := oc.ImageObjects[objectNumber]
logStr = append(logStr, fmt.Sprintf("#%-6d %s\n", objectNumber, imageObject.ResourceNamesString()))
}
logStr = append(logStr, fmt.Sprintf("\nDuplicate Images:\n"))
// Log any duplicate images.
if len(oc.DuplicateImages) > 0 {
var objectNumbers []int
for k := range oc.DuplicateImages {
objectNumbers = append(objectNumbers, k)
}
sort.Ints(objectNumbers)
var f []string
for _, i := range objectNumbers {
f = append(f, fmt.Sprintf("%d", i))
}
logStr = append(logStr, strings.Join(f, ","))
}
return logStr
}
// WriteContext represents the context for writing a PDF file.
type WriteContext struct {
// The PDF-File which gets generated.
*bufio.Writer
DirName string
FileName string
FileSize int64
Command string // The processing command in effect.
SelectedPages IntSet // For split, trim and extract.
BinaryTotalSize int64 // total stream data, counts 100% all stream data written.
BinaryImageSize int64 // total image stream data written = Read.BinaryImageSize.
BinaryFontSize int64 // total font stream data (fontfiles) = copy of Read.BinaryFontSize.
Table map[int]int64 // object write offsets
Offset int64 // current write offset
WriteToObjectStream bool // if true start to embed objects into object streams and obey ObjectStreamMaxObjects.
CurrentObjStream *int // if not nil, any new non-stream-object gets added to the object stream with this object number.
Eol string // end of line char sequence
}
// NewWriteContext returns a new WriteContext.
func NewWriteContext(eol string) *WriteContext {
return &WriteContext{SelectedPages: IntSet{}, Table: map[int]int64{}, Eol: eol}
}
// SetWriteOffset saves the current write offset to the PDFDestination.
func (wc *WriteContext) SetWriteOffset(objNumber int) {
wc.Table[objNumber] = wc.Offset
}
// HasWriteOffset returns true if an object has already been written to PDFDestination.
func (wc *WriteContext) HasWriteOffset(objNumber int) bool {
_, found := wc.Table[objNumber]
return found
}
// ReducedFeatureSet returns true for Split,Trim,Merge,ExtractPages.
// Don't confuse with pdfcpu commands, these are internal triggers.
func (wc *WriteContext) ReducedFeatureSet() bool {
switch wc.Command {
case "Split", "Trim", "ExtractPages", "Merge", "Import":
return true
}
return false
}
// ExtractPage returns true if page i needs to be generated.
// func (wc *WriteContext) ExtractPage(i int) bool {
// if wc.ExtractPages == nil {
// return false
// }
// return wc.ExtractPages[i]
// }
// LogStats logs stats for written file.
func (wc *WriteContext) LogStats() {
fileSize := wc.FileSize
binaryTotalSize := wc.BinaryTotalSize // stream data
textSize := fileSize - binaryTotalSize // non stream data
binaryImageSize := wc.BinaryImageSize
binaryFontSize := wc.BinaryFontSize
binaryOtherSize := binaryTotalSize - binaryImageSize - binaryFontSize // content streams
log.Stats.Println("Optimized:")
log.Stats.Printf("File Size : %s (%d bytes)\n", ByteSize(fileSize), fileSize)
log.Stats.Printf("Total Binary Data : %s (%d bytes) %4.1f%%\n", ByteSize(binaryTotalSize), binaryTotalSize, float32(binaryTotalSize)/float32(fileSize)*100)
log.Stats.Printf("Total Text Data : %s (%d bytes) %4.1f%%\n\n", ByteSize(textSize), textSize, float32(textSize)/float32(fileSize)*100)
log.Stats.Println("Breakup of binary data:")
log.Stats.Printf("images : %s (%d bytes) %4.1f%%\n", ByteSize(binaryImageSize), binaryImageSize, float32(binaryImageSize)/float32(binaryTotalSize)*100)
log.Stats.Printf("fonts : %s (%d bytes) %4.1f%%\n", ByteSize(binaryFontSize), binaryFontSize, float32(binaryFontSize)/float32(binaryTotalSize)*100)
log.Stats.Printf("other : %s (%d bytes) %4.1f%%\n\n", ByteSize(binaryOtherSize), binaryOtherSize, float32(binaryOtherSize)/float32(binaryTotalSize)*100)
}
// WriteEol writes an end of line sequence.
func (wc *WriteContext) WriteEol() error {
_, err := wc.WriteString(wc.Eol)
return err
}