Quantcast
Channel: 🎛️ Dash - Plotly Community Forum
Viewing all articles
Browse latest Browse all 6271

How to download a pdf file generated from a plot?

$
0
0

@gvallverdu wrote:

Hi

I would like to add a button in order to download a plot in, let says, pdf format. I succeeded to write the pdf file in the assets/plots/ folder but I am unable to pass the url of this file to the button in order to download the file.

Hereafter is a minimal example with what I have tried to do. If you click on the button, the file exits, you can browse to http://127.0.0.1:8050/assets/plots/figure.pdf and you get the file. But the button to not send the file.

#!/usr/bin/env python3
# -*- coding=utf-8 -*-

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

from plotly.io import write_image
import flask

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.A(
        id="img-download", 
        href="", 
        children=[html.Button("Download Image", id="download-btn")], 
        target="_blank",
    ),
    dcc.Graph(
        id='graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'scatter'},
            ],
            'layout': {'title': 'So Title'}
        }
    )
])

@app.callback(Output('img-download', 'href'),
              [Input('download-btn', 'n_clicks'),
               Input('graph', 'figure')])
def make_image(n_clicks, figure):
    """ Make a picture """

    fmt = "pdf"
    filename = "figure.%s" % fmt

    if n_clicks is not None:
        write_image(figure, "assets/plots/" + filename)

        url = flask.request.host + app.get_asset_url("plots/" + filename)
        print(url)
        return url

if __name__ == '__main__':
    app.run_server(debug=False)

I also inspected the html code generated (inside chrome). It seems the link is ok, but still it does not work.

Thank you for your help

Posts: 4

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 6271

Latest Images

Trending Articles



Latest Images