Plotly Chart to PDF in Streamlit using st.download_button without saving the chart as HTML?

Just wondering if someone has worked this one out ?

Hi @horasio! :wave:

Have you tried adding pdfkit?

Best,
Charly

Did you have any issues using the method exeplained in the documentation

import plotly.io as pio
import plotly.express as pe
fig = pe.scatter(df, x = X, y = Y)
pio.write_image(fig, ‘Chart.pdf’, format=‘pdf’)

#please not fig is the chart that Plotly has produced.

You can put

pio.write_image(fig, ‘Chart.pdf’, format=‘pdf’)

inside st.button. But I want to put that line inside st.download_button so that the file gets downloaded to default download folder of the browser.

write_image allows you to write to a file-like object. You can write to an instance of io.BytesIO.

import io

f = io.BytesIO()
pio.write_image(fig, f, format="pdf")

And then pass its contents to download_button.

st.download_button("Download PDF", data=f.getvalue())

Alternatively you can use to_image that will return the bytes right away.

to_image

is the one I went with as it doesn’t download anything natively and where st.download_button works well

Thank you

check this post out !

hope it help !