Gnudiff
Gnudiff

Reputation: 4305

Adding blank page to odd-paged PDF in Python

This is a rewrite of How to insert a "missing" page as blank page in PDF with Python? but I am trying to do it with the PdfFileWriter additional methods: cloneDocumentFromReader() and addBlankPage(), because it seemed cleaner this way.

I need to add a blank page at the end of PDF, if it contains odd number of pages, but the page count is larger than 1.

So I am trying to do this:

from PyPDF2 import PdfFileReader, PdfFileWriter
with open(pdffile, 'rb') as input:
    pdf=PdfFileReader(input)
    numPages=pdf.getNumPages()
    if numPages > 1 and (numPages % 2 == 1):
            outPdf=PdfFileWriter()
            outPdf.cloneDocumentFromReader(pdf)
            outPdf.addBlankPage()
            outStream=file('/tmp/test.pdf','wb')
            outPdf.write(outStream)
            outStream.close()

The code works, but the PDF created is smaller than the original, and gives error (doesn't parse) when trying to open in Adobe Acrobat.

Do I mix up something with how this should work? I was a bit surprised when I saw I couldn't navigate in Pdf with PdfWriter to choose where to add blank page, but I assumed, after I have cloned the document, it should have some internal "marker" at the end page?

Upvotes: 3

Views: 3168

Answers (1)

Gnudiff
Gnudiff

Reputation: 4305

Sorry, it turns out I did need another method. Namely PdfWriter.appendPagesFromReader() .

Upvotes: 3

Related Questions