Sep-27-2023, 09:27 PM
Hi guys,
My goal is pretty simple: to split a PDF page 2/3 the way down and move the bottom third on top.
I've been trying multiple ways to figure this out using PyPDF2 and haven't been able to crack it. Whenever I test/debug by making changes to my code I get very unexpected results even after going over the documentation. I feel like I'm misunderstanding something fundamental about what's going on here so any help would be much appreciated.
I am currently doing it in two steps, (which probably isn't the best but I'm not sure how to combine it either without saving it to file in between).
Step 1: Crop the page and save the split pages as a new PDF
My goal is pretty simple: to split a PDF page 2/3 the way down and move the bottom third on top.
I've been trying multiple ways to figure this out using PyPDF2 and haven't been able to crack it. Whenever I test/debug by making changes to my code I get very unexpected results even after going over the documentation. I feel like I'm misunderstanding something fundamental about what's going on here so any help would be much appreciated.
I am currently doing it in two steps, (which probably isn't the best but I'm not sure how to combine it either without saving it to file in between).
Step 1: Crop the page and save the split pages as a new PDF
# Get the page dimensions width = page.mediabox.width height = page.mediabox.height # Calculate the bottom third of the page bottom = height / 3 # Crop the bottom third and add it as a new page page.mediabox.lower_left = (0, 0) page.mediabox.upper_right = (width, bottom) PageTop = writer.add_page(page) # Crop the top two thirds and add it as a new page page.mediabox.lower_left = (0, bottom) page.mediabox.upper_right = (width, height) PageBottom = writer.add_page(page)Step 2: Add a new blank page and merge the two cropped pages
# Calculate dimensions max_width = max(page1.mediabox.width, page2.mediabox.width) sum_height = page1.mediabox.height + page2.mediabox.height # Create a new blank page with the calculated dimensions new_page = PageObject.create_blank_page(width = max_width, height = sum_height) # Add 1st page (bottom 3rd of the original) to the top new_page.merge_page(page1) # Add 2nd page (top 2/3 of the original) underneath page2.add_transformation(Transformation().translate(0, page2.mediabox.height)) new_page.merge_page(page2) # Add the merged page to the output output_pdf.add_page(new_page)Thanks for your time.