'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

from django.conf import settings

from PyPDF2 import PdfFileReader, PdfFileWriter

...

doc = os.path.join(settings.BASE_DIR, "../media/SC/myPDF.pdf")

reader = PdfFileReader(doc, "rb")

writer = PdfFileWriter()
writer.appendPagesFromReader(reader)

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

with open(doc, "wb") as fp:
    writer.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:
    writer.write(fp)

by:

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

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

And if I try:

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

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

Can anyone help me?



Solution 1:[1]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Thoma