2017-10-04 63 views
1

這是How to insert a "missing" page as blank page in PDF with Python?的重寫,但我試圖使用PdfFileWriter其他方法:cloneDocumentFromReader()addBlankPage(),因爲它看起來更清晰。在Python中向奇數頁PDF添加空白頁面

我需要在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比原始文件小,並且在嘗試在Adobe Acrobat中打開時出現錯誤(不解析)。

我是否會混淆這些應該如何工作?當我看到我無法用PdfWriter選擇要添加空白頁的位置時,我感到有些驚訝,但是我假設,在克隆了文檔之後,它應該在最終頁面有一些內部「標記」?

回答

1

對不起,事實證明我確實需要另一種方法。即PdfWriter.appendPagesFromReader()