-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathtest_page.py
1471 lines (1266 loc) · 48.6 KB
/
test_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
"""Test the pypdf._page module."""
import json
import math
from copy import deepcopy
from io import BytesIO
from pathlib import Path
from random import shuffle
from typing import List, Tuple
import pytest
from pypdf import PdfReader, PdfWriter, Transformation
from pypdf._page import PageObject
from pypdf.constants import PageAttributes as PG
from pypdf.errors import PdfReadError, PdfReadWarning, PyPdfError
from pypdf.generic import (
ArrayObject,
ContentStream,
DictionaryObject,
FloatObject,
IndirectObject,
NameObject,
NullObject,
RectangleObject,
TextStringObject,
)
from . import get_data_from_url, normalize_warnings
TESTS_ROOT = Path(__file__).parent.resolve()
PROJECT_ROOT = TESTS_ROOT.parent
RESOURCE_ROOT = PROJECT_ROOT / "resources"
SAMPLE_ROOT = PROJECT_ROOT / "sample-files"
def get_all_sample_files():
meta_file = SAMPLE_ROOT / "files.json"
if not Path(meta_file).is_file():
return {"data": []}
with open(meta_file) as fp:
data = fp.read()
return json.loads(data)
all_files_meta = get_all_sample_files()
@pytest.mark.samples
@pytest.mark.parametrize(
"meta",
[m for m in all_files_meta["data"] if not m["encrypted"]],
ids=[m["path"] for m in all_files_meta["data"] if not m["encrypted"]],
)
@pytest.mark.filterwarnings("ignore::pypdf.errors.PdfReadWarning")
def test_read(meta):
pdf_path = SAMPLE_ROOT / meta["path"]
reader = PdfReader(pdf_path)
try:
reader.pages[0]
except Exception:
return
assert len(reader.pages) == meta["pages"]
@pytest.mark.samples
@pytest.mark.enable_socket
@pytest.mark.parametrize(
("pdf_path", "password"),
[
("crazyones.pdf", None),
("attachment.pdf", None),
(
"libreoffice-writer-password.pdf",
"openpassword",
),
("imagemagick-images.pdf", None),
("imagemagick-lzw.pdf", None),
("reportlab-inline-image.pdf", None),
("https://arxiv.org/pdf/2201.00029.pdf", None),
],
)
def test_page_operations(pdf_path, password):
"""
This test just checks if the operation throws an exception.
This should be done way more thoroughly: It should be checked if the output
is as expected.
"""
if pdf_path.startswith("http"):
pdf_path = BytesIO(get_data_from_url(pdf_path, pdf_path.split("/")[-1]))
else:
pdf_path = RESOURCE_ROOT / pdf_path
reader = PdfReader(pdf_path)
writer = PdfWriter()
if password:
reader.decrypt(password)
writer.clone_document_from_reader(reader)
page: PageObject = writer.pages[0]
t = Transformation().translate(50, 100).rotate(90)
assert abs(t.ctm[4] + 100) < 0.01
assert abs(t.ctm[5] - 50) < 0.01
transformation = (
Transformation()
.rotate(90)
.scale(1)
.translate(1, 1)
.transform(Transformation((1, 0, 0, -1, 0, 0)))
)
page.add_transformation(transformation, expand=True)
page.add_transformation((1, 0, 0, 0, 0, 0))
page.scale(2, 2)
page.scale_by(0.5)
page.scale_to(100, 100)
page.compress_content_streams()
page.extract_text()
page.scale_by(0.5)
page.scale_to(100, 100)
page.extract_text()
@pytest.mark.parametrize(
("angle", "expected_width", "expected_height"),
[
(175, 680, 844),
(45, 994, 994),
(-80, 888, 742),
],
)
def test_mediabox_expansion_after_rotation(
angle: float, expected_width: int, expected_height: int
):
"""
Mediabox dimensions after rotation at a non-right angle with expansion are correct.
The test was validated against pillow (see PR #2282)
"""
pdf_path = RESOURCE_ROOT / "crazyones.pdf"
reader = PdfReader(pdf_path)
transformation = Transformation().rotate(angle)
for page_box in reader.pages:
page_box.add_transformation(transformation, expand=True)
mediabox = reader.pages[0].mediabox
# Deviation of up to 2 pixels is acceptable
assert math.isclose(mediabox.width, expected_width, abs_tol=2)
assert math.isclose(mediabox.height, expected_height, abs_tol=2)
def test_transformation_equivalence():
pdf_path = RESOURCE_ROOT / "labeled-edges-center-image.pdf"
reader_base = PdfReader(pdf_path)
page_base = reader_base.pages[0]
pdf_path = RESOURCE_ROOT / "box.pdf"
reader_add = PdfReader(pdf_path)
page_box = reader_add.pages[0]
op = Transformation().scale(2).rotate(45)
# Option 1: The new way
page_box1 = deepcopy(page_box)
page_base1 = deepcopy(page_base)
page_box1.add_transformation(op, expand=True)
page_base1.merge_page(page_box1, expand=False)
# Option 2: The old way
page_box2 = deepcopy(page_box)
page_base2 = deepcopy(page_base)
page_base2.merge_transformed_page(page_box2, op, expand=False)
page_box2.add_transformation(op)
page_base2.merge_page(page_box2)
# Should be the same
assert page_base1[NameObject(PG.CONTENTS)] == page_base2[NameObject(PG.CONTENTS)]
assert page_base1.mediabox == page_base2.mediabox
assert page_base1.trimbox == page_base2.trimbox
assert page_base1[NameObject(PG.ANNOTS)] == page_base2[NameObject(PG.ANNOTS)]
compare_dict_objects(
page_base1[NameObject(PG.RESOURCES)], page_base2[NameObject(PG.RESOURCES)]
)
def test_transformation_equivalence2():
pdf_path = RESOURCE_ROOT / "labeled-edges-center-image.pdf"
reader_base = PdfReader(pdf_path)
pdf_path = RESOURCE_ROOT / "box.pdf"
reader_add = PdfReader(pdf_path)
writer = PdfWriter()
writer.append(reader_base)
writer.pages[0].merge_transformed_page(
reader_add.pages[0], Transformation().scale(2).rotate(-45), False, False
)
writer.pages[0].merge_transformed_page(
reader_add.pages[0], Transformation().scale(2).translate(100, 100), True, False
)
# No special assert: the test should be visual in a viewer; 2 box with a arrow rotated and translated
writer = PdfWriter()
writer.append(reader_add)
writer.pages[0].merge_transformed_page(
reader_base.pages[0], Transformation(), True, True
)
# No special assert: Visual check the page has been increased and all is visible (box+graph)
writer = PdfWriter()
writer.append(reader_add)
height = reader_add.pages[0].mediabox.height
writer.pages[0].merge_transformed_page(
reader_base.pages[0],
Transformation().transform(Transformation((1, 0, 0, -1, 0, height))),
False,
False,
)
# No special assert: Visual check the page has been increased and all is visible (box+graph)
pdf_path = RESOURCE_ROOT / "commented-xmp.pdf"
reader_comments = PdfReader(pdf_path)
writer = PdfWriter()
writer.append(reader_base)
writer.pages[0].merge_transformed_page(
reader_comments.pages[0], Transformation().rotate(-15), True, True
)
nb_annots1 = len(writer.pages[0]["/Annots"])
writer.pages[0].merge_transformed_page(
reader_comments.pages[0], Transformation().rotate(-30), True, True
)
assert len(writer.pages[0]["/Annots"]) == 2 * nb_annots1
# No special assert: Visual check the overlay has its comments at the good position
def test_get_user_unit_property():
pdf_path = RESOURCE_ROOT / "crazyones.pdf"
reader = PdfReader(pdf_path)
assert reader.pages[0].user_unit == 1
def compare_dict_objects(d1, d2):
assert sorted(d1.keys()) == sorted(d2.keys())
for key in d1:
if isinstance(d1[key], DictionaryObject):
compare_dict_objects(d1[key], d2[key])
else:
assert d1[key] == d2[key]
@pytest.mark.slow
def test_page_transformations():
pdf_path = RESOURCE_ROOT / "crazyones.pdf"
reader = PdfReader(pdf_path)
page: PageObject = reader.pages[0]
page.merge_rotated_page(page, 90, expand=True)
op = Transformation().rotate(90).scale(1, 1)
page.merge_transformed_page(page, op, expand=True)
op = Transformation().rotate(90).scale(1, 1).translate(1, 1)
page.merge_transformed_page(page, op, expand=True)
op = Transformation().translate(-100, -100).rotate(90).translate(100, 100)
page.merge_transformed_page(page, op, expand=False)
page.merge_scaled_page(page, 2, expand=False)
op = Transformation().scale(1, 1).translate(1, 1)
page.merge_transformed_page(page, op)
page.merge_translated_page(page, 100, 100, expand=False)
page.add_transformation((1, 0, 0, 0, 0, 0))
@pytest.mark.parametrize(
("pdf_path", "password"),
[
(RESOURCE_ROOT / "crazyones.pdf", None),
(RESOURCE_ROOT / "attachment.pdf", None),
(RESOURCE_ROOT / "side-by-side-subfig.pdf", None),
(
RESOURCE_ROOT / "libreoffice-writer-password.pdf",
"openpassword",
),
],
)
def test_compress_content_streams(pdf_path, password):
reader = PdfReader(pdf_path)
writer = PdfWriter()
if password:
reader.decrypt(password)
for i, page in enumerate(reader.pages):
assert i == page.page_number
assert isinstance(reader.pages[0].get_contents(), ContentStream)
writer.clone_document_from_reader(reader)
assert isinstance(writer.pages[0].get_contents(), ContentStream)
for i, page in enumerate(writer.pages):
assert i == page.page_number
page.compress_content_streams()
# test from reader should fail as adding_object out of
# PdfWriter not possible
with pytest.raises(ValueError):
reader.pages[0].compress_content_streams()
def test_page_properties():
reader = PdfReader(RESOURCE_ROOT / "crazyones.pdf")
page = reader.pages[0]
assert page.mediabox == RectangleObject((0, 0, 612, 792))
assert page.cropbox == RectangleObject((0, 0, 612, 792))
assert page.bleedbox == RectangleObject((0, 0, 612, 792))
assert page.trimbox == RectangleObject((0, 0, 612, 792))
assert page.artbox == RectangleObject((0, 0, 612, 792))
page.bleedbox = RectangleObject((0, 1, 100, 101))
assert page.bleedbox == RectangleObject((0, 1, 100, 101))
def test_page_rotation():
reader = PdfReader(RESOURCE_ROOT / "crazyones.pdf")
page = reader.pages[0]
with pytest.raises(ValueError) as exc:
page.rotate(91)
assert exc.value.args[0] == "Rotation angle must be a multiple of 90"
# test rotation
assert page.rotation == 0
page.rotation = 180
assert page.rotation == 180
page.rotation += 190
assert page.rotation == 0
# test transfer_rotate_to_content
page.rotation -= 90
page.transfer_rotation_to_content()
assert abs(float(page.mediabox.left) - 0) < 0.1
assert abs(float(page.mediabox.bottom) - 0) < 0.1
assert abs(float(page.mediabox.right) - 792) < 0.1
assert abs(float(page.mediabox.top) - 612) < 0.1
def test_page_indirect_rotation():
reader = PdfReader(RESOURCE_ROOT / "indirect-rotation.pdf")
page = reader.pages[0]
# test rotation
assert page.rotation == 0
def test_page_scale():
op = Transformation()
with pytest.raises(ValueError) as exc:
op.scale()
assert exc.value.args[0] == "Either sx or sy must be specified"
assert op.scale(sx=2).ctm == (2, 0, 0, 2, 0, 0)
assert op.scale(sy=3).ctm == (3, 0, 0, 3, 0, 0)
def test_add_transformation_on_page_without_contents():
page = PageObject()
assert page.get_contents() is None
page.add_transformation(Transformation())
page[NameObject("/Contents")] = ContentStream(None, None)
assert isinstance(page.get_contents(), ContentStream)
@pytest.mark.enable_socket
def test_iss_1142():
# check fix for problem of context save/restore (q/Q)
url = "https://github.com/py-pdf/pypdf/files/9150656/ST.2019.PDF"
name = "st2019.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
txt = reader.pages[3].extract_text()
# The following text is contained in two different cells:
assert txt.find("有限公司") > 0
assert txt.find("郑州分公司") > 0
# 有限公司 = limited company
# 郑州分公司 = branch office in Zhengzhou
# First cell (see page 4/254):
assert txt.find("郑州药素电子商务有限公司") > 0
# Next cell (first cell in next line):
assert txt.find("郑州分公司") > 0
@pytest.mark.enable_socket
@pytest.mark.slow
@pytest.mark.parametrize(
("url", "name"),
[
# keyerror_potentially_empty_page
(
"https://github.com/user-attachments/files/18381736/tika-964029.pdf",
"tika-964029.pdf",
),
# 1140 / 1141:
(
"https://github.com/user-attachments/files/18381702/tika-932446.pdf",
"tika-932446.pdf",
),
# iss 1134:
(
"https://github.com/py-pdf/pypdf/files/9150656/ST.2019.PDF",
"iss_1134.pdf",
),
# iss 1:
(
"https://github.com/py-pdf/pypdf/files/9432350/Work.Flow.From.Check.to.QA.pdf",
"WFCA.pdf",
),
(
"https://github.com/user-attachments/files/18381736/tika-964029.pdf",
"tika-964029.pdf",
), # single_quote_op
(
"https://github.com/py-pdf/pypdf/files/9428434/TelemetryTX_EM.pdf",
"tika-964029.pdf",
), # no_ressources
(
# https://www.itu.int/rec/T-REC-X.25-199610-I/en
"https://github.com/py-pdf/pypdf/files/12423313/T-REC-X.25-199610-I.PDF-E.pdf",
"T-REC-X.25-199610-I!!PDF-E.pdf",
),
],
)
def test_extract_text(url, name):
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
for page in reader.pages:
page.extract_text()
@pytest.mark.enable_socket
@pytest.mark.slow
def test_extract_text_page_pdf_impossible_decode_xform(caplog):
url = "https://github.com/user-attachments/files/18381748/tika-972962.pdf"
name = "tika-972962.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
for page in reader.pages:
page.extract_text()
warn_msgs = normalize_warnings(caplog.text)
assert warn_msgs == [""] # text extraction recognise no text
@pytest.mark.enable_socket
@pytest.mark.slow
def test_extract_text_operator_t_star(): # L1266, L1267
url = "https://github.com/user-attachments/files/18381740/tika-967943.pdf"
name = "tika-967943.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
for page in reader.pages:
page.extract_text()
def test_extract_text_visitor_callbacks():
"""
Extract text in rectangle-objects or simple tables.
This test uses GeoBase_NHNC1_Data_Model_UML_EN.pdf.
It extracts the labels of package-boxes in Figure 2.
It extracts the texts in table "REVISION HISTORY".
"""
import logging
class PositionedText:
"""
Specify a text with coordinates, font-dictionary and font-size.
The font-dictionary may be None in case of an unknown font.
"""
def __init__(self, text, x, y, font_dict, font_size) -> None:
# TODO: \0-replace: Encoding issue in some files?
self.text = text.replace("\0", "")
self.x = x
self.y = y
self.font_dict = font_dict
self.font_size = font_size
def get_base_font(self) -> str:
"""
Gets the base font of the text.
Return UNKNOWN in case of an unknown font.
"""
if (self.font_dict is None) or "/BaseFont" not in self.font_dict:
return "UNKNOWN"
return self.font_dict["/BaseFont"]
class Rectangle:
"""Specify a rectangle."""
def __init__(self, x, y, w, h) -> None:
self.x = x.as_numeric()
self.y = y.as_numeric()
self.w = w.as_numeric()
self.h = h.as_numeric()
def contains(self, x, y) -> bool:
return (
self.x <= x <= (self.x + self.w)
and self.y <= y <= (self.y + self.h)
)
def extract_text_and_rectangles(
page: PageObject, rect_filter=None
) -> Tuple[List[PositionedText], List[Rectangle]]:
"""
Extracts texts and rectangles of a page of type pypdf._page.PageObject.
This function supports simple coordinate transformations only.
The optional rect_filter-lambda can be used to filter wanted
rectangles.
rect_filter has Rectangle as argument and must return a boolean.
It returns a tuple containing a list of extracted texts and
a list of extracted rectangles.
"""
logger = logging.getLogger("extract_text_and_rectangles")
rectangles = []
texts = []
def print_op_b(op, args, cm_matrix, tm_matrix) -> None:
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f"before: {op} at {cm_matrix}, {tm_matrix}")
if op == b"re":
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f" add rectangle: {args}")
w = args[2]
h = args[3]
r = Rectangle(args[0], args[1], w, h)
if (rect_filter is None) or rect_filter(r):
rectangles.append(r)
def print_visi(text, cm_matrix, tm_matrix, font_dict, font_size) -> None:
if text.strip() != "":
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f"at {cm_matrix}, {tm_matrix}, font size={font_size}")
texts.append(
PositionedText(
text, tm_matrix[4], tm_matrix[5], font_dict, font_size
)
)
visitor_before = print_op_b
visitor_text = print_visi
page.extract_text(
visitor_operand_before=visitor_before, visitor_text=visitor_text
)
return (texts, rectangles)
def extract_table(
texts: List[PositionedText], rectangles: List[Rectangle]
) -> List[List[List[PositionedText]]]:
"""
Extracts a table containing text.
It is expected that each cell is marked by a rectangle-object.
It is expected that the page contains one table only.
It is expected that the table contains at least 3 columns and 2 rows.
A list of rows is returned.
Each row contains a list of cells.
Each cell contains a list of PositionedText-elements.
"""
logger = logging.getLogger("extractTable")
# Step 1: Count number of x- and y-coordinates of rectangles.
# Remove duplicate rectangles. The new list is rectangles_filtered.
col2count = {}
row2count = {}
key2rectangle = {}
rectangles_filtered = []
for r in rectangles:
# Coordinates may be inaccurate, we have to round.
# cell: x=72.264, y=386.57, w=93.96, h=46.584
# cell: x=72.271, y=386.56, w=93.96, h=46.59
key = f"{round(r.x, 0)} {round(r.y, 0)} {round(r.w, 0)} {round(r.h, 0)}"
if key in key2rectangle:
# Ignore duplicate rectangles
continue
key2rectangle[key] = r
if r.x not in col2count:
col2count[r.x] = 0
if r.y not in row2count:
row2count[r.y] = 0
col2count[r.x] += 1
row2count[r.y] += 1
rectangles_filtered.append(r)
# Step 2: Look for texts in rectangles.
rectangle2texts = {}
for text in texts:
for r in rectangles_filtered:
if r.contains(text.x, text.y):
if r not in rectangle2texts:
rectangle2texts[r] = []
rectangle2texts[r].append(text)
break
# PDF: y = 0 is expected at the bottom of the page.
# So the header-row is expected to have the highest y-value.
rectangles.sort(key=lambda r: (-r.y, r.x))
# Step 3: Build the list of rows containing list of cell-texts.
rows = []
row_nr = 0
col_nr = 0
curr_y = None
curr_row = None
for r in rectangles_filtered:
if col2count[r.x] < 3 or row2count[r.y] < 2:
# We expect at least 3 columns and 2 rows.
continue
if curr_y is None or r.y != curr_y:
# next row
curr_y = r.y
col_nr = 0
row_nr += 1
curr_row = []
rows.append(curr_row)
col_nr += 1
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f"cell: x={r.x}, y={r.y}, w={r.w}, h={r.h}")
if r not in rectangle2texts:
curr_row.append("")
continue
cell_texts = list(rectangle2texts[r])
curr_row.append(cell_texts)
return rows
def extract_cell_text(cell_texts: List[PositionedText]) -> str:
"""Joins the text-objects of a cell."""
return ("".join(t.text for t in cell_texts)).strip()
# Test 1: We test the analysis of page 7 "2.1 LRS model".
reader = PdfReader(RESOURCE_ROOT / "GeoBase_NHNC1_Data_Model_UML_EN.pdf")
page_lrs_model = reader.pages[6]
# We ignore the invisible large rectangles.
def ignore_large_rectangles(r) -> bool:
return r.w < 400 and r.h < 400
(texts, rectangles) = extract_text_and_rectangles(
page_lrs_model, rect_filter=ignore_large_rectangles
)
# We see ten rectangles (5 tabs, 5 boxes) but there are 64 rectangles
# (including some invisible ones).
assert len(rectangles) == 60
rectangle2texts = {}
for t in texts:
for r in rectangles:
if r.contains(t.x, t.y):
texts = rectangle2texts.setdefault(r, [])
texts.append(t.text.strip())
break
# Five boxes and the figure-description below.
assert len(rectangle2texts) == 6
box_texts = [" ".join(texts) for texts in rectangle2texts.values()]
assert "Hydro Network" in box_texts
assert "Hydro Events" in box_texts
assert "Metadata" in box_texts
assert "Hydrography" in box_texts
assert "Toponymy (external model)" in box_texts
# Test 2: Parse table "REVISION HISTORY" on page 3.
page_revisions = reader.pages[2]
# We ignore the second table, therefore: r.y > 350
def filter_first_table(r) -> bool:
return r.w > 1 and r.h > 1 and r.w < 400 and r.h < 400 and r.y > 350
(texts, rectangles) = extract_text_and_rectangles(
page_revisions, rect_filter=filter_first_table
)
rows = extract_table(texts, rectangles)
assert len(rows) == 9
assert extract_cell_text(rows[0][0]) == "Date"
assert extract_cell_text(rows[0][1]) == "Version"
assert extract_cell_text(rows[0][2]) == "Description"
assert extract_cell_text(rows[1][0]) == "September 2002"
# The line break between "English review;"
# and "Remove" is not detected.
assert (
extract_cell_text(rows[6][2])
== "English review;Remove the UML model for the Segmented view."
)
assert extract_cell_text(rows[7][2]) == "Update from the March Workshop comments."
# Check the fonts. We check: /F2 9.96 Tf [...] [(Dat)-2(e)] TJ
text_dat_of_date = rows[0][0][0]
assert text_dat_of_date.font_dict is not None
assert text_dat_of_date.font_dict["/Name"] == "/F2"
assert text_dat_of_date.get_base_font() == "/Arial,Bold"
assert text_dat_of_date.font_dict["/Encoding"] == "/WinAnsiEncoding"
assert text_dat_of_date.font_size == 9.96
# Check: /F1 9.96 Tf [...] [(S)4(ep)4(t)-10(em)-20(be)4(r)-3( 20)4(02)] TJ
texts = rows[1][0][0]
assert texts.font_dict is not None
assert texts.font_dict["/Name"] == "/F1"
assert texts.get_base_font() == "/Arial"
assert texts.font_dict["/Encoding"] == "/WinAnsiEncoding"
assert text_dat_of_date.font_size == 9.96
# Test 3: Read a table in a document using a non-translating
# but scaling Tm-operand
reader = PdfReader(RESOURCE_ROOT / "Sample_Td-matrix.pdf")
page_td_model = reader.pages[0]
# We store the translations of the Td-executions.
list_td = []
def visitor_td(op, args, cm, tm) -> None:
if op == b"Td":
list_td.append((tm[4], tm[5]))
page_td_model.extract_text(visitor_operand_after=visitor_td)
assert len(list_td) == 4
# Check the translations of the four Td-executions.
assert list_td[0] == (210.0, 110.0)
assert list_td[1] == (410.0, 110.0)
assert list_td[2] == (210.0, 210.0)
assert list_td[3] == (410.0, 210.0)
@pytest.mark.parametrize(
("pdf_path", "password", "embedded", "unembedded"),
[
(
RESOURCE_ROOT / "crazyones.pdf",
None,
{
"/HHXGQB+SFTI1440",
"/TITXYI+SFRM0900",
"/YISQAD+SFTI1200",
},
set(),
),
(
RESOURCE_ROOT / "attachment.pdf",
None,
{
"/HHXGQB+SFTI1440",
"/TITXYI+SFRM0900",
"/YISQAD+SFTI1200",
},
set(),
),
(
RESOURCE_ROOT / "libreoffice-writer-password.pdf",
"openpassword",
{"/BAAAAA+DejaVuSans"},
set(),
),
(
RESOURCE_ROOT / "imagemagick-images.pdf",
None,
set(),
{"/Helvetica"},
),
(RESOURCE_ROOT / "imagemagick-lzw.pdf", None, set(), set()),
(
RESOURCE_ROOT / "reportlab-inline-image.pdf",
None,
set(),
{"/Helvetica"},
),
# fonts in annotations
(
RESOURCE_ROOT / "FormTestFromOo.pdf",
None,
{"/CAAAAA+LiberationSans", "/EAAAAA+SegoeUI", "/BAAAAA+LiberationSerif"},
{"/LiberationSans", "/ZapfDingbats"},
),
],
)
def test_get_fonts(pdf_path, password, embedded, unembedded):
reader = PdfReader(pdf_path, password=password)
a = set()
b = set()
for page in reader.pages:
a_tmp, b_tmp = page._get_fonts()
a = a.union(a_tmp)
b = b.union(b_tmp)
assert (a, b) == (embedded, unembedded)
@pytest.mark.enable_socket
def test_get_fonts2():
url = "https://github.com/py-pdf/pypdf/files/12618104/WS_T.483.8-2016.pdf"
name = "WS_T.483.8-2016.pdf"
reader = PdfReader(BytesIO(get_data_from_url(url, name=name)))
assert reader.pages[1]._get_fonts() == (
{
"/E-HZ9-PK7483a5-Identity-H",
"/SSJ-PK748200005d9-Identity-H",
"/QGNGZS+FzBookMaker1DlFont10536872415",
"/E-BZ9-PK748344-Identity-H",
"/E-FZ9-PK74836f-Identity-H",
"/O9-PK748464-Identity-H",
"/QGNGZR+FzBookMaker0DlFont00536872414",
"/SSJ-PK748200005db-Identity-H",
"/F-BZ9-PK7483cb-Identity-H",
"/SSJ-PK748200005da-Identity-H",
"/H-SS9-PK748200005e0-Identity-H",
"/H-HT9-PK748200005e1-Identity-H",
},
set(),
)
assert reader.pages[2]._get_fonts() == (
{
"/E-HZ9-PK7483a5-Identity-H",
"/E-FZ9-PK74836f-Identity-H",
"/E-BZ9-PK748344-Identity-H",
"/QGNGZT+FzBookMaker0DlFont00536872418",
"/O9-PK748464-Identity-H",
"/F-BZ9-PK7483cb-Identity-H",
"/H-SS9-PK748200005e0-Identity-H",
"/QGNGZU+FzBookMaker1DlFont10536872420",
"/H-HT9-PK748200005e1-Identity-H",
},
set(),
)
def test_annotation_getter():
pdf_path = RESOURCE_ROOT / "commented.pdf"
reader = PdfReader(pdf_path)
annotations = reader.pages[0].annotations
assert annotations is not None
assert isinstance(annotations[0], IndirectObject)
annot_dict = dict(annotations[0].get_object())
assert "/P" in annot_dict
assert isinstance(annot_dict["/P"], IndirectObject)
del annot_dict["/P"]
annot_dict["/Popup"] = annot_dict["/Popup"].get_object()
del annot_dict["/Popup"]["/P"]
del annot_dict["/Popup"]["/Parent"]
assert annot_dict == {
"/Type": "/Annot",
"/Subtype": "/Text",
"/Rect": ArrayObject(
[
270.75,
596.25,
294.75,
620.25,
]
),
"/Contents": "Note in second paragraph",
"/C": ArrayObject([1, 1, 0]),
"/M": "D:20220406191858+02'00",
"/Popup": DictionaryObject(
{
"/M": "D:20220406191847+02'00",
"/Rect": ArrayObject([294.75, 446.25, 494.75, 596.25]),
"/Subtype": "/Popup",
"/Type": "/Annot",
}
),
"/T": "moose",
}
def test_annotation_setter(pdf_file_path):
# Arange
pdf_path = RESOURCE_ROOT / "crazyones.pdf"
reader = PdfReader(pdf_path)
page = reader.pages[0]
writer = PdfWriter()
writer.add_page(page)
with pytest.raises(ValueError):
writer.add_page(DictionaryObject())
# Act
page_number = 0
page_link = writer.get_object(writer._pages)["/Kids"][page_number]
annot_dict = {
NameObject("/P"): page_link,
NameObject("/Type"): NameObject("/Annot"),
NameObject("/Subtype"): NameObject("/Text"),
NameObject("/Rect"): ArrayObject(
[
FloatObject(270.75),
FloatObject(596.25),
FloatObject(294.75),
FloatObject(620.25),
]
),
NameObject("/Contents"): TextStringObject("Note in second paragraph"),
NameObject("/C"): ArrayObject([FloatObject(1), FloatObject(1), FloatObject(0)]),
NameObject("/M"): TextStringObject("D:20220406191858+02'00"),
NameObject("/Popup"): DictionaryObject(
{
NameObject("/M"): TextStringObject("D:20220406191847+02'00"),
NameObject("/Rect"): ArrayObject(
[
FloatObject(294.75),
FloatObject(446.25),
FloatObject(494.75),
FloatObject(596.25),
]
),
NameObject("/Subtype"): NameObject("/Popup"),
NameObject("/Type"): TextStringObject("/Annot"),
}
),
NameObject("/T"): TextStringObject("moose"),
}
arr = ArrayObject()
page.annotations = arr
# Delete Annotations
page.annotations = None
d = DictionaryObject(annot_dict)
ind_obj = writer._add_object(d)
arr.append(ind_obj)
# Assert manually
with open(pdf_file_path, "wb") as fp:
writer.write(fp)
@pytest.mark.enable_socket
@pytest.mark.xfail(reason="#1091")
def test_text_extraction_issue_1091():
url = "https://github.com/user-attachments/files/18381737/tika-966635.pdf"
name = "tika-966635.pdf"
stream = BytesIO(get_data_from_url(url, name=name))
with pytest.warns(PdfReadWarning):
reader = PdfReader(stream)
for page in reader.pages:
page.extract_text()
@pytest.mark.enable_socket
def test_empyt_password_1088():
url = "https://github.com/user-attachments/files/18381712/tika-941536.pdf"
name = "tika-941536.pdf"
stream = BytesIO(get_data_from_url(url, name=name))
reader = PdfReader(stream)
len(reader.pages)
@pytest.mark.enable_socket
def test_old_habibi():
# this habibi has multiple characters associated with the h
reader = PdfReader(SAMPLE_ROOT / "015-arabic/habibi.pdf")
txt = reader.pages[0].extract_text() # very odd file
# extract from acrobat reader "حَبيبي habibi
assert "habibi" in txt
assert "حَبيبي" in txt
@pytest.mark.samples
def test_read_link_annotation():
reader = PdfReader(SAMPLE_ROOT / "016-libre-office-link/libre-office-link.pdf")
assert len(reader.pages[0].annotations) == 1
annot = dict(reader.pages[0].annotations[0].get_object())
expected = {
"/Type": "/Annot",
"/Subtype": "/Link",
"/A": DictionaryObject(
{
"/S": "/URI",
"/Type": "/Action",
"/URI": "https://martin-thoma.com/",
}
),
"/Border": ArrayObject([0, 0, 0]),
"/Rect": [
92.043,
771.389,
217.757,
785.189,
],
}
assert set(expected.keys()) == set(annot.keys())
del expected["/Rect"]
del annot["/Rect"]
assert annot == expected