在 Python 中将空白页添加到奇数页 PDF

Adding blank page to odd-paged PDF in Python

这是对 How to insert a "missing" page as blank page in PDF with Python? 的重写,但我正在尝试使用 PdfFileWriter 附加方法:cloneDocumentFromReader()addBlankPage(),因为这样看起来更干净.

我需要在 PDF 的末尾添加一个空白页,如果它包含奇数页,但页数大于 1。

所以我正在尝试这样做:

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

代码有效,但创建的 PDF 比原始文件小,并且在尝试在 Adob​​e Acrobat 中打开时出错(不解析)。

我是否混淆了它的工作原理?当我看到我无法使用 PdfWriter 在 Pdf 中导航以选择添加空白页的位置时,我感到有点惊讶,但我假设,在我克隆文档之后,它应该在结束页面有一些内部 "marker" ?

抱歉,原来我需要另一种方法。即 PdfWriter.appendPagesFromReader() .