forked from caj2pdf/caj2pdf
-
Notifications
You must be signed in to change notification settings - Fork 274
/
pdfwutils.py
3261 lines (2953 loc) · 109 KB
/
pdfwutils.py
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
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2014 Johannes 'josch' Schauer <j.schauer at email.de>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser 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
# <http://www.gnu.org/licenses/>.
# Portions Copyright 2021 (c) Hin-Tak Leung <[email protected]>
# - img2pdf 0.3.4 renamed and adapted for usage by caj2pdf
#
# The main changes are:
#
# - removal of large GUI routine and dependencies on PIL
# (and zlib.deflate 1-bit input, rather than ccitt-g4 compress them)
#
# - different default dpi, inverting images
#
# - allow feeding input images directly from memory, instead of reading from disk
#
# - remove dependency on pdfrw
import sys
import os
import zlib
import argparse
#from PIL import Image
# TiffImagePlugin.DEBUG = True
from datetime import datetime
#from jp2 import parsejp2
from enum import Enum
from io import BytesIO
import logging
import struct
import platform
PY3 = sys.version_info[0] >= 3
__version__ = "0.3.4"
default_dpi = 300.0
papersizes = {
"letter": "8.5inx11in",
"a0": "841mmx1189mm",
"a1": "594mmx841mm",
"a2": "420mmx594mm",
"a3": "297mmx420mm",
"a4": "210mmx297mm",
"a5": "148mmx210mm",
"a6": "105mmx148mm",
"legal": "8.5inx14in",
"tabloid": "11inx17in",
}
papernames = {
"letter": "Letter",
"a0": "A0",
"a1": "A1",
"a2": "A2",
"a3": "A3",
"a4": "A4",
"a5": "A5",
"a6": "A6",
"legal": "Legal",
"tabloid": "Tabloid",
}
FitMode = Enum("FitMode", "into fill exact shrink enlarge")
PageOrientation = Enum("PageOrientation", "portrait landscape")
Colorspace = Enum("Colorspace", "RGB L 1 CMYK CMYK;I RGBA P other")
ImageFormat = Enum("ImageFormat", "JPEG JPEG2000 CCITTGroup4 PNG TIFF PBM other")
PageMode = Enum("PageMode", "none outlines thumbs")
PageLayout = Enum("PageLayout", "single onecolumn twocolumnright twocolumnleft")
Magnification = Enum("Magnification", "fit fith fitbh")
ImgSize = Enum("ImgSize", "abs perc dpi")
Unit = Enum("Unit", "pt cm mm inch")
ImgUnit = Enum("ImgUnit", "pt cm mm inch perc dpi")
TIFFBitRevTable = [
0x00,
0x80,
0x40,
0xC0,
0x20,
0xA0,
0x60,
0xE0,
0x10,
0x90,
0x50,
0xD0,
0x30,
0xB0,
0x70,
0xF0,
0x08,
0x88,
0x48,
0xC8,
0x28,
0xA8,
0x68,
0xE8,
0x18,
0x98,
0x58,
0xD8,
0x38,
0xB8,
0x78,
0xF8,
0x04,
0x84,
0x44,
0xC4,
0x24,
0xA4,
0x64,
0xE4,
0x14,
0x94,
0x54,
0xD4,
0x34,
0xB4,
0x74,
0xF4,
0x0C,
0x8C,
0x4C,
0xCC,
0x2C,
0xAC,
0x6C,
0xEC,
0x1C,
0x9C,
0x5C,
0xDC,
0x3C,
0xBC,
0x7C,
0xFC,
0x02,
0x82,
0x42,
0xC2,
0x22,
0xA2,
0x62,
0xE2,
0x12,
0x92,
0x52,
0xD2,
0x32,
0xB2,
0x72,
0xF2,
0x0A,
0x8A,
0x4A,
0xCA,
0x2A,
0xAA,
0x6A,
0xEA,
0x1A,
0x9A,
0x5A,
0xDA,
0x3A,
0xBA,
0x7A,
0xFA,
0x06,
0x86,
0x46,
0xC6,
0x26,
0xA6,
0x66,
0xE6,
0x16,
0x96,
0x56,
0xD6,
0x36,
0xB6,
0x76,
0xF6,
0x0E,
0x8E,
0x4E,
0xCE,
0x2E,
0xAE,
0x6E,
0xEE,
0x1E,
0x9E,
0x5E,
0xDE,
0x3E,
0xBE,
0x7E,
0xFE,
0x01,
0x81,
0x41,
0xC1,
0x21,
0xA1,
0x61,
0xE1,
0x11,
0x91,
0x51,
0xD1,
0x31,
0xB1,
0x71,
0xF1,
0x09,
0x89,
0x49,
0xC9,
0x29,
0xA9,
0x69,
0xE9,
0x19,
0x99,
0x59,
0xD9,
0x39,
0xB9,
0x79,
0xF9,
0x05,
0x85,
0x45,
0xC5,
0x25,
0xA5,
0x65,
0xE5,
0x15,
0x95,
0x55,
0xD5,
0x35,
0xB5,
0x75,
0xF5,
0x0D,
0x8D,
0x4D,
0xCD,
0x2D,
0xAD,
0x6D,
0xED,
0x1D,
0x9D,
0x5D,
0xDD,
0x3D,
0xBD,
0x7D,
0xFD,
0x03,
0x83,
0x43,
0xC3,
0x23,
0xA3,
0x63,
0xE3,
0x13,
0x93,
0x53,
0xD3,
0x33,
0xB3,
0x73,
0xF3,
0x0B,
0x8B,
0x4B,
0xCB,
0x2B,
0xAB,
0x6B,
0xEB,
0x1B,
0x9B,
0x5B,
0xDB,
0x3B,
0xBB,
0x7B,
0xFB,
0x07,
0x87,
0x47,
0xC7,
0x27,
0xA7,
0x67,
0xE7,
0x17,
0x97,
0x57,
0xD7,
0x37,
0xB7,
0x77,
0xF7,
0x0F,
0x8F,
0x4F,
0xCF,
0x2F,
0xAF,
0x6F,
0xEF,
0x1F,
0x9F,
0x5F,
0xDF,
0x3F,
0xBF,
0x7F,
0xFF,
]
class NegativeDimensionError(Exception):
pass
class UnsupportedColorspaceError(Exception):
pass
class ImageOpenError(Exception):
pass
class JpegColorspaceError(Exception):
pass
class PdfTooLargeError(Exception):
pass
class AlphaChannelError(Exception):
pass
class ExifOrientationError(Exception):
pass
# without pdfrw this function is a no-op
def my_convert_load(string):
return string
def parse(cont, indent=1):
if type(cont) is dict:
return (
b"<<\n"
+ b"\n".join(
[
4 * indent * b" " + k + b" " + parse(v, indent + 1)
for k, v in sorted(cont.items())
]
)
+ b"\n"
+ 4 * (indent - 1) * b" "
+ b">>"
)
elif type(cont) is int:
return str(cont).encode()
elif type(cont) is float:
if int(cont) == cont:
return parse(int(cont))
else:
return ("%0.4f" % cont).rstrip("0").encode()
elif isinstance(cont, MyPdfDict):
# if cont got an identifier, then addobj() has been called with it
# and a link to it will be added, otherwise add it inline
if hasattr(cont, "identifier"):
return ("%d 0 R" % cont.identifier).encode()
else:
return parse(cont.content, indent)
elif type(cont) is str or isinstance(cont, bytes):
if type(cont) is str and type(cont) is not bytes:
raise TypeError(
"parse must be passed a bytes object in py3. Got: %s" % cont
)
return cont
elif isinstance(cont, list):
return b"[ " + b" ".join([parse(c, indent) for c in cont]) + b" ]"
else:
raise TypeError("cannot handle type %s with content %s" % (type(cont), cont))
class MyPdfDict(object):
def __init__(self, *args, **kw):
self.content = dict()
if args:
if len(args) == 1:
args = args[0]
self.content.update(args)
self.stream = None
for key, value in kw.items():
if key == "stream":
self.stream = value
self.content[MyPdfName.Length] = len(value)
elif key == "indirect":
pass
else:
self.content[getattr(MyPdfName, key)] = value
def tostring(self):
if self.stream is not None:
return (
("%d 0 obj\n" % self.identifier).encode()
+ parse(self.content)
+ b"\nstream\n"
+ self.stream
+ b"\nendstream\nendobj\n"
)
else:
return (
("%d 0 obj\n" % self.identifier).encode()
+ parse(self.content)
+ b"\nendobj\n"
)
def __setitem__(self, key, value):
self.content[key] = value
def __getitem__(self, key):
return self.content[key]
def __contains__(self, key):
return key in self.content
class MyPdfName:
def __getattr__(self, name):
return b"/" + name.encode("ascii")
MyPdfName = MyPdfName()
class MyPdfObject(bytes):
def __new__(cls, string):
return bytes.__new__(cls, string.encode("ascii"))
class MyPdfArray(list):
pass
class MyPdfWriter:
def __init__(self, version="1.3"):
self.objects = []
# create an incomplete pages object so that a /Parent entry can be
# added to each page
self.pages = MyPdfDict(Type=MyPdfName.Pages, Kids=[], Count=0)
self.catalog = MyPdfDict(Pages=self.pages, Type=MyPdfName.Catalog)
self.version = version # default pdf version 1.3
self.pagearray = []
def addobj(self, obj):
newid = len(self.objects) + 1
obj.identifier = newid
self.objects.append(obj)
def tostream(self, info, stream):
xreftable = list()
# justification of the random binary garbage in the header from
# adobe:
#
# > Note: If a PDF file contains binary data, as most do (see Section
# > 3.1, “Lexical Conventions”), it is recommended that the header
# > line be immediately followed by a comment line containing at
# > least four binary characters—that is, characters whose codes are
# > 128 or greater. This ensures proper behavior of file transfer
# > applications that inspect data near the beginning of a file to
# > determine whether to treat the file’s contents as text or as
# > binary.
#
# the choice of binary characters is arbitrary but those four seem to
# be used elsewhere.
pdfheader = ("%%PDF-%s\n" % self.version).encode("ascii")
pdfheader += b"%\xe2\xe3\xcf\xd3\n"
stream.write(pdfheader)
# From section 3.4.3 of the PDF Reference (version 1.7):
#
# > Each entry is exactly 20 bytes long, including the end-of-line
# > marker.
# >
# > [...]
# >
# > The format of an in-use entry is
# > nnnnnnnnnn ggggg n eol
# > where
# > nnnnnnnnnn is a 10-digit byte offset
# > ggggg is a 5-digit generation number
# > n is a literal keyword identifying this as an in-use entry
# > eol is a 2-character end-of-line sequence
# >
# > [...]
# >
# > If the file’s end-of-line marker is a single character (either a
# > carriage return or a line feed), it is preceded by a single space;
#
# Since we chose to use a single character eol marker, we precede it by
# a space
pos = len(pdfheader)
xreftable.append(b"0000000000 65535 f \n")
for o in self.objects:
xreftable.append(("%010d 00000 n \n" % pos).encode())
content = o.tostring()
stream.write(content)
pos += len(content)
xrefoffset = pos
stream.write(b"xref\n")
stream.write(("0 %d\n" % len(xreftable)).encode())
for x in xreftable:
stream.write(x)
stream.write(b"trailer\n")
stream.write(
parse({b"/Size": len(xreftable), b"/Info": info, b"/Root": self.catalog})
+ b"\n"
)
stream.write(b"startxref\n")
stream.write(("%d\n" % xrefoffset).encode())
stream.write(b"%%EOF\n")
return
def addpage(self, page):
page[b"/Parent"] = self.pages
self.pagearray.append(page)
self.pages.content[b"/Kids"].append(page)
self.pages.content[b"/Count"] += 1
self.addobj(page)
if PY3:
class MyPdfString:
@classmethod
def encode(cls, string, hextype=False):
if hextype:
return (
b"< "
+ b" ".join(("%06x" % c).encode("ascii") for c in string)
+ b" >"
)
else:
try:
string = string.encode("ascii")
except UnicodeEncodeError:
string = b"\xfe\xff" + string.encode("utf-16-be")
# We should probably encode more here because at least
# ghostscript interpretes a carriage return byte (0x0D) as a
# new line byte (0x0A)
# PDF supports: \n, \r, \t, \b and \f
string = string.replace(b"\\", b"\\\\")
string = string.replace(b"(", b"\\(")
string = string.replace(b")", b"\\)")
return b"(" + string + b")"
else:
class MyPdfString(object):
@classmethod
def encode(cls, string, hextype=False):
if hextype:
return (
b"< "
+ b" ".join(("%06x" % c).encode("ascii") for c in string)
+ b" >"
)
else:
# This mimics exactely to what pdfrw does.
string = string.replace(b"\\", b"\\\\")
string = string.replace(b"(", b"\\(")
string = string.replace(b")", b"\\)")
return b"(" + string + b")"
class pdfdoc(object):
def __init__(
self,
version="1.3",
title=None,
author=None,
creator=None,
producer=None,
creationdate=None,
moddate=None,
subject=None,
keywords=None,
nodate=False,
panes=None,
initial_page=None,
magnification=None,
page_layout=None,
fit_window=False,
center_window=False,
fullscreen=False,
with_pdfrw=False,
):
if with_pdfrw:
try:
from pdfrw import PdfWriter, PdfDict, PdfName, PdfString
self.with_pdfrw = True
except ImportError:
PdfWriter = MyPdfWriter
PdfDict = MyPdfDict
PdfName = MyPdfName
PdfString = MyPdfString
self.with_pdfrw = False
else:
PdfWriter = MyPdfWriter
PdfDict = MyPdfDict
PdfName = MyPdfName
PdfString = MyPdfString
self.with_pdfrw = False
now = datetime.now()
self.info = PdfDict(indirect=True)
def datetime_to_pdfdate(dt):
return dt.strftime("%Y%m%d%H%M%SZ")
if title is not None:
self.info[PdfName.Title] = PdfString.encode(title)
if author is not None:
self.info[PdfName.Author] = PdfString.encode(author)
if creator is not None:
self.info[PdfName.Creator] = PdfString.encode(creator)
if producer is not None and producer != "":
self.info[PdfName.Producer] = PdfString.encode(producer)
if creationdate is not None:
self.info[PdfName.CreationDate] = PdfString.encode(
"D:" + datetime_to_pdfdate(creationdate)
)
elif not nodate:
self.info[PdfName.CreationDate] = PdfString.encode(
"D:" + datetime_to_pdfdate(now)
)
if moddate is not None:
self.info[PdfName.ModDate] = PdfString.encode(
"D:" + datetime_to_pdfdate(moddate)
)
elif not nodate:
self.info[PdfName.ModDate] = PdfString.encode(
"D:" + datetime_to_pdfdate(now)
)
if subject is not None:
self.info[PdfName.Subject] = PdfString.encode(subject)
if keywords is not None:
self.info[PdfName.Keywords] = PdfString.encode(",".join(keywords))
self.writer = PdfWriter()
self.writer.version = version
# this is done because pdfrw adds info, catalog and pages as the first
# three objects in this order
if not self.with_pdfrw:
self.writer.addobj(self.info)
self.writer.addobj(self.writer.catalog)
self.writer.addobj(self.writer.pages)
self.panes = panes
self.initial_page = initial_page
self.magnification = magnification
self.page_layout = page_layout
self.fit_window = fit_window
self.center_window = center_window
self.fullscreen = fullscreen
def add_imagepage(
self,
color,
imgwidthpx,
imgheightpx,
imgformat,
imgdata,
imgwidthpdf,
imgheightpdf,
imgxpdf,
imgypdf,
pagewidth,
pageheight,
userunit=None,
palette=None,
inverted=False,
depth=0,
rotate=0,
cropborder=None,
bleedborder=None,
trimborder=None,
artborder=None,
):
if self.with_pdfrw:
from pdfrw import PdfDict, PdfName, PdfObject, PdfString
from pdfrw.py23_diffs import convert_load
else:
PdfDict = MyPdfDict
PdfName = MyPdfName
PdfObject = MyPdfObject
PdfString = MyPdfString
convert_load = my_convert_load
if color == Colorspace["1"] or color == Colorspace.L:
colorspace = PdfName.DeviceGray
elif color == Colorspace.RGB:
colorspace = PdfName.DeviceRGB
elif color == Colorspace.CMYK or color == Colorspace["CMYK;I"]:
colorspace = PdfName.DeviceCMYK
elif color == Colorspace.P:
if self.with_pdfrw:
raise Exception(
"pdfrw does not support hex strings for "
"palette image input, re-run with "
"--without-pdfrw"
)
colorspace = [
PdfName.Indexed,
PdfName.DeviceRGB,
len(palette) - 1,
PdfString.encode(palette, hextype=True),
]
else:
raise UnsupportedColorspaceError("unsupported color space: %s" % color.name)
# either embed the whole jpeg or deflate the bitmap representation
if imgformat is ImageFormat.JPEG:
ofilter = PdfName.DCTDecode
elif imgformat is ImageFormat.JPEG2000:
ofilter = PdfName.JPXDecode
self.writer.version = "1.5" # jpeg2000 needs pdf 1.5
elif imgformat is ImageFormat.CCITTGroup4:
ofilter = [PdfName.CCITTFaxDecode]
else:
ofilter = PdfName.FlateDecode
image = PdfDict(stream=convert_load(imgdata))
image[PdfName.Type] = PdfName.XObject
image[PdfName.Subtype] = PdfName.Image
image[PdfName.Filter] = ofilter
image[PdfName.Width] = imgwidthpx
if (imgheightpx < 0):
image[PdfName.Height] = -imgheightpx
else:
image[PdfName.Height] = imgheightpx
image[PdfName.ColorSpace] = colorspace
image[PdfName.BitsPerComponent] = depth
if color == Colorspace["CMYK;I"]:
# Inverts all four channels
image[PdfName.Decode] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]
if imgformat is ImageFormat.CCITTGroup4:
decodeparms = PdfDict()
# The default for the K parameter is 0 which indicates Group 3 1-D
# encoding. We set it to -1 because we want Group 4 encoding.
decodeparms[PdfName.K] = -1
if inverted:
decodeparms[PdfName.BlackIs1] = PdfObject("false")
else:
decodeparms[PdfName.BlackIs1] = PdfObject("true")
decodeparms[PdfName.Columns] = imgwidthpx
decodeparms[PdfName.Rows] = imgheightpx
image[PdfName.DecodeParms] = [decodeparms]
elif imgformat is ImageFormat.PBM:
decodeparms = PdfDict()
decodeparms[PdfName.Predictor] = 1
decodeparms[PdfName.Colors] = 1
decodeparms[PdfName.Columns] = imgwidthpx
decodeparms[PdfName.BitsPerComponent] = depth
image[PdfName.DecodeParms] = decodeparms
elif imgformat is ImageFormat.PNG:
decodeparms = PdfDict()
decodeparms[PdfName.Predictor] = 15
if color in [Colorspace.P, Colorspace["1"], Colorspace.L]:
decodeparms[PdfName.Colors] = 1
else:
decodeparms[PdfName.Colors] = 3
decodeparms[PdfName.Columns] = imgwidthpx
decodeparms[PdfName.BitsPerComponent] = depth
image[PdfName.DecodeParms] = decodeparms
text = (
"q\n%0.4f 0 0 %0.4f %0.4f %0.4f cm\n/Im0 Do\nQ"
% (imgwidthpdf, -imgheightpdf, imgxpdf, imgypdf)
).encode("ascii")
content = PdfDict(stream=convert_load(text))
resources = PdfDict(XObject=PdfDict(Im0=image))
page = PdfDict(indirect=True)
page[PdfName.Type] = PdfName.Page
page[PdfName.MediaBox] = [0, 0, pagewidth, pageheight]
# 14.11.2 Page Boundaries
# ...
# The crop, bleed, trim, and art boxes shall not ordinarily extend
# beyond the boundaries of the media box. If they do, they are
# effectively reduced to their intersection with the media box.
if cropborder is not None:
page[PdfName.CropBox] = [
cropborder[1],
cropborder[0],
pagewidth - 2 * cropborder[1],
pageheight - 2 * cropborder[0],
]
if bleedborder is None:
if PdfName.CropBox in page:
page[PdfName.BleedBox] = page[PdfName.CropBox]
else:
page[PdfName.BleedBox] = [
bleedborder[1],
bleedborder[0],
pagewidth - 2 * bleedborder[1],
pageheight - 2 * bleedborder[0],
]
if trimborder is None:
if PdfName.CropBox in page:
page[PdfName.TrimBox] = page[PdfName.CropBox]
else:
page[PdfName.TrimBox] = [
trimborder[1],
trimborder[0],
pagewidth - 2 * trimborder[1],
pageheight - 2 * trimborder[0],
]
if artborder is None:
if PdfName.CropBox in page:
page[PdfName.ArtBox] = page[PdfName.CropBox]
else:
page[PdfName.ArtBox] = [
artborder[1],
artborder[0],
pagewidth - 2 * artborder[1],
pageheight - 2 * artborder[0],
]
page[PdfName.Resources] = resources
page[PdfName.Contents] = content
if rotate != 0:
page[PdfName.Rotate] = rotate
if userunit is not None:
# /UserUnit requires PDF 1.6
if self.writer.version < "1.6":
self.writer.version = "1.6"
page[PdfName.UserUnit] = userunit
self.writer.addpage(page)
if not self.with_pdfrw:
self.writer.addobj(content)
self.writer.addobj(image)
def add_multi_imagepage(
self,
coordinates,
collected_images
):
(
color,
ndpi,
imgformat,
imgdata,
imgwidthpx,
imgheightpx,
palette,
inverted,
depth,
rotate,
) = collected_images[0]
pagewidth, pageheight, imgwidthpdf, imgheightpdf = default_layout_fun(
imgwidthpx, imgheightpx, ndpi
)
if (pageheight < 0):
pageheight = -pageheight
userunit = None
if pagewidth < 3.00 or pageheight < 3.00:
logging.warning(
"pdf width or height is below 3.00 - too small for some viewers!"
)
elif pagewidth > 14400.0 or pageheight > 14400.0:
if kwargs["allow_oversized"]:
userunit = find_scale(pagewidth, pageheight)
pagewidth /= userunit
pageheight /= userunit
imgwidthpdf /= userunit
imgheightpdf /= userunit
else:
raise PdfTooLargeError(
"pdf width or height must not exceed 200 inches."
)
# the image is always centered on the page
imgxpdf = (pagewidth - imgwidthpdf) / 2.0
imgypdf = (pageheight + imgheightpdf) / 2.0
cropborder=None
bleedborder=None
trimborder=None
artborder=None
if self.with_pdfrw:
from pdfrw import PdfDict, PdfName, PdfObject, PdfString
from pdfrw.py23_diffs import convert_load
else:
PdfDict = MyPdfDict
PdfName = MyPdfName
PdfObject = MyPdfObject
PdfString = MyPdfString
convert_load = my_convert_load
if color == Colorspace["1"] or color == Colorspace.L:
colorspace = PdfName.DeviceGray
elif color == Colorspace.RGB:
colorspace = PdfName.DeviceRGB
elif color == Colorspace.CMYK or color == Colorspace["CMYK;I"]:
colorspace = PdfName.DeviceCMYK
elif color == Colorspace.P:
if self.with_pdfrw:
raise Exception(
"pdfrw does not support hex strings for "
"palette image input, re-run with "
"--without-pdfrw"
)
colorspace = [
PdfName.Indexed,
PdfName.DeviceRGB,
len(palette) - 1,
PdfString.encode(palette, hextype=True),
]
else:
raise UnsupportedColorspaceError("unsupported color space: %s" % color.name)
# either embed the whole jpeg or deflate the bitmap representation
if imgformat is ImageFormat.JPEG:
ofilter = PdfName.DCTDecode
elif imgformat is ImageFormat.JPEG2000:
ofilter = PdfName.JPXDecode
self.writer.version = "1.5" # jpeg2000 needs pdf 1.5
elif imgformat is ImageFormat.CCITTGroup4:
ofilter = [PdfName.CCITTFaxDecode]
else:
ofilter = PdfName.FlateDecode
image = PdfDict(stream=convert_load(imgdata))
image[PdfName.Type] = PdfName.XObject
image[PdfName.Subtype] = PdfName.Image
image[PdfName.Filter] = ofilter
image[PdfName.Width] = imgwidthpx
if (imgheightpx < 0):
image[PdfName.Height] = -imgheightpx
else: