Python Convert HTML to PDF

html to pdf | Python Methods and Functions




Convert HTML / Web Page to PDF

There are many sites that do not allow pdf downloads, either ask to buy their premium version, or do not have such a pdf download service.

Converting in 3 steps from a webpage / HTML to PDF

Step 1: Download pdfkit library

 $ pip install pdfkit 

 Step 2: Download wkhtmltopdf
For Ubuntu / Debian:

 sudo apt-get install wkhtmltopdf 

For Windows:
(a) Link for downloads: ​​WKHTMLTOPDF
(b) Set : PATH variable sets the binary folder in environment variables. 

Step 3: Python code to download:
(i) Already saved HTML page

import pdfkit

pdfkit.from_file ( 'test.html' , 'out.pdf' )

(ii) Convert by website URL

(iii) Store text in PDF format

import pdfkit

pdfkit.from_url ( ' https://www.google.co.in/ ' , < / code> 'shaurya.pdf' )

import pdfkit

pdfkit.from_string ( 'Shaurya GFG' , 'GfG.pdf' )

Congratulations : Your PDF file will be created and saved in the same directory where it exists Python file.

Miscellaneous knowledge content:
1. You can pass a list with multiple URLs or files:

pdfkit. from_url ([ 'google.com' , 'python.engineering' , ' facebook.com' ], 'shaurya.pdf' )

pdfkit.from_file ([ 'file1.html' , ' file2.html' ], 'out.pdf' )

2. Store content in variable

# Use False instead of the output path to save the pdf to a variable

pdf = pdfkit.from_url ( ' http://google.com ' , False )





Python Convert HTML to PDF: StackOverflow Questions

Render HTML to PDF in Django site

Question by crib

For my django powered site, I am looking for an easy solution to convert dynamic html pages to pdf.

Pages include HTML and charts from Google visualization API (which is javascript based, yet including those graphs is a must).

Tutorials