Mosky1970
Mosky1970

Reputation: 73

Writing multiple matplotlib figures to PDF file

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??

Upvotes: 1

Views: 486

Answers (1)

Mosky1970
Mosky1970

Reputation: 73

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)

Upvotes: 1

Related Questions