icon

Table of Contents

How to Generate PDFs with Python, PDFKit and CraftMyPDF

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
blog

A Guide to Generate Barcodes and QRcodes

In this article, we’ll explore barcodes and QR codes, discussing their applications and how they’re used in various scenarios. I’ll guide you through the steps to create these codes using Python and Node.js. Additionally, we’ll look at how to generate barcodes and QR codes with CraftMyPDF, which supports REST API and integrates seamlessly with no-code platforms like Zapier, Make.com, and Bubble.

Read More »
blog

How to generate PDF documents with PHP

There are various libraries available to generate PDF documents with PHP such as FPDF, TCPDF, or DOMPDF. These libraries provide a wide range of features for creating PDF documents, such as setting page size, margins, fonts, and images.

In this article, I would briefly discuss some of these libraries along with some code snippets and show you how to generate a PDF document using PHP and CraftMyPDF.

Read More »
blog

5 Ways to generate PDFs with C#

In this article, we will cover different options available, including using libraries such as iTextSharp and PdfSharp, cloud-based APIs such as CraftMyPDF, built-in classes in the .NET Framework like the PrintDocument class, and the Microsoft Office Interop library.

Read More »
blog

How to Generate PDF Invoices with Zapier

With PDF invoices, it’s easier to send invoices directly to clients without needing paper copies.

In this article, I would be showing you how to generate PDF invoices with Zapier and also help you understand the benefits of doing this. Let’s get to it!

Read More »
blog

Best-performing Banner Ads Sizes in 2023

Choosing the most appropriate banner for your company isn’t always easy. There are lots of things to consider such as the color, size, type of banner, and so on. This could be a little problematic if you have no knowledge of the different types of banner ads but don’t worry, that’s why I’m here.

Read More »
Copyright ©2024 CraftMyPDF.com

Email us at [email protected] for support