How to Convert HTML to pdf in Python

  2932 views   8 months ago Python

Hello guys,

In this article, we will use pdfkit package to create PDF package. pdfkit is wrapper for wkhtmltopdf utility. wkhtmltopdf is open-source command line tools to convert HTML to PDF file.

First of all, install pdfkit package using pip command.

pip install pdfkit

We will also need to install wkhtmltopdf 

sudo apt-get install wkhtmltopdf

After installation, create a python file and input the below code. This will create PDF file from any website URL.

import pdfkit

pdfkit.from_url('https://laravelcode.com/', 'laravelcode.pdf')

If you have already saved HTML file, use from_file() method.

import pdfkit

pdfkit.from_file('index.html', 'homepage.pdf')

Save PDF file from text.

import pdfkit

pdfkit.from_string('Hello World!', 'world.pdf')

If you want to process PDF file using variable, pass the second argument as False.

import pdfkit

pdf = pdfkit.from_url('https://laravelcode.com/', False)

You can also modify margin, page size etc, before creating PDF file. Pass third parameter as dictionary with valid options. Here[http://wkhtmltopdf.org/usage/wkhtmltopdf.txt] you can find all option and pass in the PDF file.

import pdfkit

options = {
    'page-size': 'A4',
    'margin-top': '0.50in',
    'margin-right': '0.50in',
    'margin-bottom': '0.50in',
    'margin-left': '0.50in',
    'encoding': "UTF-8",
    'no-outline': None
}

pdfkit.from_url('https://laravelcode.com/', 'laravelcode.pdf', options=options)

This way, you can create PDF file form website page or local file. I hope you will like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]