/
_page.py
2437 lines (2203 loc) · 91.4 KB
/
_page.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
# Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import math
import re
import sys
from decimal import Decimal
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Union,
cast,
overload,
)
from ._cmap import build_char_map, unknown_char_map
from ._protocols import PdfReaderProtocol, PdfWriterProtocol
from ._text_extraction import (
OrientationNotFoundError,
_layout_mode,
crlf_space_check,
handle_tj,
mult,
)
from ._utils import (
WHITESPACES_AS_REGEXP,
CompressedTransformationMatrix,
File,
ImageFile,
TransformationMatrixType,
logger_warning,
matrix_multiply,
)
from .constants import AnnotationDictionaryAttributes as ADA
from .constants import ImageAttributes as IA
from .constants import PageAttributes as PG
from .constants import Ressources as RES
from .errors import PageSizeNotDefinedError, PdfReadError
from .filters import _xobj_to_image
from .generic import (
ArrayObject,
ContentStream,
DictionaryObject,
EncodedStreamObject,
FloatObject,
IndirectObject,
NameObject,
NullObject,
NumberObject,
RectangleObject,
StreamObject,
)
if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal
MERGE_CROP_BOX = "cropbox" # pypdf<=3.4.0 used 'trimbox'
def _get_rectangle(self: Any, name: str, defaults: Iterable[str]) -> RectangleObject:
retval: Union[None, RectangleObject, IndirectObject] = self.get(name)
if isinstance(retval, RectangleObject):
return retval
if retval is None:
for d in defaults:
retval = self.get(d)
if retval is not None:
break
if isinstance(retval, IndirectObject):
retval = self.pdf.get_object(retval)
retval = RectangleObject(retval) # type: ignore
_set_rectangle(self, name, retval)
return retval
def _set_rectangle(self: Any, name: str, value: Union[RectangleObject, float]) -> None:
name = NameObject(name)
self[name] = value
def _delete_rectangle(self: Any, name: str) -> None:
del self[name]
def _create_rectangle_accessor(name: str, fallback: Iterable[str]) -> property:
return property(
lambda self: _get_rectangle(self, name, fallback),
lambda self, value: _set_rectangle(self, name, value),
lambda self: _delete_rectangle(self, name),
)
class Transformation:
"""
Represent a 2D transformation.
The transformation between two coordinate systems is represented by a 3-by-3
transformation matrix matrix with the following form::
a b 0
c d 0
e f 1
Because a transformation matrix has only six elements that can be changed,
it is usually specified in PDF as the six-element array [ a b c d e f ].
Coordinate transformations are expressed as matrix multiplications::
a b 0
[ x′ y′ 1 ] = [ x y 1 ] × c d 0
e f 1
Example:
>>> from pypdf import Transformation
>>> op = Transformation().scale(sx=2, sy=3).translate(tx=10, ty=20)
>>> page.add_transformation(op)
"""
# 9.5.4 Coordinate Systems for 3D
# 4.2.2 Common Transformations
def __init__(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0)):
self.ctm = ctm
@property
def matrix(self) -> TransformationMatrixType:
"""
Return the transformation matrix as a tuple of tuples in the form:
((a, b, 0), (c, d, 0), (e, f, 1))
"""
return (
(self.ctm[0], self.ctm[1], 0),
(self.ctm[2], self.ctm[3], 0),
(self.ctm[4], self.ctm[5], 1),
)
@staticmethod
def compress(matrix: TransformationMatrixType) -> CompressedTransformationMatrix:
"""
Compresses the transformation matrix into a tuple of (a, b, c, d, e, f).
Args:
matrix: The transformation matrix as a tuple of tuples.
Returns:
A tuple representing the transformation matrix as (a, b, c, d, e, f)
"""
return (
matrix[0][0],
matrix[0][1],
matrix[1][0],
matrix[1][1],
matrix[2][0],
matrix[2][1],
)
def transform(self, m: "Transformation") -> "Transformation":
"""
Apply one transformation to another.
Args:
m: a Transformation to apply.
Returns:
A new ``Transformation`` instance
Example:
>>> from pypdf import Transformation
>>> op = Transformation((1, 0, 0, -1, 0, height)) # vertical mirror
>>> op = Transformation().transform(Transformation((-1, 0, 0, 1, iwidth, 0))) # horizontal mirror
>>> page.add_transformation(op)
"""
ctm = Transformation.compress(matrix_multiply(self.matrix, m.matrix))
return Transformation(ctm)
def translate(self, tx: float = 0, ty: float = 0) -> "Transformation":
"""
Translate the contents of a page.
Args:
tx: The translation along the x-axis.
ty: The translation along the y-axis.
Returns:
A new ``Transformation`` instance
"""
m = self.ctm
return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty))
def scale(
self, sx: Optional[float] = None, sy: Optional[float] = None
) -> "Transformation":
"""
Scale the contents of a page towards the origin of the coordinate system.
Typically, that is the lower-left corner of the page. That can be
changed by translating the contents / the page boxes.
Args:
sx: The scale factor along the x-axis.
sy: The scale factor along the y-axis.
Returns:
A new Transformation instance with the scaled matrix.
"""
if sx is None and sy is None:
raise ValueError("Either sx or sy must be specified")
if sx is None:
sx = sy
if sy is None:
sy = sx
assert sx is not None
assert sy is not None
op: TransformationMatrixType = ((sx, 0, 0), (0, sy, 0), (0, 0, 1))
ctm = Transformation.compress(matrix_multiply(self.matrix, op))
return Transformation(ctm)
def rotate(self, rotation: float) -> "Transformation":
"""
Rotate the contents of a page.
Args:
rotation: The angle of rotation in degrees.
Returns:
A new ``Transformation`` instance with the rotated matrix.
"""
rotation = math.radians(rotation)
op: TransformationMatrixType = (
(math.cos(rotation), math.sin(rotation), 0),
(-math.sin(rotation), math.cos(rotation), 0),
(0, 0, 1),
)
ctm = Transformation.compress(matrix_multiply(self.matrix, op))
return Transformation(ctm)
def __repr__(self) -> str:
return f"Transformation(ctm={self.ctm})"
@overload
def apply_on(self, pt: List[float], as_object: bool = False) -> List[float]:
...
@overload
def apply_on(
self, pt: Tuple[float, float], as_object: bool = False
) -> Tuple[float, float]:
...
def apply_on(
self,
pt: Union[Tuple[float, float], List[float]],
as_object: bool = False,
) -> Union[Tuple[float, float], List[float]]:
"""
Apply the transformation matrix on the given point.
Args:
pt: A tuple or list representing the point in the form (x, y)
Returns:
A tuple or list representing the transformed point in the form (x', y')
"""
typ = FloatObject if as_object else float
pt1 = (
typ(float(pt[0]) * self.ctm[0] + float(pt[1]) * self.ctm[2] + self.ctm[4]),
typ(float(pt[0]) * self.ctm[1] + float(pt[1]) * self.ctm[3] + self.ctm[5]),
)
return list(pt1) if isinstance(pt, list) else pt1
class PageObject(DictionaryObject):
"""
PageObject represents a single page within a PDF file.
Typically these objects will be created by accessing the
:attr:`pages<pypdf.PdfReader.pages>` property of the
:class:`PdfReader<pypdf.PdfReader>` class, but it is
also possible to create an empty page with the
:meth:`create_blank_page()<pypdf._page.PageObject.create_blank_page>` static method.
Args:
pdf: PDF file the page belongs to.
indirect_reference: Stores the original indirect reference to
this object in its source PDF
"""
original_page: "PageObject" # very local use in writer when appending
def __init__(
self,
pdf: Union[None, PdfReaderProtocol, PdfWriterProtocol] = None,
indirect_reference: Optional[IndirectObject] = None,
) -> None:
DictionaryObject.__init__(self)
self.pdf: Union[None, PdfReaderProtocol, PdfWriterProtocol] = pdf
self.inline_images: Optional[Dict[str, ImageFile]] = None
# below Union for mypy but actually Optional[List[str]]
self.inline_images_keys: Optional[List[Union[str, List[str]]]] = None
self.indirect_reference = indirect_reference
def hash_value_data(self) -> bytes:
data = super().hash_value_data()
data += b"%d" % id(self)
return data
@property
def user_unit(self) -> float:
"""
A read-only positive number giving the size of user space units.
It is in multiples of 1/72 inch. Hence a value of 1 means a user
space unit is 1/72 inch, and a value of 3 means that a user
space unit is 3/72 inch.
"""
return self.get(PG.USER_UNIT, 1)
@staticmethod
def create_blank_page(
pdf: Union[None, PdfReaderProtocol, PdfWriterProtocol] = None,
width: Union[float, Decimal, None] = None,
height: Union[float, Decimal, None] = None,
) -> "PageObject":
"""
Return a new blank page.
If ``width`` or ``height`` is ``None``, try to get the page size
from the last page of *pdf*.
Args:
pdf: PDF file the page belongs to
width: The width of the new page expressed in default user
space units.
height: The height of the new page expressed in default user
space units.
Returns:
The new blank page
Raises:
PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains
no page
"""
page = PageObject(pdf)
# Creates a new page (cf PDF Reference 7.7.3.3)
page.__setitem__(NameObject(PG.TYPE), NameObject("/Page"))
page.__setitem__(NameObject(PG.PARENT), NullObject())
page.__setitem__(NameObject(PG.RESOURCES), DictionaryObject())
if width is None or height is None:
if pdf is not None and len(pdf.pages) > 0:
lastpage = pdf.pages[len(pdf.pages) - 1]
width = lastpage.mediabox.width
height = lastpage.mediabox.height
else:
raise PageSizeNotDefinedError
page.__setitem__(
NameObject(PG.MEDIABOX), RectangleObject((0, 0, width, height)) # type: ignore
)
return page
@property
def _old_images(self) -> List[File]: # deprecated
"""
Get a list of all images of the page.
This requires pillow. You can install it via 'pip install pypdf[image]'.
For the moment, this does NOT include inline images. They will be added
in future.
"""
images_extracted: List[File] = []
if RES.XOBJECT not in self[PG.RESOURCES]: # type: ignore
return images_extracted
x_object = self[PG.RESOURCES][RES.XOBJECT].get_object() # type: ignore
for obj in x_object:
if x_object[obj][IA.SUBTYPE] == "/Image":
extension, byte_stream, img = _xobj_to_image(x_object[obj])
if extension is not None:
filename = f"{obj[1:]}{extension}"
images_extracted.append(File(name=filename, data=byte_stream))
images_extracted[-1].image = img
images_extracted[-1].indirect_reference = x_object[
obj
].indirect_reference
return images_extracted
def _get_ids_image(
self,
obj: Optional[DictionaryObject] = None,
ancest: Optional[List[str]] = None,
call_stack: Optional[List[Any]] = None,
) -> List[Union[str, List[str]]]:
if call_stack is None:
call_stack = []
_i = getattr(obj, "indirect_reference", None)
if _i in call_stack:
return []
else:
call_stack.append(_i)
if self.inline_images_keys is None:
content = self._get_contents_as_bytes() or b""
nb_inlines = 0
for matching in re.finditer(
WHITESPACES_AS_REGEXP + b"BI" + WHITESPACES_AS_REGEXP,
content,
):
start_of_string = content[: matching.start()]
if len(re.findall(b"[^\\\\]\\(", start_of_string)) == len(
re.findall(b"[^\\\\]\\)", start_of_string)
):
nb_inlines += 1
self.inline_images_keys = [f"~{x}~" for x in range(nb_inlines)]
if obj is None:
obj = self
if ancest is None:
ancest = []
lst: List[Union[str, List[str]]] = []
if PG.RESOURCES not in obj or RES.XOBJECT not in cast(
DictionaryObject, obj[PG.RESOURCES]
):
return self.inline_images_keys
x_object = obj[PG.RESOURCES][RES.XOBJECT].get_object() # type: ignore
for o in x_object:
if not isinstance(x_object[o], StreamObject):
continue
if x_object[o][IA.SUBTYPE] == "/Image":
lst.append(o if len(ancest) == 0 else ancest + [o])
else: # is a form with possible images inside
lst.extend(self._get_ids_image(x_object[o], ancest + [o], call_stack))
return lst + self.inline_images_keys
def _get_image(
self,
id: Union[str, List[str], Tuple[str]],
obj: Optional[DictionaryObject] = None,
) -> ImageFile:
if obj is None:
obj = cast(DictionaryObject, self)
if isinstance(id, tuple):
id = list(id)
if isinstance(id, List) and len(id) == 1:
id = id[0]
try:
xobjs = cast(
DictionaryObject, cast(DictionaryObject, obj[PG.RESOURCES])[RES.XOBJECT]
)
except KeyError:
if not (id[0] == "~" and id[-1] == "~"):
raise
if isinstance(id, str):
if id[0] == "~" and id[-1] == "~":
if self.inline_images is None:
self.inline_images = self._get_inline_images()
if self.inline_images is None: # pragma: no cover
raise KeyError("no inline image can be found")
return self.inline_images[id]
imgd = _xobj_to_image(cast(DictionaryObject, xobjs[id]))
extension, byte_stream = imgd[:2]
f = ImageFile(
name=f"{id[1:]}{extension}",
data=byte_stream,
image=imgd[2],
indirect_reference=xobjs[id].indirect_reference,
)
return f
else: # in a sub object
ids = id[1:]
return self._get_image(ids, cast(DictionaryObject, xobjs[id[0]]))
@property
def images(self) -> List[ImageFile]:
"""
Read-only property emulating a list of images on a page.
Get a list of all images on the page. The key can be:
- A string (for the top object)
- A tuple (for images within XObject forms)
- An integer
Examples:
reader.pages[0].images[0] # return fist image
reader.pages[0].images['/I0'] # return image '/I0'
# return image '/Image1' within '/TP1' Xobject/Form:
reader.pages[0].images['/TP1','/Image1']
for img in reader.pages[0].images: # loop within all objects
images.keys() and images.items() can be used.
The ImageFile has the following properties:
`.name` : name of the object
`.data` : bytes of the object
`.image` : PIL Image Object
`.indirect_reference` : object reference
and the following methods:
`.replace(new_image: PIL.Image.Image, **kwargs)` :
replace the image in the pdf with the new image
applying the saving parameters indicated (such as quality)
Example usage:
reader.pages[0].images[0]=replace(Image.open("new_image.jpg", quality = 20)
Inline images are extracted and named ~0~, ~1~, ..., with the
indirect_reference set to None.
"""
return _VirtualListImages(self._get_ids_image, self._get_image) # type: ignore
def _get_inline_images(self) -> Dict[str, ImageFile]:
"""
get inline_images
entries will be identified as ~1~
"""
content = self.get_contents()
if content is None:
return {}
imgs_data = []
for param, ope in content.operations:
if ope == b"INLINE IMAGE":
imgs_data.append(
{"settings": param["settings"], "__streamdata__": param["data"]}
)
elif ope in (b"BI", b"EI", b"ID"): # pragma: no cover
raise PdfReadError(
f"{ope} operator met whereas not expected,"
"please share usecase with pypdf dev team"
)
"""backup
elif ope == b"BI":
img_data["settings"] = {}
elif ope == b"EI":
imgs_data.append(img_data)
img_data = {}
elif ope == b"ID":
img_data["__streamdata__"] = b""
elif "__streamdata__" in img_data:
if len(img_data["__streamdata__"]) > 0:
img_data["__streamdata__"] += b"\n"
raise Exception("check append")
img_data["__streamdata__"] += param
elif "settings" in img_data:
img_data["settings"][ope.decode()] = param
"""
files = {}
for num, ii in enumerate(imgs_data):
init = {
"__streamdata__": ii["__streamdata__"],
"/Length": len(ii["__streamdata__"]),
}
for k, v in ii["settings"].items():
try:
v = NameObject(
{
"/G": "/DeviceGray",
"/RGB": "/DeviceRGB",
"/CMYK": "/DeviceCMYK",
"/I": "/Indexed",
"/AHx": "/ASCIIHexDecode",
"/A85": "/ASCII85Decode",
"/LZW": "/LZWDecode",
"/Fl": "/FlateDecode",
"/RL": "/RunLengthDecode",
"/CCF": "/CCITTFaxDecode",
"/DCT": "/DCTDecode",
}[v]
)
except (TypeError, KeyError):
if isinstance(v, NameObject):
# it is a custom name : we have to look in resources :
# the only applicable case is for ColorSpace
try:
res = cast(DictionaryObject, self["/Resources"])[
"/ColorSpace"
]
v = cast(DictionaryObject, res)[v]
except KeyError: # for res and v
raise PdfReadError(
f"Can not find resource entry {v} for {k}"
)
init[
NameObject(
{
"/BPC": "/BitsPerComponent",
"/CS": "/ColorSpace",
"/D": "/Decode",
"/DP": "/DecodeParms",
"/F": "/Filter",
"/H": "/Height",
"/W": "/Width",
"/I": "/Interpolate",
"/Intent": "/Intent",
"/IM": "/ImageMask",
}[k]
)
] = v
ii["object"] = EncodedStreamObject.initialize_from_dictionary(init)
extension, byte_stream, img = _xobj_to_image(ii["object"])
files[f"~{num}~"] = ImageFile(
name=f"~{num}~{extension}",
data=byte_stream,
image=img,
indirect_reference=None,
)
return files
@property
def rotation(self) -> int:
"""
The VISUAL rotation of the page.
This number has to be a multiple of 90 degrees: 0, 90, 180, or 270 are
valid values. This property does not affect ``/Contents``.
"""
rotate_obj = self.get(PG.ROTATE, 0)
return rotate_obj if isinstance(rotate_obj, int) else rotate_obj.get_object()
@rotation.setter
def rotation(self, r: float) -> None:
self[NameObject(PG.ROTATE)] = NumberObject((((int(r) + 45) // 90) * 90) % 360)
def transfer_rotation_to_content(self) -> None:
"""
Apply the rotation of the page to the content and the media/crop/...
boxes.
It's recommended to apply this function before page merging.
"""
r = -self.rotation # rotation to apply is in the otherway
self.rotation = 0
mb = RectangleObject(self.mediabox)
trsf = (
Transformation()
.translate(
-float(mb.left + mb.width / 2), -float(mb.bottom + mb.height / 2)
)
.rotate(r)
)
pt1 = trsf.apply_on(mb.lower_left)
pt2 = trsf.apply_on(mb.upper_right)
trsf = trsf.translate(-min(pt1[0], pt2[0]), -min(pt1[1], pt2[1]))
self.add_transformation(trsf, False)
for b in ["/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox"]:
if b in self:
rr = RectangleObject(self[b]) # type: ignore
pt1 = trsf.apply_on(rr.lower_left)
pt2 = trsf.apply_on(rr.upper_right)
self[NameObject(b)] = RectangleObject(
(
min(pt1[0], pt2[0]),
min(pt1[1], pt2[1]),
max(pt1[0], pt2[0]),
max(pt1[1], pt2[1]),
)
)
def rotate(self, angle: int) -> "PageObject":
"""
Rotate a page clockwise by increments of 90 degrees.
Args:
angle: Angle to rotate the page. Must be an increment of 90 deg.
Returns:
The rotated PageObject
"""
if angle % 90 != 0:
raise ValueError("Rotation angle must be a multiple of 90")
self[NameObject(PG.ROTATE)] = NumberObject(self.rotation + angle)
return self
def _merge_resources(
self,
res1: DictionaryObject,
res2: DictionaryObject,
resource: Any,
new_res1: bool = True,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
try:
assert isinstance(self.indirect_reference, IndirectObject)
pdf = self.indirect_reference.pdf
is_pdf_writer = hasattr(
pdf, "_add_object"
) # ---------- expect isinstance(pdf,PdfWriter)
except (AssertionError, AttributeError):
pdf = None
is_pdf_writer = False
def compute_unique_key(base_key: str) -> Tuple[str, bool]:
"""
Find a key that either doesn't already exist or has the same value
(indicated by the bool)
Args:
base_key: An index is added to this to get the computed key
Returns:
A tuple (computed key, bool) where the boolean indicates
if there is a resource of the given computed_key with the same
value.
"""
value = page2res.raw_get(base_key)
# TODO : possible improvement : in case of writer, the indirect_reference
# can not be found because translated : this may be improved
# try the current key first (e.g. "foo"), but otherwise iterate
# through "foo-0", "foo-1", etc. new_res can contain only finitely
# many keys, thus this'll eventually end, even if it's been crafted
# to be maximally annoying.
computed_key = base_key
idx = 0
while computed_key in new_res:
if new_res.raw_get(computed_key) == value:
# there's already a resource of this name, with the exact
# same value
return computed_key, True
computed_key = f"{base_key}-{idx}"
idx += 1
return computed_key, False
if new_res1:
new_res = DictionaryObject()
new_res.update(res1.get(resource, DictionaryObject()).get_object())
else:
new_res = cast(DictionaryObject, res1[resource])
page2res = cast(
DictionaryObject, res2.get(resource, DictionaryObject()).get_object()
)
rename_res = {}
for key in page2res:
unique_key, same_value = compute_unique_key(key)
newname = NameObject(unique_key)
if key != unique_key:
# we have to use a different name for this
rename_res[key] = newname
if not same_value:
if is_pdf_writer:
new_res[newname] = page2res.raw_get(key).clone(pdf)
try:
new_res[newname] = new_res[newname].indirect_reference
except AttributeError:
pass
else:
new_res[newname] = page2res.raw_get(key)
lst = sorted(new_res.items())
new_res.clear()
for el in lst:
new_res[el[0]] = el[1]
return new_res, rename_res
@staticmethod
def _content_stream_rename(
stream: ContentStream,
rename: Dict[Any, Any],
pdf: Union[None, PdfReaderProtocol, PdfWriterProtocol],
) -> ContentStream:
if not rename:
return stream
stream = ContentStream(stream, pdf)
for operands, _operator in stream.operations:
if isinstance(operands, list):
for i, op in enumerate(operands):
if isinstance(op, NameObject):
operands[i] = rename.get(op, op)
elif isinstance(operands, dict):
for i, op in operands.items():
if isinstance(op, NameObject):
operands[i] = rename.get(op, op)
else:
raise KeyError(f"type of operands is {type(operands)}")
return stream
@staticmethod
def _add_transformation_matrix(
contents: Any,
pdf: Union[None, PdfReaderProtocol, PdfWriterProtocol],
ctm: CompressedTransformationMatrix,
) -> ContentStream:
"""Add transformation matrix at the beginning of the given contents stream."""
a, b, c, d, e, f = ctm
contents = ContentStream(contents, pdf)
contents.operations.insert(
0,
[
[
FloatObject(a),
FloatObject(b),
FloatObject(c),
FloatObject(d),
FloatObject(e),
FloatObject(f),
],
" cm",
],
)
return contents
def _get_contents_as_bytes(self) -> Optional[bytes]:
"""
Return the page contents as bytes.
Returns:
The ``/Contents`` object as bytes, or ``None`` if it doesn't exist.
"""
if PG.CONTENTS in self:
obj = self[PG.CONTENTS].get_object()
if isinstance(obj, list):
return b"".join(x.get_object().get_data() for x in obj)
else:
return cast(bytes, cast(EncodedStreamObject, obj).get_data())
else:
return None
def get_contents(self) -> Optional[ContentStream]:
"""
Access the page contents.
Returns:
The ``/Contents`` object, or ``None`` if it doesn't exist.
``/Contents`` is optional, as described in PDF Reference 7.7.3.3
"""
if PG.CONTENTS in self:
try:
pdf = cast(IndirectObject, self.indirect_reference).pdf
except AttributeError:
pdf = None
obj = self[PG.CONTENTS].get_object()
if isinstance(obj, NullObject):
return None
else:
return ContentStream(obj, pdf)
else:
return None
def replace_contents(
self, content: Union[None, ContentStream, EncodedStreamObject, ArrayObject]
) -> None:
"""
Replace the page contents with the new content and nullify old objects
Args:
content : new content. if None delete the content field.
"""
if not hasattr(self, "indirect_reference") or self.indirect_reference is None:
# the page is not attached : the content is directly attached.
self[NameObject(PG.CONTENTS)] = content
return
if isinstance(self.get(PG.CONTENTS, None), ArrayObject):
for o in self[PG.CONTENTS]: # type: ignore[attr-defined]
try:
self._objects[o.indirect_reference.idnum - 1] = NullObject() # type: ignore
except AttributeError:
pass
if isinstance(content, ArrayObject):
for i in range(len(content)):
content[i] = self.indirect_reference.pdf._add_object(content[i])
if content is None:
if PG.CONTENTS not in self:
return
else:
assert self.indirect_reference is not None
assert self[PG.CONTENTS].indirect_reference is not None
self.indirect_reference.pdf._objects[
self[PG.CONTENTS].indirect_reference.idnum - 1 # type: ignore
] = NullObject()
del self[PG.CONTENTS]
elif not hasattr(self.get(PG.CONTENTS, None), "indirect_reference"):
try:
self[NameObject(PG.CONTENTS)] = self.indirect_reference.pdf._add_object(
content
)
except AttributeError:
# applies at least for page not in writer
# as a backup solution, we put content as an object although not in accordance with pdf ref
# this will be fixed with the _add_object
self[NameObject(PG.CONTENTS)] = content
else:
content.indirect_reference = self[
PG.CONTENTS
].indirect_reference # TODO: in a future may required generation managment
try:
self.indirect_reference.pdf._objects[
content.indirect_reference.idnum - 1 # type: ignore
] = content
except AttributeError:
# applies at least for page not in writer
# as a backup solution, we put content as an object although not in accordance with pdf ref
# this will be fixed with the _add_object
self[NameObject(PG.CONTENTS)] = content
def merge_page(
self, page2: "PageObject", expand: bool = False, over: bool = True
) -> None:
"""
Merge the content streams of two pages into one.
Resource references
(i.e. fonts) are maintained from both pages. The mediabox/cropbox/etc
of this page are not altered. The parameter page's content stream will
be added to the end of this page's content stream, meaning that it will
be drawn after, or "on top" of this page.
Args:
page2: The page to be merged into this one. Should be
an instance of :class:`PageObject<PageObject>`.
over: set the page2 content over page1 if True(default) else under
expand: If true, the current page dimensions will be
expanded to accommodate the dimensions of the page to be merged.
"""
self._merge_page(page2, over=over, expand=expand)
def _merge_page(
self,
page2: "PageObject",
page2transformation: Optional[Callable[[Any], ContentStream]] = None,
ctm: Optional[CompressedTransformationMatrix] = None,
over: bool = True,
expand: bool = False,
) -> None:
# First we work on merging the resource dictionaries. This allows us
# to find out what symbols in the content streams we might need to
# rename.
try:
assert isinstance(self.indirect_reference, IndirectObject)
if hasattr(
self.indirect_reference.pdf, "_add_object"
): # ---------- to detect PdfWriter
return self._merge_page_writer(
page2, page2transformation, ctm, over, expand
)
except (AssertionError, AttributeError):
pass
new_resources = DictionaryObject()
rename = {}
try:
original_resources = cast(DictionaryObject, self[PG.RESOURCES].get_object())
except KeyError:
original_resources = DictionaryObject()
try:
page2resources = cast(DictionaryObject, page2[PG.RESOURCES].get_object())
except KeyError:
page2resources = DictionaryObject()
new_annots = ArrayObject()
for page in (self, page2):
if PG.ANNOTS in page:
annots = page[PG.ANNOTS]
if isinstance(annots, ArrayObject):
new_annots.extend(annots)
for res in (
RES.EXT_G_STATE,