
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert HTML to PDF using Python
In general, we look at some external websites to convert our files to PDF format; instead, we can convert them using Python on our own.
In this article, we will understand the steps to convert the HTML (Hyper Text Markup Language) to PDF using Python code.
Steps to convert HTML to PDF
Following are the steps to convert the HTML file to PDF using Python:
Step 1: Installation
Download the pdfkit library by running the following command in the command prompt:
pip install pdfkit
Step 2: Download wkhtmltopdf
Following are the steps to download wkhtmltopdf:
- Download wkhtmltopdf using the link.
- The path location should be C:\Program Files\wkhtmltopdf\bin .
- Next, add the path to the environmental variables by selecting Path.
- Select Edit and New, add C:\Program Files\wkhtmltopdf\bin, and click on OK
- Now open the command to check the version using wkhtmltopdf --version
Step 3: Code to convert the HTML file to PDF
Following is the code to convert the HTML file to PDF:
#convert.py import pdfkit # Configure the path to wkhtmltopdf config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe') # Convert a local HTML file to PDF pdfkit.from_file('example.html', 'convertedfile.pdf', configuration=config)
Save the above code with a convert1.py extension. Make sure that the HTML file that we would like to convert to PDF is in the same location. Now open the command prompt and run convert1.py; the converted PDF will be in the same folder.
In the following image, you find that the example.html file is saved as convertedfile.pdf in the same folder.