HTML to PDF with Python and wkhtmltopdf or Headless Chrome

November 22nd, 2018 / by api2pdf /

Intro

In this article we will cover converting HTML to PDF format with Python with just a few lines of code and the Api2Pdf API. Api2Pdf is an HTML to PDF API built on AWS Lambda that allows you to produce PDFs at massive scale. Api2Pdf offers both wkhtmltopdf and Headless Chrome as options to use. In addition to converting HTML to PDF, the REST API provides capability for converting a URL to a PDF, Microsoft Office files using LibreOffice, merging PDFs together, as well as bar codes and QR codes using Zebra Crossing (ZXING). In this article, we will focus just on HTML to PDF conversion.

Install the Api2Pdf Client Library

In order to convert HTML to PDF with Python, we need to first install the Api2Pdf client library. The library’s documentation and code is available on Github here. Use pip to install with the following command.

pip install api2pdf

Grab an API Key

Quickly grab an API key by creating an account on portal.api2pdf.com. It only takes a minute.

Convert HTML to PDF with Python

Start with the sample code below and replace ‘YOUR-API-KEY’ with the API key you acquired from the previous step. This example uses Headless Chrome.

from api2pdf import Api2Pdf
a2p_client = Api2Pdf('YOUR-API-KEY')
api_response = a2p_client.HeadlessChrome.convert_from_html('<p>Hello, World</p>')
print(api_response.result)

That’s all there is to it!

Tags: , , , , , , , , , , , , , , , , , ,

Comments are closed.