Generate PDF with Python Flask or Django

February 17th, 2019 / by api2pdf /

If you are building a web application in Python with either of the two most popular frameworks – Flask or Django, there’s a good chance you will need to support functionality for PDF generation.

Convert HTML to PDF with Flask or Django

To generate PDFs, we are going to use API2PDF. API2PDF is a REST API that supports PDF generation at massive scale. It can scale to millions of requests, has no rate limits or file size limits. Most importantly, it provides you the choice to generate PDFs with either Headless Chrome or wkhtmltopdf.

In the example below, we are going to use Headless Chrome. Start by installing the api2pdf client library with

pip install api2pdf

Then grab an api key at https://portal.api2pdf.com/register. It only takes a minute and it’s free to get started.

For convenience, I create some helper methods to abstract away from the library in case you want to swap out API2PDF with something else at a later time. See the sample code below. I tend to put this in its own file, such as pdf_manager.py.

Switch out “YOUR-API-KEY” with the api key you acquired from API2PDF. You should now be ready to generate PDFs! Give it a shot by calling the functions either with a url to an existing website or raw HTML. The functions will return a file-like object to the PDF that you can do with whatever you’d like. If you prefer to just grab the URL that was generated from API2PDF, you can return that instead.

That’s all!

Tags: , , , , , , ,

Comments are closed.