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?