Я пытаюсь сделать PDF на лету в моем приложении. Я недавно портировал код Python 2 на Python 3. И теперь он терпит неудачу с FPDF error: Not a PNG file: /tmp/tmpoi0oz__u
в этой строке
with tempfile.NamedTemporaryFile(mode='w+b', buffering=1) as f:
f.write(base64.b64decode(signature_data))
self.image(f.name, type='PNG', h=40) # Fails here (says this is not a PNG).
...
Код:
...
try:
from fpdf import FPDF, HTMLMixin
from io import BytesIO
import tempfile
html = """
<img src="{}/static/media/logo.png" height="25">
""".format(script_dir)
class PDF(FPDF, HTMLMixin):
def footer(self):
if signature_data:
with tempfile.NamedTemporaryFile(mode='w+b', buffering=1) as f:
f.write(base64.b64decode(signature_data))
self.image(f.name, type='PNG', h=40)
self.cell(0, 10, 'Signed on: {}'.format(timestamp), 0, 1, 'L')
else:
self.cell(0, 10, 'No valid signature was found. Please contact us for a new form.', 0, 1, 'C')
self.set_y(-15)
self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Arial', '', 12)
pdf.write_html(html)
tf = tempfile.NamedTemporaryFile()
with open(tf.name, "w", encoding='utf-8',
errors='ignore') as f:
pdf.output(f.name, dest='F')
attachment = f.name
send_mail(subject="Your PDF", message=message,
bcc_mail="myemail@gmail.com", attachment=attachment)
except Exception as e:
import traceback
print(traceback.format_exc())
print("PDF FAIL")
...
Трассировка:
Traceback (most recent call last):
File "registration.py", line 233, in send_mail_with_pdf
pdf.output(f.name, dest='F')
File "venv/lib/python3.6/site-packages/fpdf/fpdf.py", line 1065, in output
self.close()
File "venv/lib/python3.6/site-packages/fpdf/fpdf.py", line 241, in close
self.footer()
File "registration.py", line 218, in footer
self.image(f.name, type='PNG', h=40)
File "venv/lib/python3.6/site-packages/fpdf/fpdf.py", line 150, in wrapper
return fn(self, *args, **kwargs)
File "venv/lib/python3.6/site-packages/fpdf/fpdf.py", line 971, in image
info=self._parsepng(name)
File "venv/lib/python3.6/site-packages/fpdf/fpdf.py", line 1780, in _parsepng
self.error('Not a PNG file: '+name)
File "venv/lib/python3.6/site-packages/fpdf/fpdf.py", line 227, in error
raise RuntimeError('FPDF error: '+msg)
RuntimeError: FPDF error: Not a PNG file: /tmp/tmpoi0oz__u
PDF FAIL
FPDF error: Not a PNG file: /tmp/tmpoi0oz__u
Я пытался найти проблему в течение нескольких часов и не могу продолжить. Пожалуйста, помогите.