2013-11-26 41 views
0

嗨即時嘗試水印PDF文件使用pypdf2雖然我得到這個錯誤,我不知道出了什麼問題。使用Python 2.7.6在Windows 32位pypdf2 1.19PYPDF水印返回錯誤

Traceback (most recent call last): File "test.py", line 13, in <module> 
    page.mergePage(watermark.getPage(0)) File "C:\Python27\site-packages\PyPDF2\pdf.py", line 1594, in mergePage 
    self._mergePage(page2) File "C:\Python27\site-packages\PyPDF2\pdf.py", line 1651, in _mergePage 
    page2Content, rename, self.pdf) File "C:Python27\site-packages\PyPDF2\pdf.py", line 1547, in 
_contentStreamRename 
    op = operands[i] KeyError: 0 

我碰到下面的錯誤。 希望有人能告訴我我做錯了什麼。

我的Python文件:

from PyPDF2 import PdfFileWriter, PdfFileReader 

output = PdfFileWriter() 
input = PdfFileReader(open("test.pdf", "rb")) 
watermark = PdfFileReader(open("watermark.pdf", "rb")) 

# print how many pages input1 has: 
print("test.pdf has %d pages." % input.getNumPages()) 
print("watermark.pdf has %d pages." % watermark.getNumPages()) 

# add page 0 from input, but first add a watermark from another PDF: 
page = input.getPage(0) 
page.mergePage(watermark.getPage(0)) 
output.addPage(page) 

# finally, write "output" to document-output.pdf 
outputStream = file("outputs.pdf", "wb") 
output.write(outputStream) 
outputStream.close() 

回答

0

試着寫一個StringIO的對象,而不是一個磁盤文件。因此,更換此:

outputStream = file("outputs.pdf", "wb") 
output.write(outputStream) 
outputStream.close() 

與此:

outputStream = StringIO.StringIO() 
output.write(outputStream) #write merged output to the StringIO object 
outputStream.close() 

如果上面的代碼工作,那麼你可能是具有文件寫入權限問題。作爲參考,請看PyPDF working example in my article

+0

謝謝Prahlad,解決了一些。我發現程序在水印文件中遇到了一些問題。在重新制作水印文件並更改權限後,它就像一個魅力一樣工作。 – user1949157

+0

更新工作示例的斷開鏈接https://www.prahladyeri.com/blog/2013/11/how-to-generate-pdf-in-python-for-google-app-engine.html –

+0

@JulioTrecenti,謝謝努力!事實上,我之前將博客從Openshift wordpress遷移到github頁面,因爲它的空閒並且沒有轉換上限。 –

0

我嘗試使用PyPDF2其中已被reportlab生成的網頁,其中使用了內嵌圖像canvas.drawInlineImage(...),存儲PDF的對象流中的圖像合併時遇到這個錯誤。對圖像使用類似技術的其他PDF可能會以同樣的方式受到影響 - 實際上,PDF的內容流中有一個數據對象被拋入其中,PyPDF2並不期望它。

如果您有能力,解決方案可以重新生成源pdf,但不要使用內嵌的內容流存儲的圖像 - 例如在reportlab中使用canvas.drawImage(...)生成。

這是PyPDF2上的issue about this