Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyFPDF returns a blank pdf after encoding as a byte string

Tags:

python

fpdf

I need to convert a PyFPDF object into a byte string first, and then save it as a file. However, the following code saves a blank PDF file. When I add pages, the blank pages are added, but all text disappears. What can I do to solve this problem?

The PDF creation code is taken from the Hello World example.

pdf = FPDF('P', 'mm', 'A4')
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
pdf.cell(40, 10, 'Hello World!')
pdf.close()
return_byte_string = pdf.output("output_file.pdf", 'S')

with open("output_file.pdf", "w") as pdf_file:
    pdf_file.write(return_byte_string)    
like image 445
Emerson Hsieh Avatar asked Sep 16 '25 02:09

Emerson Hsieh


1 Answers

If you are using python 3.x, you need to do the following.

return_byte_string = pdf.output("output_file.pdf", 'S').encode('latin-1')
like image 81
Shifa Avatar answered Sep 18 '25 14:09

Shifa