Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug in mediabox expansion when applying non-right angle rotation #2282

Merged
merged 6 commits into from
Nov 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 0 additions & 5 deletions pypdf/_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -1655,11 +1655,6 @@ def add_transformation(

lowerleft = (min(new_x), min(new_y))
upperright = (max(new_x), max(new_y))
lowerleft = (min(corners[0], lowerleft[0]), min(corners[1], lowerleft[1]))
upperright = (
max(corners[2], upperright[0]),
max(corners[3], upperright[1]),
)

self.mediabox.lower_left = lowerleft
self.mediabox.upper_right = upperright
Expand Down
29 changes: 29 additions & 0 deletions tests/test_page.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Test the pypdf._page module."""
import json
import math
from copy import deepcopy
from io import BytesIO
from pathlib import Path
Expand Down Expand Up @@ -122,6 +123,34 @@ def test_page_operations(pdf_path, password):
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 expension 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 upto 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)
Expand Down