Skip to content

Commit 2cf9c27

Browse files
committed
Add up2_main function to support configurable page layouts (2x2, 3x3, 1x2, 2x1) without impacting default behavior.
1 parent 80d3f4c commit 2cf9c27

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

pdfly/up2.py

+42
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,45 @@ def main(pdf: Path, output: Path) -> None:
2727
with open(output, "wb") as fp:
2828
writer.write(fp)
2929
print("done.")
30+
31+
def up2_main(pdf: Path, output: Path, layout: str = None) -> None:
32+
reader = PdfReader(str(pdf))
33+
writer = PdfWriter()
34+
35+
if layout:
36+
# Define layout configurations (columns, rows) for each grid type
37+
layout_options = {
38+
"2x2": (2, 2),
39+
"3x3": (3, 3),
40+
"1x2": (1, 2),
41+
"2x1": (2, 1)
42+
}
43+
44+
if layout not in layout_options:
45+
raise ValueError(f"Unsupported layout: {layout}")
46+
47+
columns, rows = layout_options[layout]
48+
# Adjusted to use 'mediabox' instead of 'media_box'
49+
page_width = reader.pages[0].mediabox.width / columns
50+
page_height = reader.pages[0].mediabox.height / rows
51+
52+
# Arrange pages in specified grid
53+
for i in range(0, len(reader.pages), columns * rows):
54+
new_page = writer.add_blank_page(width=reader.pages[0].mediabox.width,
55+
height=reader.pages[0].mediabox.height)
56+
57+
for col in range(columns):
58+
for row in range(rows):
59+
index = i + row * columns + col
60+
if index < len(reader.pages):
61+
page = reader.pages[index]
62+
x_position = col * page_width
63+
y_position = reader.pages[0].mediabox.height - (row + 1) * page_height
64+
new_page.merge_translated_page(page, x_position, y_position)
65+
else:
66+
# Default behavior: add pages without grid layout
67+
for page in reader.pages:
68+
writer.add_page(page)
69+
70+
with open(output, "wb") as f_out:
71+
writer.write(f_out)

0 commit comments

Comments
 (0)