4

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)    
Emerson Hsieh
  • 234
  • 3
  • 21
  • Why not let fPDF write the file? Just change the S to F on the `pdf.output1` call and remove the assignment. – Dave Jun 18 '19 at 11:39
  • Please have a look at [this answer](https://stackoverflow.com/a/76197700/17865804) – Chris May 08 '23 at 05:28

1 Answers1

2

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')
Shifa
  • 21
  • 4