简体   繁体   中英

PyPDF2.PdfFileWriter addAttachment not working

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?

Second argument in addAttachment has to be a byte-like object. You can do that by encoding the string:

meta.addAttachment("The filename to display", "The data in the file".encode())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM