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')