[英]PyPDF2.PdfFileWriter addAttachment not working
基於https://programtalk.com/python-examples/PyPDF2.PdfFileWriter/示例2,我嘗試將附件添加到PDF文件中。
這是我要運行的代碼:
import os
import PyPDF2
from django.conf import settings
...
doc = os.path.join(settings.BASE_DIR, "../media/SC/myPDF.pdf")
unmeta = PyPDF2.PdfFileReader(doc, "rb")
meta = PyPDF2.PdfFileWriter()
meta.appendPagesFromReader(unmeta)
meta.addAttachment("The filename to display", "The data in the file")
with open(doc, 'wb') as fp:
meta.write(fp)
運行此代碼時,我得到:“ TypeError:需要一個類似字節的對象,而不是'str'”。
如果我更換
with open(doc, 'wb') as fp:
meta.write(fp)
通過:
with open(doc, 'wb') as fp:
meta.write(b'fp')
我收到此錯誤:“'字節'對象沒有屬性'寫'”。
如果我嘗試:
with open(doc, 'w') as fp:
meta.write(fp)
我收到此錯誤:“ write()參數必須為str,而不是字節”
誰能幫我?
addAttachment中的第二個參數必須是類似字節的對象。 您可以通過編碼字符串來做到這一點:
meta.addAttachment("The filename to display", "The data in the file".encode())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.