[英]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.