How to download a pdf file generated from a plot?

Thanks for your help.

Hereafter I put a workaround. In that case, I use a button to make the picture and a link to download this picture when the picture is produced.

Nevertheless, I am not sure it works online. I did not succeed in installing orca on my server (I do not have neither conda nor npm).

#!/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
from flask import Flask, send_from_directory
from urllib.parse import quote as urlquote

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

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

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

PLOTS_DIRECTORY = "./plots"

@server.route("/download/<path:path>")
def download(path):
    """Serve a file from the upload directory."""
    return send_from_directory(PLOTS_DIRECTORY, path, as_attachment=True)


@app.callback(Output('download-img-btn', 'children'),
              [Input('make-img-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, PLOTS_DIRECTORY + filename)

        url = "/download/" + urlquote(filename)

        return html.A(download=filename, href=url, children=["Download " + filename])

if __name__ == '__main__':
    app.run_server(debug=True)
3 Likes