Create PDF file without having to save locally

Viewed 105

I have a flask API deployed as a container on AWS Lightsail where I'm using the PdfPages class from matplotlib's backend_pdf to save figures to a pdf file. The PdfPages class takes a filename as an argument, writes the data to the file, and saves the file locally. An example is shown below:

with PdfPages('foo.pdf') as pdf:
fig = plt.figure()
pdf.savefig(fig)
pdf.savefig()

My question is this: How can I save all the figures and return them as part of the response from the server?

My initial solution was to save the figure objects to a list and return the list like so:

fig_list = []
for i in range(0, len(data)):
    fig = plt.figure()
    fig_list.append(fig)
response = {'figures': fig_list}
return jsonify(response)

The problem with this is that the Figure object is not JSON serializable and therefore I can't return the list as part of my response from the API. What other ways can I achieve this without having to create and save a pdf file?

0 Answers
Related