pypdf icon indicating copy to clipboard operation
pypdf copied to clipboard

writer.add_page(page) increasing page size

Open Atomnp opened this issue 1 year ago • 0 comments

writer. add_page(page) increase page size, I have a pdf file, each file of this pdf file contains two slides merged into one, I want to split each page into two and create a new pdf by doing this to all pages in the pdf. I have included my solution which doesn't work. The issue is that it never finishes running. When I tried to inspect the issue I found that the size of the page object in each iteration increased very quickly.

Environment

Arch linux python version 3.10.6

Code + PDF

from PyPDF2 import PdfWriter, PdfReader
reader = PdfReader('rmi.pdf') 
writer = PdfWriter()
import copy

for page in reader.pages:
    
    left_half=copy.deepcopy(page)
    right_half=copy.deepcopy(page)
    

    old_ll=page.cropbox.lower_left 
    old_lr=page.cropbox.lower_right
    old_ul= page.cropbox.upper_left
    old_ur= page.cropbox.upper_right 
    

    x1,y1=old_ur[0]/2,old_ur[1]
    x2,y2=old_lr[0]/2,old_lr[1]
    
    left_half.mediabox.upper_left = old_ul 
    left_half.mediabox.lower_right = (x2,y2)


    right_half.mediabox.upper_left = (x1,y1) 
    right_half.mediabox.lower_right = old_lr
    
    writer.add_page(left_half)
    writer.add_page(right_half)
  
with open('result.pdf','wb') as fp:
    writer.write(fp) 

rmi.pdf

I also found the working solution but I don't know why the code below works but the one above don't

from PyPDF2 import PdfWriter, PdfReader
reader = PdfReader('rmi.pdf') 
writer = PdfWriter()
import copy

for page in reader.pages:
    
    left_half=copy.deepcopy(page)
    right_half=copy.deepcopy(page)
    

    old_ll=page.cropbox.lower_left 
    old_lr=page.cropbox.lower_right
    old_ul= page.cropbox.upper_left
    old_ur= page.cropbox.upper_right 
    

    x1,y1=old_ur[0]/2,old_ur[1]
    x2,y2=old_lr[0]/2,old_lr[1]
    
    left_half.mediabox.upper_left = old_ul 
    left_half.mediabox.lower_right = (x2,y2)


    right_half.mediabox.upper_left = (x1,y1) 
    right_half.mediabox.lower_right = old_lr
    
    writer.add_page(left_half)
    writer.add_page(right_half)
  
with open('result.pdf','wb') as fp:
    writer.write(fp) 

Atomnp avatar Sep 09 '22 17:09 Atomnp