icon

How to Generate PDFs with Python, PDFKit and CraftMyPDF

Table of Contents

Introduction

PDF stands for portable document format, it’s designed to be compatible across different operating systems. There are many use-cases of PDF documents, you can create invoices, contracts, shipping labels, and other PDF documents.

There are different approaches to generating PDFs in Python. Template-based PDF generation is the best way to create PDFs, it gives you the flexibility to create dynamic PDFs from pre-defined templates.

In this article, we are going to use a python library PDFKit to generate PDFs from HTML. In addition, we also make use of CraftMyPDF’s PDF generation API to create PDF documents from a drag-and-drop template.

Create PDFs with Python Library – PDFKit

HTML is the standard markup language for the webpages and it is used to define the structure and content of web documents. The easiest way to create PDFs is to render PDFs from HTML templates.

wkhtmltopdf is an open-source command-line tool that renders HTML into PDF with the Qt WebKit rendering engine. You can run the command in the console to generate PDFs.

To use the command-line in Python, JazzCore developed PDFKit – a wrapper for wkhtmltopdf utility.

First, we need to install wkhtmltopdf in Linux/Ubuntu

sudo apt-get update
sudo apt-get install xvfb libfontconfig wkhtmltopdf

Then, install the PDFKit library

pip3 install pdfkit

Once wkhtmltopdf and PDFKit are installed, the next step is to create a Python file to generate a PDF from a URL.

The following is a simple example to pass the URL to wkhtmltopdf and generate a local file craftmy.pdf.

import pdfkit
pdfkit.from_url('https://craftmypdf.com', 'craftmy.pdf')

One of the coolest features of PDFKit is that can generate a PDF from directly HTML

import pdfkit
html_sample = """<h1><b>This is a heading 1</b></h1>
       <p>1st line ...</p>
       <p>2nd line ...</p>
       <p>3rd line ...</p>
       <p>4th line ...</p>
       """

pdfkit.from_string(html_sample, output_path = "craftmy.pdf")

The output of the PDF

Generate PDFs with CraftMyPDF

CraftMyPDF provides PDF generation API, and it comes with an easy-to-use drag & drop editor to let you design templates in any browser and generate pixel-perfect PDF documents from pre-defined templates and JSON data.

First, design a PDF template, the following is a packing list template designed with CraftMyPDF’s PDF template editor.

The following is the Python snippet to generate a PDF from a template:

import requests, json

def main():
    # Please replace this with your API Key
    api_key = "7832MjA6MTE6UjlkM3h4emxpTExzeFR0aQ="
    data = {
      'invoice_number': 'INV38379',
      'date': '2021-09-30',
      'currency': 'USD',
      'total_amount': 82542.56
    }

    json_payload = {
      "data": json.dumps(data) ,
      "output_file": "output.pdf",
      "export_type": "json",
      "expiration": 10,
      "template_id": "05f77b2b18ad809a"
    }

    # Calling the REST API to generate a PDF
    response = requests.post(
        F"https://api.craftmypdf.com/v1/create",
        headers = {"X-API-KEY": F"{api_key}"},
        json = json_payload
    )

    print(response.content)

if __name__ == "__main__":
    main()

Conclusion

Both methods offer you an easy way to turn templates and data into PDF documents.

In the first part of the tutorial, we walked you through the library PDFKit to generate PDFs from HTML in Python. In the second part, you have learned how to make use of REST API to generate PDFs with Python and CraftMyPDF.

To generate PDF documents from highly reusable templates, sign up for a free CraftMyPDF account now.

Recent Posts
Copyright ©2022 CraftMyPDF.com

Email us at hello@craftmypdf.com for support