Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display a website written in Dash as a static PDF (Python)?

I want to export the site I've made in dash into a static PDF. Here is the code for my site (it's just a chart with 3 columns):

import dash
import dash_core_components as dcc
import dash_html_components as html
import pdfkit
from flask import Flask, render_template, make_response

app = dash.Dash()
app.layout = html.Div(
                className="three columns",
                children=html.Div([
                    dcc.Graph(
                        id='right-top-graph',
                        figure={
                            'data': [{
                                'x': [1, 2, 3],
                                'y': [3, 1, 2],
                                'type': 'bar'
                            }],
                            'layout': {
                                'height': 400,
                                'margin': {'l': 10, 'b': 20, 't': 0, 'r': 0}
                            }
                        }
                    ),


                ])
            )

app.css.append_css({
    'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})

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

I tried using pdfkit by adding this code to my script, but it didn't work (received an error telling me that render_template() takes 1 positional argument but 2 were given):

rendered = render_template('pdf_template.html',app)
pdf = pdfkit.from_string(rendered, False)
response = make_response(pdf)
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = 'attachment; filename=output.pdf'

Does anyone have any idea as to how I can convert my dash site into a PDF?

Thanks in advance.

like image 633
semiflex Avatar asked Oct 15 '18 15:10

semiflex


1 Answers

You can use the print function of whatever browser you are using (usually control + p) and save it as PDF if all you are looking for is the static PDF file.

If you want more enhanced functionality you can add a print to PDF button like the one in one of the dash examples. It uses a js file to invoke the browser print functionality, see more detail. This way you can also use CSS to define the way the PDF output looks

The problem with using the python file to generate pdf directly is that dash only creates a JSON representation of the layout tree which is then assembled in the browser itself, see more.

like image 177
Sam Avatar answered Oct 24 '22 06:10

Sam