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

Automate PDF Generation with N8n and CraftMyPDF

Whether it’s generating invoices, reports, or customized documents, automation tools make the process more efficient. One powerful way to achieve this is by combining the versatility of n8n with the capabilities of CraftMyPDF.

Let’s explore how you can use N8n and CraftMyPDF integration to automate PDF generation.

Read More »
blog

8 tips for Optimizing Your PDF Generation

In this post, we’ll go over 8 practical tips to help you optimize your PDF creation with CraftMyPDF. Whether you’re just starting or already familiar with the tool, these tips will make your PDF generation easier and more efficient.

Read More »
blog

How to generate PDF documents with Flutterflow

The purpose of this blog post is to provide a step-by-step guide on generating PDFs in FlutterFlow using CraftMyPDF.

By following this guide, you’ll learn how to seamlessly incorporate PDF generation capabilities to generate Business Contracts into your FlutterFlow projects, enhancing your application’s functionality and user experience.

Read More »
blog

How to Overlay Text on an Image in HTML and CSS

CraftMyPDF’s Image Generation API: Now, if coding isn’t really your thing or you just want a quicker solution, CraftMyPDF has got you covered. Their API is designed to make the process of generating images with text overlays a breeze.

Read More »
blog

Generate PDFs in C# with 8 Libraries (2024 Updated)

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 documents with 4 Popular PHP Libraries (Updated 2024)

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 »
Copyright ©2024 CraftMyPDF.com

Email us at [email protected] for support