forked from pdfcpu/pdfcpu
/
nup.go
1086 lines (901 loc) · 25.1 KB
/
nup.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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 (
"bytes"
"fmt"
"io"
"math"
"os"
"sort"
"strconv"
"strings"
"github.com/88250/pdfcpu/pkg/filter"
"github.com/pkg/errors"
)
var (
errInvalidGridID = errors.New("pdfcpu nup: n must be one of 2, 3, 4, 6, 8, 9, 12, 16")
errInvalidGridDims = errors.New("pdfcpu grid: dimensions: m >= 0, n >= 0")
errInvalidNUpConfig = errors.New("pdfcpu: invalid configuration string")
)
var (
nUpValues = []int{2, 3, 4, 6, 8, 9, 12, 16}
nUpDims = map[int]Dim{
2: {2, 1},
3: {3, 1},
4: {2, 2},
6: {3, 2},
8: {4, 2},
9: {3, 3},
12: {4, 3},
16: {4, 4},
}
)
type nUpParamMap map[string]func(string, *NUp) error
var nupParamMap = nUpParamMap{
"dimensions": parseDimensionsNUp,
"formsize": parsePageFormatNUp,
"papersize": parsePageFormatNUp,
"orientation": parseOrientation,
"border": parseElementBorder,
"margin": parseElementMargin,
"backgroundcolor": parseSheetBackgroundColor,
"bgcolor": parseSheetBackgroundColor,
"guides": parseBookletGuides,
"multifolio": parseBookletMultifolio,
"foliosize": parseBookletFolioSize,
}
// Handle applies parameter completion and if successful
// parses the parameter values into import.
func (m nUpParamMap) Handle(paramPrefix, paramValueStr string, nup *NUp) error {
var param string
// Completion support
for k := range m {
if !strings.HasPrefix(k, paramPrefix) {
continue
}
if len(param) > 0 {
return errors.Errorf("pdfcpu: ambiguous parameter prefix \"%s\"", paramPrefix)
}
param = k
}
if param == "" {
return errors.Errorf("pdfcpu: ambiguous parameter prefix \"%s\"", paramPrefix)
}
return m[param](paramValueStr, nup)
}
// NUp represents the command details for the command "NUp".
type NUp struct {
PageDim *Dim // Page dimensions in display unit.
PageSize string // Paper size eg. A4L, A4P, A4(=default=A4P), see paperSize.go
UserDim bool // true if one of dimensions or paperSize provided overriding the default.
Orient orientation // One of rd(=default),dr,ld,dl
Grid *Dim // Intra page grid dimensions eg (2,2)
PageGrid bool // Create a mxn grid of pages for PDF inputfiles only (think "extra page n-Up").
ImgInputFile bool // Process image or PDF input files.
Margin int // Cropbox for n-Up content.
Border bool // Draw bounding box.
BookletGuides bool // Draw folding and cutting lines.
MultiFolio bool // Render booklet as sequence of folios.
FolioSize int // Booklet multifolio folio size: default: 8
InpUnit DisplayUnit // input display unit.
BgColor *SimpleColor // background color
}
// DefaultNUpConfig returns the default NUp configuration.
func DefaultNUpConfig() *NUp {
return &NUp{
PageSize: "A4",
Orient: RightDown,
Margin: 3,
Border: true,
}
}
func (nup NUp) String() string {
return fmt.Sprintf("N-Up conf: %s %s, orient=%s, grid=%s, pageGrid=%t, isImage=%t\n",
nup.PageSize, *nup.PageDim, nup.Orient, *nup.Grid, nup.PageGrid, nup.ImgInputFile)
}
// N returns the nUp value.
func (nup NUp) N() int {
return int(nup.Grid.Height * nup.Grid.Width)
}
type orientation int
func (o orientation) String() string {
switch o {
case RightDown:
return "right down"
case DownRight:
return "down right"
case LeftDown:
return "left down"
case DownLeft:
return "down left"
}
return ""
}
// These are the defined anchors for relative positioning.
const (
RightDown orientation = iota
DownRight
LeftDown
DownLeft
)
func parsePageFormatNUp(s string, nup *NUp) (err error) {
if nup.UserDim {
return errors.New("pdfcpu: only one of formsize(papersize) or dimensions allowed")
}
nup.PageDim, nup.PageSize, err = parsePageFormat(s)
nup.UserDim = true
return err
}
func parseDimensionsNUp(s string, nup *NUp) (err error) {
if nup.UserDim {
return errors.New("pdfcpu: only one of formsize(papersize) or dimensions allowed")
}
nup.PageDim, nup.PageSize, err = parsePageDim(s, nup.InpUnit)
nup.UserDim = true
return err
}
func parseOrientation(s string, nup *NUp) error {
switch s {
case "rd":
nup.Orient = RightDown
case "dr":
nup.Orient = DownRight
case "ld":
nup.Orient = LeftDown
case "dl":
nup.Orient = DownLeft
default:
return errors.Errorf("pdfcpu: unknown nUp orientation: %s", s)
}
return nil
}
func parseElementBorder(s string, nup *NUp) error {
switch strings.ToLower(s) {
case "on", "true", "t":
nup.Border = true
case "off", "false", "f":
nup.Border = false
default:
return errors.New("pdfcpu: nUp border, please provide one of: on/off true/false t/f")
}
return nil
}
func parseBookletGuides(s string, nup *NUp) error {
switch strings.ToLower(s) {
case "on", "true", "t":
nup.BookletGuides = true
case "off", "false", "f":
nup.BookletGuides = false
default:
return errors.New("pdfcpu: booklet guides, please provide one of: on/off true/false t/f")
}
return nil
}
func parseBookletMultifolio(s string, nup *NUp) error {
switch strings.ToLower(s) {
case "on", "true", "t":
nup.MultiFolio = true
case "off", "false", "f":
nup.MultiFolio = false
default:
return errors.New("pdfcpu: booklet guides, please provide one of: on/off true/false t/f")
}
return nil
}
func parseBookletFolioSize(s string, nup *NUp) error {
i, err := strconv.Atoi(s)
if err != nil {
return errors.Errorf("pdfcpu: illegal folio size: must be an numeric value, %s\n", s)
}
nup.FolioSize = i
return nil
}
func parseElementMargin(s string, nup *NUp) error {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return err
}
if f < 0 {
return errors.New("pdfcpu: nUp margin, Please provide a positive value")
}
nup.Margin = int(toUserSpace(f, nup.InpUnit))
return nil
}
func parseSheetBackgroundColor(s string, nup *NUp) error {
c, err := parseColor(s)
if err != nil {
return err
}
nup.BgColor = &c
return nil
}
// ParseNUpDetails parses a NUp command string into an internal structure.
func ParseNUpDetails(s string, nup *NUp) error {
if s == "" {
return errInvalidNUpConfig
}
ss := strings.Split(s, ",")
for _, s := range ss {
ss1 := strings.Split(s, ":")
if len(ss1) != 2 {
return errInvalidNUpConfig
}
paramPrefix := strings.TrimSpace(ss1[0])
paramValueStr := strings.TrimSpace(ss1[1])
if err := nupParamMap.Handle(paramPrefix, paramValueStr, nup); err != nil {
return err
}
}
return nil
}
// PDFNUpConfig returns an NUp configuration for Nup-ing PDF files.
func PDFNUpConfig(val int, desc string) (*NUp, error) {
nup := DefaultNUpConfig()
if desc != "" {
if err := ParseNUpDetails(desc, nup); err != nil {
return nil, err
}
}
return nup, ParseNUpValue(val, nup)
}
// ImageNUpConfig returns an NUp configuration for Nup-ing image files.
func ImageNUpConfig(val int, desc string) (*NUp, error) {
nup, err := PDFNUpConfig(val, desc)
if err != nil {
return nil, err
}
nup.ImgInputFile = true
return nup, nil
}
// PDFGridConfig returns a grid configuration for Nup-ing PDF files.
func PDFGridConfig(rows, cols int, desc string) (*NUp, error) {
nup := DefaultNUpConfig()
nup.PageGrid = true
if desc != "" {
if err := ParseNUpDetails(desc, nup); err != nil {
return nil, err
}
}
return nup, ParseNUpGridDefinition(rows, cols, nup)
}
// ImageGridConfig returns a grid configuration for Nup-ing image files.
func ImageGridConfig(rows, cols int, desc string) (*NUp, error) {
nup, err := PDFGridConfig(rows, cols, desc)
if err != nil {
return nil, err
}
nup.ImgInputFile = true
return nup, nil
}
// ParseNUpValue parses the NUp value into an internal structure.
func ParseNUpValue(n int, nUp *NUp) error {
if !IntMemberOf(n, nUpValues) {
return errInvalidGridID
}
// The n-Up layout depends on the orientation of the chosen output paper size.
// This optional paper size may also be specified by dimensions in user unit.
// The default paper size is A4 or A4P (A4 in portrait mode) respectively.
var portrait bool
if nUp.PageDim == nil {
portrait = PaperSize[nUp.PageSize].Portrait()
} else {
portrait = RectForDim(nUp.PageDim.Width, nUp.PageDim.Height).Portrait()
}
d := nUpDims[n]
if portrait {
d.Width, d.Height = d.Height, d.Width
}
nUp.Grid = &d
return nil
}
// ParseNUpGridDefinition parses NUp grid dimensions into an internal structure.
func ParseNUpGridDefinition(rows, cols int, nUp *NUp) error {
m := cols
if m <= 0 {
return errInvalidGridDims
}
n := rows
if m <= 0 {
return errInvalidGridDims
}
nUp.Grid = &Dim{float64(m), float64(n)}
return nil
}
func rectsForGrid(nup *NUp) []*Rectangle {
cols := int(nup.Grid.Width)
rows := int(nup.Grid.Height)
maxX := float64(nup.PageDim.Width)
maxY := float64(nup.PageDim.Height)
gw := maxX / float64(cols)
gh := maxY / float64(rows)
var llx, lly float64
rr := []*Rectangle{}
switch nup.Orient {
case RightDown:
for i := rows - 1; i >= 0; i-- {
for j := 0; j < cols; j++ {
llx = float64(j) * gw
lly = float64(i) * gh
rr = append(rr, Rect(llx, lly, llx+gw, lly+gh))
}
}
case DownRight:
for i := 0; i < cols; i++ {
for j := rows - 1; j >= 0; j-- {
llx = float64(i) * gw
lly = float64(j) * gh
rr = append(rr, Rect(llx, lly, llx+gw, lly+gh))
}
}
case LeftDown:
for i := rows - 1; i >= 0; i-- {
for j := cols - 1; j >= 0; j-- {
llx = float64(j) * gw
lly = float64(i) * gh
rr = append(rr, Rect(llx, lly, llx+gw, lly+gh))
}
}
case DownLeft:
for i := cols - 1; i >= 0; i-- {
for j := rows - 1; j >= 0; j-- {
llx = float64(i) * gw
lly = float64(j) * gh
rr = append(rr, Rect(llx, lly, llx+gw, lly+gh))
}
}
}
return rr
}
func bestFitRectIntoRect(rSrc, rDest *Rectangle, enforceOrient bool) (w, h, dx, dy, rot float64) {
if rSrc.FitsWithin(rDest) {
// Translate rSrc into center of rDest without scaling.
w = rSrc.Width()
h = rSrc.Height()
dx = rDest.Width()/2 - rSrc.Width()/2
dy = rDest.Height()/2 - rSrc.Height()/2
return
}
if rSrc.Landscape() {
if rDest.Landscape() {
if rSrc.AspectRatio() > rDest.AspectRatio() {
w = rDest.Width()
h = rSrc.ScaledHeight(w)
dy = (rDest.Height() - h) / 2
} else {
h = rDest.Height()
w = rSrc.ScaledWidth(h)
dx = (rDest.Width() - w) / 2
}
} else {
if enforceOrient {
rot = 90
if 1/rSrc.AspectRatio() < rDest.AspectRatio() {
w = rDest.Height()
h = rSrc.ScaledHeight(w)
dx = (rDest.Width() - h) / 2
} else {
h = rDest.Width()
w = rSrc.ScaledWidth(h)
dy = (rDest.Height() - w) / 2
}
return
}
w = rDest.Width()
h = rSrc.ScaledHeight(w)
dy = (rDest.Height() - h) / 2
}
return
}
if rSrc.Portrait() {
if rDest.Portrait() {
if rSrc.AspectRatio() < rDest.AspectRatio() {
h = rDest.Height()
w = rSrc.ScaledWidth(h)
dx = (rDest.Width() - w) / 2
} else {
w = rDest.Width()
h = rSrc.ScaledHeight(w)
dy = (rDest.Height() - h) / 2
}
} else {
if enforceOrient {
rot = 90
if 1/rSrc.AspectRatio() > rDest.AspectRatio() {
h = rDest.Width()
w = rSrc.ScaledWidth(h)
dy = (rDest.Height() - w) / 2
} else {
w = rDest.Height()
h = rSrc.ScaledHeight(w)
dx = (rDest.Width() - h) / 2
}
return
}
h = rDest.Height()
w = rSrc.ScaledWidth(h)
dx = (rDest.Width() - w) / 2
}
return
}
w = rDest.Height()
if rDest.Portrait() {
w = rDest.Width()
}
h = w
dx = rDest.Width()/2 - rSrc.Width()/2
dy = rDest.Height()/2 - rSrc.Height()/2
return
}
func nUpTilePDFBytes(wr io.Writer, rSrc, rDest *Rectangle, formResID string, nup *NUp, rotate, enforceOrient bool) {
// rScr is a rectangular region represented by form formResID in form space.
// rDest is an arbitrary rectangular region in dest space.
// It is the location where we want the form content to get rendered on a "best fit" basis.
// Accounting for the aspect ratios of rSrc and rDest "best fit" tries to fit the largest version of rScr into rDest.
// This may result in a 90 degree rotation.
//
// rotate:
// indicates if we need to apply a post rotation of 180 degrees eg for booklets.
//
// enforceOrient:
// indicates if we need to enforce dest's orientation.
// Draw bounding box.
if nup.Border {
fmt.Fprintf(wr, "[]0 d 0.1 w %.2f %.2f m %.2f %.2f l %.2f %.2f l %.2f %.2f l s ",
rDest.LL.X, rDest.LL.Y, rDest.UR.X, rDest.LL.Y, rDest.UR.X, rDest.UR.Y, rDest.LL.X, rDest.UR.Y,
)
}
// Apply margin to rDest which potentially makes it smaller.
rDestCr := rDest.CroppedCopy(float64(nup.Margin))
// Calculate transform matrix.
// Best fit translation of a source rectangle into a destination rectangle.
// For nup we enforce the dest orientation,
// whereas in cases where the original orientation needs to be preserved eg. for booklets, we don't.
w, h, dx, dy, r := bestFitRectIntoRect(rSrc, rDestCr, enforceOrient)
if nup.BgColor != nil {
if nup.ImgInputFile {
// Fill background.
FillRectStacked(wr, rDest, *nup.BgColor)
} else if nup.Margin > 0 {
// Fill margins.
m := float64(nup.Margin)
drawMargins(wr, *nup.BgColor, rDest, 0, m, m, m, m)
}
}
// Apply additional rotation.
if rotate {
r += 180
}
sx := w
sy := h
if !nup.ImgInputFile {
sx /= rSrc.Width()
sy /= rSrc.Height()
}
sin := math.Sin(r * float64(degToRad))
cos := math.Cos(r * float64(degToRad))
switch r {
case 90:
dx += h
case 180:
dx += w
dy += h
case 270:
dy += w
}
dx += rDestCr.LL.X
dy += rDestCr.LL.Y
m := calcTransformMatrix(sx, sy, sin, cos, dx, dy)
// Apply transform matrix and display form.
fmt.Fprintf(wr, "q %.2f %.2f %.2f %.2f %.2f %.2f cm /%s Do Q ",
m[0][0], m[0][1], m[1][0], m[1][1], m[2][0], m[2][1], formResID)
}
func nUpImagePDFBytes(w io.Writer, imgWidth, imgHeight int, nup *NUp, formResID string) {
for _, r := range rectsForGrid(nup) {
// Append to content stream.
nUpTilePDFBytes(w, RectForDim(float64(imgWidth), float64(imgHeight)), r, formResID, nup, false, true)
}
}
func createNUpFormForImage(xRefTable *XRefTable, imgIndRef *IndirectRef, w, h, i int) (*IndirectRef, error) {
imgResID := fmt.Sprintf("Im%d", i)
bb := RectForDim(float64(w), float64(h))
var b bytes.Buffer
fmt.Fprintf(&b, "/%s Do ", imgResID)
d := Dict(
map[string]Object{
"ProcSet": NewNameArray("PDF", "Text", "ImageB", "ImageC", "ImageI"),
"XObject": Dict(map[string]Object{imgResID: *imgIndRef}),
},
)
ir, err := xRefTable.IndRefForNewObject(d)
if err != nil {
return nil, err
}
sd := StreamDict{
Dict: Dict(
map[string]Object{
"Type": Name("XObject"),
"Subtype": Name("Form"),
"BBox": bb.Array(),
"Matrix": NewIntegerArray(1, 0, 0, 1, 0, 0),
"Resources": *ir,
},
),
Content: b.Bytes(),
FilterPipeline: []PDFFilter{{Name: filter.Flate, DecodeParms: nil}},
}
sd.InsertName("Filter", filter.Flate)
if err = sd.Encode(); err != nil {
return nil, err
}
return xRefTable.IndRefForNewObject(sd)
}
func createNUpFormForPDF(xRefTable *XRefTable, resDict *IndirectRef, content []byte, cropBox *Rectangle) (*IndirectRef, error) {
sd := StreamDict{
Dict: Dict(
map[string]Object{
"Type": Name("XObject"),
"Subtype": Name("Form"),
"BBox": cropBox.Array(),
"Matrix": NewNumberArray(1, 0, 0, 1, -cropBox.LL.X, -cropBox.LL.Y),
"Resources": *resDict,
},
),
Content: content,
FilterPipeline: []PDFFilter{{Name: filter.Flate, DecodeParms: nil}},
}
sd.InsertName("Filter", filter.Flate)
if err := sd.Encode(); err != nil {
return nil, err
}
return xRefTable.IndRefForNewObject(sd)
}
// NewNUpPageForImage creates a new page dict in xRefTable for given image filename and n-up conf.
func NewNUpPageForImage(xRefTable *XRefTable, fileName string, parentIndRef *IndirectRef, nup *NUp) (*IndirectRef, error) {
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
// create image dict.
imgIndRef, w, h, err := createImageResource(xRefTable, f, false, false)
if err != nil {
return nil, err
}
resID := 0
formIndRef, err := createNUpFormForImage(xRefTable, imgIndRef, w, h, resID)
if err != nil {
return nil, err
}
formResID := fmt.Sprintf("Fm%d", resID)
resourceDict := Dict(
map[string]Object{
"XObject": Dict(map[string]Object{formResID: *formIndRef}),
},
)
resIndRef, err := xRefTable.IndRefForNewObject(resourceDict)
if err != nil {
return nil, err
}
var buf bytes.Buffer
nUpImagePDFBytes(&buf, w, h, nup, formResID)
sd, _ := xRefTable.NewStreamDictForBuf(buf.Bytes())
if err = sd.Encode(); err != nil {
return nil, err
}
contentsIndRef, err := xRefTable.IndRefForNewObject(*sd)
if err != nil {
return nil, err
}
dim := nup.PageDim
mediaBox := RectForDim(dim.Width, dim.Height)
pageDict := Dict(
map[string]Object{
"Type": Name("Page"),
"Parent": *parentIndRef,
"MediaBox": mediaBox.Array(),
"Resources": *resIndRef,
"Contents": *contentsIndRef,
},
)
return xRefTable.IndRefForNewObject(pageDict)
}
// NUpFromOneImage creates one page with instances of one image.
func NUpFromOneImage(ctx *Context, fileName string, nup *NUp, pagesDict Dict, pagesIndRef *IndirectRef) error {
indRef, err := NewNUpPageForImage(ctx.XRefTable, fileName, pagesIndRef, nup)
if err != nil {
return err
}
if err = AppendPageTree(indRef, 1, pagesDict); err != nil {
return err
}
ctx.PageCount++
return nil
}
func wrapUpPage(ctx *Context, nup *NUp, d Dict, buf bytes.Buffer, pagesDict Dict, pagesIndRef *IndirectRef) error {
xRefTable := ctx.XRefTable
var fm FontMap
if nup.BookletGuides {
// For booklets only.
fm = drawBookletGuides(nup, &buf)
}
resourceDict := Dict(
map[string]Object{
"XObject": d,
},
)
fontRes, err := fontResources(xRefTable, fm)
if err != nil {
return err
}
if len(fontRes) > 0 {
resourceDict["Font"] = fontRes
}
resIndRef, err := xRefTable.IndRefForNewObject(resourceDict)
if err != nil {
return err
}
sd, _ := xRefTable.NewStreamDictForBuf(buf.Bytes())
if err = sd.Encode(); err != nil {
return err
}
contentsIndRef, err := xRefTable.IndRefForNewObject(*sd)
if err != nil {
return err
}
dim := nup.PageDim
mediaBox := RectForDim(dim.Width, dim.Height)
pageDict := Dict(
map[string]Object{
"Type": Name("Page"),
"Parent": *pagesIndRef,
"MediaBox": mediaBox.Array(),
"Resources": *resIndRef,
"Contents": *contentsIndRef,
},
)
indRef, err := xRefTable.IndRefForNewObject(pageDict)
if err != nil {
return err
}
if err = AppendPageTree(indRef, 1, pagesDict); err != nil {
return err
}
ctx.PageCount++
return nil
}
// NUpFromMultipleImages creates pages in NUp-style rendering each image once.
func NUpFromMultipleImages(ctx *Context, fileNames []string, nup *NUp, pagesDict Dict, pagesIndRef *IndirectRef) error {
if nup.PageGrid {
nup.PageDim.Width *= nup.Grid.Width
nup.PageDim.Height *= nup.Grid.Height
}
xRefTable := ctx.XRefTable
formsResDict := NewDict()
var buf bytes.Buffer
rr := rectsForGrid(nup)
// fileCount must be a multiple of n.
// If not, we will insert blank pages at the end.
fileCount := len(fileNames)
if fileCount%nup.N() != 0 {
fileCount += nup.N() - fileCount%nup.N()
}
for i := 0; i < fileCount; i++ {
if i > 0 && i%len(rr) == 0 {
// Wrap complete nUp page.
if err := wrapUpPage(ctx, nup, formsResDict, buf, pagesDict, pagesIndRef); err != nil {
return err
}
buf.Reset()
formsResDict = NewDict()
}
rDest := rr[i%len(rr)]
var fileName string
if i < len(fileNames) {
fileName = fileNames[i]
}
if fileName == "" {
// This is an empty page at the end.
if nup.BgColor != nil {
FillRectStacked(&buf, rDest, *nup.BgColor)
}
continue
}
f, err := os.Open(fileName)
if err != nil {
return err
}
imgIndRef, w, h, err := createImageResource(xRefTable, f, false, false)
if err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
formIndRef, err := createNUpFormForImage(xRefTable, imgIndRef, w, h, i)
if err != nil {
return err
}
formResID := fmt.Sprintf("Fm%d", i)
formsResDict.Insert(formResID, *formIndRef)
// Append to content stream of page i.
nUpTilePDFBytes(&buf, RectForDim(float64(w), float64(h)), rr[i%len(rr)], formResID, nup, false, true)
}
// Wrap incomplete nUp page.
return wrapUpPage(ctx, nup, formsResDict, buf, pagesDict, pagesIndRef)
}
func sortSelectedPages(pages IntSet) []int {
var pageNumbers []int
for k, v := range pages {
if v {
pageNumbers = append(pageNumbers, k)
}
}
sort.Ints(pageNumbers)
return pageNumbers
}
func nupPageNumber(i int, sortedPageNumbers []int) int {
var pageNumber int
if i < len(sortedPageNumbers) {
pageNumber = sortedPageNumbers[i]
}
return pageNumber
}
func (ctx *Context) nUpTilePDFBytesForPDF(
pageNr int,
formsResDict Dict,
buf *bytes.Buffer,
rDest *Rectangle,
nup *NUp,
rotate bool) error {
consolidateRes := true
d, _, inhPAttrs, err := ctx.PageDict(pageNr, consolidateRes)
if err != nil {
return err
}
if d == nil {
return errors.Errorf("pdfcpu: unknown page number: %d\n", pageNr)
}
// Retrieve content stream bytes.
bb, err := ctx.PageContent(d)
if err == errNoContent {
// TODO render if has annotations.
return nil
}
if err != nil {
return err
}
// Create an object for this resDict in xRefTable.
ir, err := ctx.IndRefForNewObject(inhPAttrs.resources)
if err != nil {
return err
}
cropBox := inhPAttrs.mediaBox
if inhPAttrs.cropBox != nil {
cropBox = inhPAttrs.cropBox
}
// Account for existing rotation.
if inhPAttrs.rotate != 0 {
if IntMemberOf(inhPAttrs.rotate, []int{+90, -90, +270, -270}) {
w := cropBox.Width()
cropBox.UR.X = cropBox.LL.X + cropBox.Height()
cropBox.UR.Y = cropBox.LL.Y + w
}
bb = append(contentBytesForPageRotation(inhPAttrs.rotate, cropBox.Width(), cropBox.Height()), bb...)
}
formIndRef, err := createNUpFormForPDF(ctx.XRefTable, ir, bb, cropBox)
if err != nil {
return err
}
formResID := fmt.Sprintf("Fm%d", pageNr)
formsResDict.Insert(formResID, *formIndRef)
// Append to content stream buf of destination page.
nUpTilePDFBytes(buf, cropBox, rDest, formResID, nup, rotate, true)
return nil
}
func (ctx *Context) nupPages(
selectedPages IntSet,
nup *NUp,
pagesDict Dict,
pagesIndRef *IndirectRef) error {
var buf bytes.Buffer
formsResDict := NewDict()
rr := rectsForGrid(nup)
sortedPageNumbers := sortSelectedPages(selectedPages)
pageCount := len(sortedPageNumbers)
// pageCount must be a multiple of n.
// If not, we will insert blank pages at the end.
if pageCount%nup.N() != 0 {
pageCount += nup.N() - pageCount%nup.N()
}
for i := 0; i < pageCount; i++ {
if i > 0 && i%len(rr) == 0 {
// Wrap complete page.
if err := wrapUpPage(ctx, nup, formsResDict, buf, pagesDict, pagesIndRef); err != nil {
return err
}
buf.Reset()
formsResDict = NewDict()
}
rDest := rr[i%len(rr)]