Skip to content

Commit

Permalink
Add up2_main function to support configurable page layouts (2x2, 3x3,…
Browse files Browse the repository at this point in the history
… 1x2, 2x1) without impacting default behavior.
  • Loading branch information
mulla028 committed Oct 30, 2024
1 parent 80d3f4c commit 2cf9c27
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions pdfly/up2.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,45 @@ def main(pdf: Path, output: Path) -> None:
with open(output, "wb") as fp:
writer.write(fp)
print("done.")

def up2_main(pdf: Path, output: Path, layout: str = None) -> None:
reader = PdfReader(str(pdf))
writer = PdfWriter()

if layout:
# Define layout configurations (columns, rows) for each grid type
layout_options = {
"2x2": (2, 2),
"3x3": (3, 3),
"1x2": (1, 2),
"2x1": (2, 1)
}

if layout not in layout_options:
raise ValueError(f"Unsupported layout: {layout}")

columns, rows = layout_options[layout]
# Adjusted to use 'mediabox' instead of 'media_box'
page_width = reader.pages[0].mediabox.width / columns
page_height = reader.pages[0].mediabox.height / rows

# Arrange pages in specified grid
for i in range(0, len(reader.pages), columns * rows):
new_page = writer.add_blank_page(width=reader.pages[0].mediabox.width,
height=reader.pages[0].mediabox.height)

for col in range(columns):
for row in range(rows):
index = i + row * columns + col
if index < len(reader.pages):
page = reader.pages[index]
x_position = col * page_width
y_position = reader.pages[0].mediabox.height - (row + 1) * page_height
new_page.merge_translated_page(page, x_position, y_position)
else:
# Default behavior: add pages without grid layout
for page in reader.pages:
writer.add_page(page)

with open(output, "wb") as f_out:
writer.write(f_out)

0 comments on commit 2cf9c27

Please sign in to comment.