0

I am writing some code using PYPDF2 to append a blank page where a pdf document has an odd number of pages.

Issue: Code adds the blank page, but all previous pages with text are given as blank. Any ideas as to where the issue is in the code below?

Any help would be very much appreciated. Thanks.

#Import Packages
from PyPDF2 import PdfFileWriter, PdfFileReader
import os

directory=r'C:\Users\sarah\.spyder-py3\pdf_test'

for file in os.listdir(directory):
    if file.endswith('.pdf'):
        with open(os.path.join(directory,file), 'rb') as pdfFileObj:  
            pdf=PdfFileReader(pdfFileObj)
            numPages=pdf.getNumPages()

            if numPages % 2 == 1:
                outpdf=PdfFileWriter()
                outpdf.appendPagesFromReader(pdf)
                outpdf.addBlankPage()

          with open(os.path.join(directory,file), 'wb') as pdfFileObj2:  
                outpdf.write(pdfFileObj2)    
#Additional code which resolves the issue - Save output files to a new directory
outdir=os.path.join(indir+r'\new2')
                if os.path.exists(outdir):
                    print(outdir + ' : directory already exists')
                if not os.path.exists(outdir):
                    mkdir=os.mkdir(outdir)
                    print(outdir + ' : directory created')            
  • https://stackoverflow.com/questions/52499339/pypdf2-why-does-pdffilewriter-forget-changes-i-made-to-a-document# – Joe May 10 '20 at 13:39
  • Thanks for the link. Does the .appendPagesFromReader not copy the content of the pdf then? – SarahChapman May 10 '20 at 15:33
  • It should work. I made some edits to your code, it might be that the indentation was the problem. Since you are still in the `with` context, the original pdf file might still be open. Please try to save a file with a different name. – Joe May 10 '20 at 16:53
  • Just tested this by adding the indent and saving the output files into a new directory with the same name, to avoid the issues with the original file being open. Thanks for your help, really big help whilst in the early stages of learning python. – SarahChapman May 10 '20 at 19:14
  • Amended code to include solution – SarahChapman May 10 '20 at 19:20

0 Answers0