1

I have a list of Matplotlib figures that are saved as bytes in pdf format and base64 encoded. I wish to save these figures to a PDF file with the following code:

with open('result.pdf', 'wb') as f:
    for fig in f_list:
        f.write(base64.b64decode(fig))

The file is created successfully but it seems like only the last figure is saved to the file. What am I doing wrong??

4
  • Can you append PDFs to each other like that? Do you have something like poppler installed? You could use pdfunite if you did. Commented Jan 12, 2022 at 3:43
  • wb overwrites the file. You can append with ab, but that doesn't fix your problem. That appends bytes. If you want to add pages to a PDF, then you'll need a Python library that knows how to do that. Commented Jan 12, 2022 at 3:52
  • If you have more than one fig in the list, they will all be written. How do you know there is only one? Are you using a pdf reader? You could sum the size of the decoded figures in the loop and see if that matches file size. Commented Jan 12, 2022 at 4:02
  • Turns out all the figures were being written to the file but only the last page was being displayed. I used PyPDF2 to fix this Commented Jan 13, 2022 at 8:40

1 Answer 1

1

All the figures are being written to the file but only the last page was being displayed. I had to use a PyPDF2 to save and display all the pages.

The implementation is below:

from PyPDF2 import PdfFileReader, PdfFileWriter


writer = PdfFileWriter()
for fig in f_list:
    decoded_data = base64.b64decode(fig)
    reader = PdfFileReader(io.BytesIO(decoded_data)) # convert the figure to a stream object
    writer.addPage(reader.getPage(0))

with open('result.pdf', 'wb') as pdf_file:
    writer.write(pdf_file)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.