1

Based on https://programtalk.com/python-examples/PyPDF2.PdfFileWriter/, example 2, I try to to add an attachment into a PDF file.

Here is my code I am trying to run:

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)

When I run this code, I get: "TypeError: a bytes-like object is required, not 'str'".

If I replace

with open(doc, 'wb') as fp:
    meta.write(fp)

by:

with open(doc, 'wb') as fp:
    meta.write(b'fp')

I get this error: "'bytes' object has no attribute 'write'".

And if I try:

with open(doc, 'w') as fp:
    meta.write(fp)

I get this error: "write() argument must be str, not bytes"

Can anyone help me?

4

1 回答 1

0

addAttachment 中的第二个参数必须是类似字节的对象。您可以通过对字符串进行编码来做到这一点:

meta.addAttachment("The filename to display", "The data in the file".encode())
于 2017-12-29T10:47:59.503 回答