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
|
import os
from io import BytesIO
from pathlib import Path
from unittest.mock import patch
import pytest
from PyPDF2 import PdfMerger, PdfReader, PdfWriter
from PyPDF2.constants import CheckboxRadioButtonAttributes
from PyPDF2.constants import TypFitArguments as TF
from PyPDF2.errors import PdfReadError, PdfStreamError
from PyPDF2.generic import (
AnnotationBuilder,
ArrayObject,
BooleanObject,
ByteStringObject,
Destination,
DictionaryObject,
FloatObject,
IndirectObject,
NameObject,
NullObject,
NumberObject,
OutlineItem,
RectangleObject,
TextStringObject,
TreeObject,
create_string_object,
encode_pdfdocencoding,
read_hex_string_from_stream,
read_object,
read_string_from_stream,
)
from . import ReaderDummy, get_pdf_from_url
TESTS_ROOT = Path(__file__).parent.resolve()
PROJECT_ROOT = TESTS_ROOT.parent
RESOURCE_ROOT = PROJECT_ROOT / "resources"
class ChildDummy(DictionaryObject):
@property
def indirect_reference(self):
return self
def test_float_object_exception(caplog):
assert FloatObject("abc") == 0
assert caplog.text != ""
def test_number_object_exception(caplog):
assert NumberObject("0,0") == 0
assert caplog.text != ""
def test_number_object_no_exception():
NumberObject(2**100000000)
def test_create_string_object_exception():
with pytest.raises(TypeError) as exc:
create_string_object(123)
assert ( # typeguard is not running
exc.value.args[0] == "create_string_object should have str or unicode arg"
) or ( # typeguard is enabled
'type of argument "string" must be one of (str, bytes); got int instead'
in exc.value.args[0]
)
@pytest.mark.parametrize(
("value", "expected", "tell"), [(b"true", b"true", 4), (b"false", b"false", 5)]
)
def test_boolean_object(value, expected, tell):
stream = BytesIO(value)
assert BooleanObject.read_from_stream(stream).value == (expected == b"true")
stream.seek(0, 0)
assert stream.read() == expected
assert stream.tell() == tell
def test_boolean_object_write():
stream = BytesIO()
boolobj = BooleanObject(None)
boolobj.write_to_stream(stream, encryption_key=None)
stream.seek(0, 0)
assert stream.read() == b"false"
def test_boolean_eq():
boolobj = BooleanObject(True)
assert (boolobj == True) is True # noqa: E712
assert (boolobj == False) is False # noqa: E712
assert (boolobj == "True") is False
boolobj = BooleanObject(False)
assert (boolobj == True) is False # noqa: E712
assert (boolobj == False) is True # noqa: E712
assert (boolobj == "True") is False
def test_boolean_object_exception():
stream = BytesIO(b"False")
with pytest.raises(PdfReadError) as exc:
BooleanObject.read_from_stream(stream)
assert exc.value.args[0] == "Could not read Boolean object"
def test_array_object_exception():
stream = BytesIO(b"False")
with pytest.raises(PdfReadError) as exc:
ArrayObject.read_from_stream(stream, None)
assert exc.value.args[0] == "Could not read array"
def test_null_object_exception():
stream = BytesIO(b"notnull")
with pytest.raises(PdfReadError) as exc:
NullObject.read_from_stream(stream)
assert exc.value.args[0] == "Could not read Null object"
@pytest.mark.parametrize("value", [b"", b"False", b"foo ", b"foo ", b"foo bar"])
def test_indirect_object_premature(value):
stream = BytesIO(value)
with pytest.raises(PdfStreamError) as exc:
IndirectObject.read_from_stream(stream, None)
assert exc.value.args[0] == "Stream has ended unexpectedly"
def test_readHexStringFromStream():
stream = BytesIO(b"a1>")
assert read_hex_string_from_stream(stream) == "\x10"
def test_readHexStringFromStream_exception():
stream = BytesIO(b"")
with pytest.raises(PdfStreamError) as exc:
read_hex_string_from_stream(stream)
assert exc.value.args[0] == "Stream has ended unexpectedly"
def test_readStringFromStream_exception():
stream = BytesIO(b"x")
with pytest.raises(PdfStreamError) as exc:
read_string_from_stream(stream)
assert exc.value.args[0] == "Stream has ended unexpectedly"
def test_readStringFromStream_not_in_escapedict_no_digit():
stream = BytesIO(b"x\\y")
with pytest.raises(PdfReadError) as exc:
read_string_from_stream(stream)
assert exc.value.args[0] == "Stream has ended unexpectedly"
def test_readStringFromStream_multichar_eol():
stream = BytesIO(b"x\\\n )")
assert read_string_from_stream(stream) == " "
def test_readStringFromStream_multichar_eol2():
stream = BytesIO(b"x\\\n\n)")
assert read_string_from_stream(stream) == ""
def test_readStringFromStream_excape_digit():
stream = BytesIO(b"x\\1a )")
assert read_string_from_stream(stream) == "\x01a "
def test_readStringFromStream_excape_digit2():
stream = BytesIO(b"(hello \\1\\2\\3\\4)")
assert read_string_from_stream(stream) == "hello \x01\x02\x03\x04"
def test_NameObject(caplog):
stream = BytesIO(b"x")
with pytest.raises(PdfReadError) as exc:
NameObject.read_from_stream(stream, None)
assert exc.value.args[0] == "name read error"
assert (
NameObject.read_from_stream(
BytesIO(b"/A;Name_With-Various***Characters?"), None
)
== "/A;Name_With-Various***Characters?"
)
assert (
NameObject.read_from_stream(BytesIO(b"/paired#28#29parentheses"), None)
== "/paired()parentheses"
)
assert NameObject.read_from_stream(BytesIO(b"/A#42"), None) == "/AB"
assert (
NameObject.read_from_stream(
BytesIO(b"/#f1j#d4#aa#0c#ce#87#b4#b3#b0#23J#86#fe#2a#b2jYJ#94"),
ReaderDummy(),
)
== "/ñjÔª\x0cÎ\x87´³°#J\x86þ*²jYJ\x94"
)
assert (NameObject.read_from_stream(BytesIO(b"/#JA#231f"), None)) == "/#JA#1f"
assert (
NameObject.read_from_stream(
BytesIO(b"/#e4#bd#a0#e5#a5#bd#e4#b8#96#e7#95#8c"), None
)
) == "/你好世界"
# test write
b = BytesIO()
NameObject("/hello").write_to_stream(b, None)
assert bytes(b.getbuffer()) == b"/hello"
caplog.clear()
b = BytesIO()
NameObject("hello").write_to_stream(b, None)
assert bytes(b.getbuffer()) == b"hello"
assert "Incorrect first char" in caplog.text
caplog.clear()
b = BytesIO()
NameObject("/DIJMAC+Arial Black#1").write_to_stream(b, None)
assert bytes(b.getbuffer()) == b"/DIJMAC+Arial#20Black#231"
assert caplog.text == ""
b = BytesIO()
NameObject("/你好世界").write_to_stream(b, None)
assert bytes(b.getbuffer()) == b"/#E4#BD#A0#E5#A5#BD#E4#B8#96#E7#95#8C"
assert caplog.text == ""
def test_destination_fit_r():
d = Destination(
TextStringObject("title"),
NullObject(),
NameObject(TF.FIT_R),
FloatObject(0),
FloatObject(0),
FloatObject(0),
FloatObject(0),
)
assert d.title == NameObject("title")
assert d.typ == "/FitR"
assert d.zoom is None
assert d.left == FloatObject(0)
assert d.right == FloatObject(0)
assert d.top == FloatObject(0)
assert d.bottom == FloatObject(0)
assert list(d) == []
d.empty_tree()
def test_destination_fit_v():
Destination(NameObject("title"), NullObject(), NameObject(TF.FIT_V), FloatObject(0))
# Trigger Exception
Destination(NameObject("title"), NullObject(), NameObject(TF.FIT_V), None)
def test_destination_exception():
with pytest.raises(PdfReadError) as exc:
Destination(
NameObject("title"), NullObject(), NameObject("foo"), FloatObject(0)
)
assert exc.value.args[0] == "Unknown Destination Type: 'foo'"
def test_outline_item_write_to_stream():
stream = BytesIO()
oi = OutlineItem(
NameObject("title"), NullObject(), NameObject(TF.FIT_V), FloatObject(0)
)
oi.write_to_stream(stream, None)
stream.seek(0, 0)
assert stream.read() == b"<<\n/Title (title)\n/Dest [ null /FitV 0 ]\n>>"
def test_encode_pdfdocencoding_keyerror():
with pytest.raises(UnicodeEncodeError) as exc:
encode_pdfdocencoding("😀")
assert exc.value.args[0] == "pdfdocencoding"
def test_read_object_comment_exception():
stream = BytesIO(b"% foobar")
pdf = None
with pytest.raises(PdfStreamError) as exc:
read_object(stream, pdf)
assert exc.value.args[0] == "File ended unexpectedly."
def test_read_object_empty():
stream = BytesIO(b"endobj")
pdf = None
assert isinstance(read_object(stream, pdf), NullObject)
def test_read_object_invalid():
stream = BytesIO(b"hello")
pdf = None
with pytest.raises(PdfReadError) as exc:
read_object(stream, pdf)
assert "hello" in exc.value.args[0]
def test_read_object_comment():
stream = BytesIO(b"% foobar\n1 ")
pdf = None
out = read_object(stream, pdf)
assert out == 1
def test_ByteStringObject():
bo = ByteStringObject("stream", encoding="utf-8")
stream = BytesIO(b"")
bo.write_to_stream(stream, encryption_key="foobar")
stream.seek(0, 0)
assert stream.read() == b"<1cdd628b972e>" # TODO: how can we verify this?
def test_DictionaryObject_key_is_no_pdfobject():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
with pytest.raises(ValueError) as exc:
do["foo"] = NameObject("/GoTo")
assert exc.value.args[0] == "key must be PdfObject"
def test_DictionaryObject_xmp_meta():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
assert do.xmp_metadata is None
def test_DictionaryObject_value_is_no_pdfobject():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
with pytest.raises(ValueError) as exc:
do[NameObject("/S")] = "/GoTo"
assert exc.value.args[0] == "value must be PdfObject"
def test_DictionaryObject_setdefault_key_is_no_pdfobject():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
with pytest.raises(ValueError) as exc:
do.setdefault("foo", NameObject("/GoTo"))
assert exc.value.args[0] == "key must be PdfObject"
def test_DictionaryObject_setdefault_value_is_no_pdfobject():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
with pytest.raises(ValueError) as exc:
do.setdefault(NameObject("/S"), "/GoTo")
assert exc.value.args[0] == "value must be PdfObject"
def test_DictionaryObject_setdefault_value():
do = DictionaryObject({NameObject("/S"): NameObject("/GoTo")})
do.setdefault(NameObject("/S"), NameObject("/GoTo"))
def test_DictionaryObject_read_from_stream():
stream = BytesIO(b"<< /S /GoTo >>")
pdf = None
out = DictionaryObject.read_from_stream(stream, pdf)
assert out.get_object() == {NameObject("/S"): NameObject("/GoTo")}
def test_DictionaryObject_read_from_stream_broken():
stream = BytesIO(b"< /S /GoTo >>")
pdf = None
with pytest.raises(PdfReadError) as exc:
DictionaryObject.read_from_stream(stream, pdf)
assert (
exc.value.args[0]
== "Dictionary read error at byte 0x2: stream must begin with '<<'"
)
def test_DictionaryObject_read_from_stream_unexpected_end():
stream = BytesIO(b"<< \x00/S /GoTo")
pdf = None
with pytest.raises(PdfStreamError) as exc:
DictionaryObject.read_from_stream(stream, pdf)
assert exc.value.args[0] == "Stream has ended unexpectedly"
def test_DictionaryObject_read_from_stream_stream_no_newline():
stream = BytesIO(b"<< /S /GoTo >>stream")
pdf = None
with pytest.raises(PdfReadError) as exc:
DictionaryObject.read_from_stream(stream, pdf)
assert exc.value.args[0] == "Stream data must be followed by a newline"
@pytest.mark.parametrize(("strict"), [(True), (False)])
def test_DictionaryObject_read_from_stream_stream_no_stream_length(strict):
stream = BytesIO(b"<< /S /GoTo >>stream\n")
class Tst: # to replace pdf
strict = False
pdf = Tst()
pdf.strict = strict
with pytest.raises(PdfReadError) as exc:
DictionaryObject.read_from_stream(stream, pdf)
assert exc.value.args[0] == "Stream length not defined"
@pytest.mark.parametrize(
("strict", "length", "should_fail"),
[
(True, 6, False),
(True, 10, False),
(True, 4, True),
(False, 6, False),
(False, 10, False),
],
)
def test_DictionaryObject_read_from_stream_stream_stream_valid(
strict, length, should_fail
):
stream = BytesIO(b"<< /S /GoTo /Length %d >>stream\nBT /F1\nendstream\n" % length)
class Tst: # to replace pdf
strict = True
pdf = Tst()
pdf.strict = strict
with pytest.raises(PdfReadError) as exc:
do = DictionaryObject.read_from_stream(stream, pdf)
# TODO: What should happen with the stream?
assert do == {"/S": "/GoTo"}
if length in (6, 10):
assert b"BT /F1" in do._StreamObject__data
raise PdfReadError("__ALLGOOD__")
assert should_fail ^ (exc.value.args[0] == "__ALLGOOD__")
def test_RectangleObject():
ro = RectangleObject((1, 2, 3, 4))
assert ro.lower_left == (1, 2)
assert ro.lower_right == (3, 2)
assert ro.upper_left == (1, 4)
assert ro.upper_right == (3, 4)
ro.lower_left = (5, 6)
assert ro.lower_left == (5, 6)
ro.bottom -= 2
ro.left -= 2
assert ro.lower_left == (3, 4)
ro.lower_right = (7, 8)
assert ro.lower_right == (7, 8)
ro.upper_left = (9, 11)
assert ro.upper_left == (9, 11)
ro.upper_right = (13, 17)
assert ro.upper_right == (13, 17)
ro.top += 1
ro.right += 1
assert ro.upper_right == (14, 18)
def test_TextStringObject_exc():
tso = TextStringObject("foo")
with pytest.raises(Exception) as exc:
tso.get_original_bytes()
assert exc.value.args[0] == "no information about original bytes"
def test_TextStringObject_autodetect_utf16():
tso = TextStringObject("foo")
tso.autodetect_utf16 = True
assert tso.get_original_bytes() == b"\xfe\xff\x00f\x00o\x00o"
def test_remove_child_not_in_tree():
tree = TreeObject()
with pytest.raises(ValueError) as exc:
tree.remove_child(ChildDummy())
assert exc.value.args[0] == "Removed child does not appear to be a tree item"
def test_remove_child_not_in_that_tree():
tree = TreeObject()
tree.indirect_reference = NullObject()
# child = ChildDummy(TreeObject())
child = TreeObject()
with pytest.raises(ValueError) as exc:
child.remove_from_tree()
assert exc.value.args[0] == "Removed child does not appear to be a tree item"
tree.add_child(child, ReaderDummy())
with pytest.raises(ValueError) as exc:
tree.remove_child(child)
assert exc.value.args[0] == "Removed child is not a member of this tree"
def test_remove_child_not_found_in_tree():
class ChildDummy(DictionaryObject):
@property
def indirect_reference(self):
return self
tree = TreeObject()
tree.indirect_reference = NullObject()
child = ChildDummy(TreeObject())
tree.add_child(child, ReaderDummy())
child2 = ChildDummy(TreeObject())
child2[NameObject("/Parent")] = tree
with pytest.raises(ValueError) as exc:
tree.remove_child(child2)
assert exc.value.args[0] == "Removal couldn't find item in tree"
def test_remove_child_found_in_tree():
writer = PdfWriter()
# Add Tree
tree = TreeObject()
writer._add_object(tree)
# Add first child
# It's important to set a value, otherwise the writer.get_reference will
# return the same object when a second child is added.
child1 = TreeObject()
child1[NameObject("/Foo")] = TextStringObject("bar")
child1_ref = writer._add_object(child1)
tree.add_child(child1_ref, writer)
assert tree[NameObject("/Count")] == 1
assert len([el for el in tree.children()]) == 1
# Add second child
child2 = TreeObject()
child2[NameObject("/Foo")] = TextStringObject("baz")
child2_ref = writer._add_object(child2)
tree.add_child(child2_ref, writer)
assert tree[NameObject("/Count")] == 2
assert len([el for el in tree.children()]) == 2
# Remove last child
tree.remove_child(child2_ref)
assert tree[NameObject("/Count")] == 1
assert len([el for el in tree.children()]) == 1
# Add new child
child3 = TreeObject()
child3[NameObject("/Foo")] = TextStringObject("3")
child3_ref = writer._add_object(child3)
tree.add_child(child3_ref, writer)
assert tree[NameObject("/Count")] == 2
assert len([el for el in tree.children()]) == 2
# Remove first child
child1 = tree[NameObject("/First")]
tree.remove_child(child1)
assert tree[NameObject("/Count")] == 1
assert len([el for el in tree.children()]) == 1
child4 = TreeObject()
child4[NameObject("/Foo")] = TextStringObject("4")
child4_ref = writer._add_object(child4)
tree.add_child(child4_ref, writer)
assert tree[NameObject("/Count")] == 2
assert len([el for el in tree.children()]) == 2
child5 = TreeObject()
child5[NameObject("/Foo")] = TextStringObject("5")
child5_ref = writer._add_object(child5)
tree.add_child(child5_ref, writer)
assert tree[NameObject("/Count")] == 3
assert len([el for el in tree.children()]) == 3
# Remove middle child
# tree.remove_child(child4)
child4.remove_from_tree()
assert tree[NameObject("/Count")] == 2
assert len([el for el in tree.children()]) == 2
tree.empty_tree()
def test_remove_child_in_tree():
pdf = RESOURCE_ROOT / "form.pdf"
tree = TreeObject()
reader = PdfReader(pdf)
writer = PdfWriter()
writer._add_object(tree)
writer.add_page(reader.pages[0])
writer.add_outline_item("foo", page_number=0)
obj = writer._objects[-1]
tree.add_child(obj, writer)
tree.remove_child(obj)
tree.add_child(obj, writer)
tree.empty_tree()
@pytest.mark.external
def test_dict_read_from_stream(caplog):
url = "https://corpora.tika.apache.org/base/docs/govdocs1/984/984877.pdf"
name = "tika-984877.pdf"
return
reader = PdfReader(BytesIO(get_pdf_from_url(url, name=name)))
for page in reader.pages:
page.extract_text()
assert (
"Multiple definitions in dictionary at byte 0x1084 for key /Length"
in caplog.text
)
@pytest.mark.external
def test_parse_content_stream_peek_percentage():
url = "https://corpora.tika.apache.org/base/docs/govdocs1/985/985770.pdf"
name = "tika-985770.pdf"
return
reader = PdfReader(BytesIO(get_pdf_from_url(url, name=name)))
for page in reader.pages:
page.extract_text()
@pytest.mark.external
def test_read_inline_image_no_has_q():
# pdf/df7e1add3156af17a372bc165e47a244.pdf
url = "https://corpora.tika.apache.org/base/docs/govdocs1/998/998719.pdf"
name = "tika-998719.pdf"
return
reader = PdfReader(BytesIO(get_pdf_from_url(url, name=name)))
for page in reader.pages:
page.extract_text()
@pytest.mark.external
def test_read_inline_image_loc_neg_1():
url = "https://corpora.tika.apache.org/base/docs/govdocs1/935/935066.pdf"
name = "tika-935066.pdf"
return
reader = PdfReader(BytesIO(get_pdf_from_url(url, name=name)))
for page in reader.pages:
page.extract_text()
@pytest.mark.slow
@pytest.mark.external
def test_text_string_write_to_stream():
url = "https://corpora.tika.apache.org/base/docs/govdocs1/924/924562.pdf"
name = "tika-924562.pdf"
return
reader = PdfReader(BytesIO(get_pdf_from_url(url, name=name)))
for page in reader.pages:
page.compress_content_streams()
@pytest.mark.external
def test_name_object_read_from_stream_unicode_error(): # L588
url = "https://corpora.tika.apache.org/base/docs/govdocs1/974/974966.pdf"
name = "tika-974966.pdf"
return
reader = PdfReader(BytesIO(get_pdf_from_url(url, name=name)))
for page in reader.pages:
page.extract_text()
@pytest.mark.external
def test_bool_repr(tmp_path):
url = "https://corpora.tika.apache.org/base/docs/govdocs1/932/932449.pdf"
name = "tika-932449.pdf"
return
reader = PdfReader(BytesIO(get_pdf_from_url(url, name=name)))
write_path = tmp_path / "tmp-fields-report.txt"
with open(write_path, "w") as fp:
fields = reader.get_fields(fileobj=fp)
assert fields
assert list(fields.keys()) == ["USGPOSignature"]
with open(write_path) as fp:
data = fp.read()
assert data.startswith(
"Field Name: USGPOSignature\nField Type: Signature\nField Flags: 1\n"
"Value: {'/Type': '/Sig', '/Filter': '/Adobe.PPKLite', "
"'/SubFilter':"
)
@pytest.mark.external
@patch("PyPDF2._reader.logger_warning")
def test_issue_997(mock_logger_warning):
url = "https://github.com/py-pdf/PyPDF2/files/8908874/Exhibit_A-2_930_Enterprise_Zone_Tax_Credits_final.pdf"
name = "gh-issue-997.pdf"
return
merger = PdfMerger()
merged_filename = "tmp-out.pdf"
merger.append(BytesIO(get_pdf_from_url(url, name=name))) # here the error raises
with open(merged_filename, "wb") as f:
merger.write(f)
merger.close()
mock_logger_warning.assert_called_with(
"Overwriting cache for 0 4", "PyPDF2._reader"
)
# Strict
merger = PdfMerger(strict=True)
merged_filename = "tmp-out.pdf"
with pytest.raises(PdfReadError) as exc:
merger.append(
BytesIO(get_pdf_from_url(url, name=name))
) # here the error raises
assert exc.value.args[0] == "Could not find object."
with open(merged_filename, "wb") as f:
merger.write(f)
merger.close()
# cleanup
os.remove(merged_filename)
def test_annotation_builder_free_text():
# Arrange
pdf_path = RESOURCE_ROOT / "crazyones.pdf"
reader = PdfReader(pdf_path)
page = reader.pages[0]
writer = PdfWriter()
writer.add_page(page)
# Act
free_text_annotation = AnnotationBuilder.free_text(
"Hello World - bold and italic\nThis is the second line!",
rect=(50, 550, 200, 650),
font="Arial",
bold=True,
italic=True,
font_size="20pt",
font_color="00ff00",
border_color="0000ff",
background_color="cdcdcd",
)
writer.add_annotation(0, free_text_annotation)
free_text_annotation = AnnotationBuilder.free_text(
"Another free text annotation (not bold, not italic)",
rect=(500, 550, 200, 650),
font="Arial",
bold=False,
italic=False,
font_size="20pt",
font_color="00ff00",
border_color="0000ff",
background_color="cdcdcd",
)
writer.add_annotation(0, free_text_annotation)
# Assert: You need to inspect the file manually
target = "annotated-pdf.pdf"
with open(target, "wb") as fp:
writer.write(fp)
os.remove(target) # comment this out for manual inspection
def test_annotation_builder_line():
# Arrange
pdf_path = RESOURCE_ROOT / "crazyones.pdf"
reader = PdfReader(pdf_path)
page = reader.pages[0]
writer = PdfWriter()
writer.add_page(page)
# Act
line_annotation = AnnotationBuilder.line(
text="Hello World\nLine2",
rect=(50, 550, 200, 650),
p1=(50, 550),
p2=(200, 650),
)
writer.add_annotation(0, line_annotation)
# Assert: You need to inspect the file manually
target = "annotated-pdf.pdf"
with open(target, "wb") as fp:
writer.write(fp)
os.remove(target) # comment this out for manual inspection
def test_annotation_builder_square():
# Arrange
pdf_path = RESOURCE_ROOT / "crazyones.pdf"
reader = PdfReader(pdf_path)
page = reader.pages[0]
writer = PdfWriter()
writer.add_page(page)
# Act
square_annotation = AnnotationBuilder.rectangle(
rect=(50, 550, 200, 650), interiour_color="ff0000"
)
writer.add_annotation(0, square_annotation)
square_annotation = AnnotationBuilder.rectangle(
rect=(40, 400, 150, 450),
)
writer.add_annotation(0, square_annotation)
# Assert: You need to inspect the file manually
target = "annotated-pdf-square.pdf"
with open(target, "wb") as fp:
writer.write(fp)
os.remove(target) # comment this out for manual inspection
def test_annotation_builder_link():
# Arrange
pdf_path = RESOURCE_ROOT / "outline-without-title.pdf"
reader = PdfReader(pdf_path)
page = reader.pages[0]
writer = PdfWriter()
writer.add_page(page)
# Act
# Part 1: Too many args
with pytest.raises(ValueError) as exc:
AnnotationBuilder.link(
rect=(50, 550, 200, 650),
url="https://martin-thoma.com/",
target_page_index=3,
)
assert (
exc.value.args[0]
== "Either 'url' or 'target_page_index' have to be provided. url=https://martin-thoma.com/, target_page_index=3"
)
# Part 2: Too few args
with pytest.raises(ValueError) as exc:
AnnotationBuilder.link(
rect=(50, 550, 200, 650),
)
assert (
exc.value.args[0]
== "Either 'url' or 'target_page_index' have to be provided. Both were None."
)
# Part 3: External Link
link_annotation = AnnotationBuilder.link(
rect=(50, 50, 100, 100),
url="https://martin-thoma.com/",
border=[1, 0, 6, [3, 2]],
)
writer.add_annotation(0, link_annotation)
# Part 4: Internal Link
link_annotation = AnnotationBuilder.link(
rect=(100, 100, 300, 200),
target_page_index=1,
border=[50, 10, 4],
)
writer.add_annotation(0, link_annotation)
for page in reader.pages[1:]:
writer.add_page(page)
# Assert: You need to inspect the file manually
target = "annotated-pdf-link.pdf"
with open(target, "wb") as fp:
writer.write(fp)
os.remove(target) # comment this out for manual inspection
def test_annotation_builder_text():
# Arrange
pdf_path = RESOURCE_ROOT / "outline-without-title.pdf"
reader = PdfReader(pdf_path)
page = reader.pages[0]
writer = PdfWriter()
writer.add_page(page)
# Act
text_annotation = AnnotationBuilder.text(
text="Hello World\nThis is the second line!",
rect=(50, 550, 500, 650),
open=True,
)
writer.add_annotation(0, text_annotation)
# Assert: You need to inspect the file manually
target = "annotated-pdf-popup.pdf"
with open(target, "wb") as fp:
writer.write(fp)
os.remove(target) # comment this out for manual inspection
def test_CheckboxRadioButtonAttributes_opt():
assert "/Opt" in CheckboxRadioButtonAttributes.attributes_dict()
def test_name_object_invalid_decode():
stream = BytesIO(b"/\x80\x02\x03")
# strict:
with pytest.raises(PdfReadError) as exc:
NameObject.read_from_stream(stream, ReaderDummy(strict=True))
assert "Illegal character in Name Object" in exc.value.args[0]
# non-strict:
stream.seek(0)
NameObject.read_from_stream(stream, ReaderDummy(strict=False))
def test_indirect_object_invalid_read():
stream = BytesIO(b"0 1 s")
with pytest.raises(PdfReadError) as exc:
IndirectObject.read_from_stream(stream, ReaderDummy())
assert exc.value.args[0] == "Error reading indirect object reference at byte 0x5"
def test_create_string_object_force():
assert create_string_object(b"Hello World", []) == "Hello World"
assert create_string_object(b"Hello World", {72: "A"}) == "Aello World"
assert create_string_object(b"Hello World", "utf8") == "Hello World"
@pytest.mark.parametrize(
("value", "expected"),
[
("0.000000", "0"),
("0.0", "0"),
("1.0", "1"),
("0.123000", "0.123"),
("0.000123000", "0.000123"),
("0.0", "0"),
("0", "0"),
("1", "1"),
("1.0", "1"),
("1.01", "1.01"),
("1.010", "1.01"),
("0000.0000", "0"),
("0.10101010", "0.1010101"),
("50000000000", "50000000000"),
("99900000000000000123", "99900000000000000123"),
("99900000000000000123.456000", "99900000000000000123.456"),
("0.00000000000000000000123", "0.00000000000000000000123"),
("0.00000000000000000000123000", "0.00000000000000000000123"),
(
"50032481330523882508234.00000000000000000000123000",
"50032481330523882508234.00000000000000000000123",
),
(
"928457298572093487502198745102973402987412908743.75249875981374981237498213740000",
"928457298572093487502198745102973402987412908743.7524987598137498123749821374",
),
],
)
def test_float_object_decimal_to_string(value, expected):
assert repr(FloatObject(value)) == expected
|