How to Generate PDF using PDFKit with Python?

By Hardik Savani October 30, 2023 Category : Python

Hi Dev,

This article will give you an example of python pdfkit create pdf file. let us discuss about python pdfkit generate pdf file. I would like to share with you how to create pdf file using pdfkit in python. If you have a question about how to create pdf files in python using pdfkit then I will give a simple example with a solution.

In this example, I will show you how to create pdf file in python using pdfkit, we will use pdfkit and wkhtmltopdf to generate pdf file in python. So, without further ado, let's follow simple steps with python3 (Python 3) version.

Step 1: Install PDFKit Library

In this step, we need to install pdfkit library by the following the command:

pip3 install pdfkit

Step 2: Install wkhtmltopdf Software

In this step, we need to install wkhtmltopdf software to your system, so let's use following way for your system.

For Ubuntu User:

sudo apt-get update
sudo apt-get install wkhtmltopdf

For Windows User:

Download wkhtmltopdf Exe File

Step 3: Create HTML File

Here, we will create sample.html file with some dummy date. let's copy below code and create file in root directory:


<!DOCTYPE html>
<html lang="en">
        <meta charset="UTF-8">
        <h1>Welcome to!</h1>
        <p>This is a sample HTML file.</p>

Step 4: Create Python File

Here, we will create python file and write code to generate pdf file. i will give you two example code one for ubuntu user and another for windows user. so let's see the bellow code: (For Ubuntu Users)

import pdfkit
# Generate PDF File Code
pdfkit.from_file('sample.html', 'out.pdf') (For Windows Users)

import pdfkit
# Define Path of wkhtmltopdf.exe
pathToWkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
# Point pdfkit configuration to wkhtmltopdf.exe
config = pdfkit.configuration(wkhtmltopdf=pathToWkhtmltopdf)
# Convert HTML file to PDF File
pdfkit.from_file('sample.html', 'sample.pdf', configuration=config)

Run Python App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:



I hope it can help you...

Tags :