Flask-WkHTMLtoPDF

Flask-WkHTMLtoPDF


Convert JavaScript dependent Flask templates into PDFs with wkhtmltopdf.

copyright:
  1. 2015 by Chris Griffin
license:

MIT, see LICENSE file for more info

class flask_wkhtmltopdf.Wkhtmltopdf(app=None)[source]

Wkhtmltopdf class container to use the robust wkhtmltopdf library which is capable of generating a PDF from HTML, CSS, and JavaScript using a modified WebKit engine. This extension allows you to easily incorporate this functionality into your Flask app.

In addition to the dependencies automatically installed, you must manually download the appropriate wkhtmltopdf command line tool from http://wkhtmltopdf.org/downloads.html

The main function render_template_to_pdf() works similar to Flask’s built-in render_template() function and in fact utilizes some of the same underlying functions. However, as the name suggests, it will return a pdf instead of a rendered webpage.

To initialize, pass your flask app’s object to Flask-WkHTMLtoPDF:

from flask_wkhtmltopdf import Wkhtmltopdf

app = Flask(__name__)
wkhtmltopdf = Wkhtmltopdf(app)

Then pass the template to the render_template_to_pdf() function. You can pass Jinja2 params just like with render_template():

render_template_to_pdf('test.html', download=True, save=False, param='hello')

Celery, an asynchronous task queue, is highly suggested when using Flask-WkHTMLtoPDF as rendering the PDF can be resource heavy and take an unacceptable amount of time to generate. To enable Celery, set ‘WKHTMLTOPDF_USE_CELERY = True’ in your Flask app’s config.

You must add three variables to your Flask app’s config:

WKHTMLTOPDF_BIN_PATH = r'C:\Program Files\wkhtmltopdfin'
PDF_DIR_PATH =  os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'pdf')
render_template_to_pdf(template_name_or_list, save=False, download=False, wkhtmltopdf_args=None, **context)[source]

Renders a template from the template folder with the given context and produces a pdf. As this can be resource intensive, the function can easily be decorated with celery.task() by setting the WKHTMLTOPDF_USE_CELERY to True.

Parameters:
  • template_name_or_list – The name of the template to be rendered, or an iterable with template names. The first one existing will be rendered.
  • save – Specifies whether to save the temporary pdf generated. Defaults to False.
  • download – Specifies if the pdf should be displayed in the browser or downloaded as an attachment. Defaults to False (in browser).
  • context – The variables that should be available in the context of the Jinja2 template.
  • wkhtmltopdf_args – Optional list of arguments to send to wkhtmltopdf (list of – options)