Python Convert Html to PDF

Convert HTML/webpage to PDF

There are many websites that do not allow to download the content in form of pdf, they either ask to buy their premium version or don’t have such download service in form of pdf.

Conversion in 3 Steps from Webpage/HTML to PDF

Step1: Download library pdfkit

 $ pip install pdfkit

Step2: Download wkhtmltopdf
For Ubuntu/Debian:



 sudo apt-get install wkhtmltopdf

For Windows:
(a)Download link: WKHTMLTOPDF
(b)Set: PATH variable set binary folder in Environment variables.

Step3: Code in Python to Download:
(i) Already Saved HTML page

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


(ii) Convert by website URL

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


(iii) Store text in PDF

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Congratulations: Your pdf file would be created and saved in the same directory where python file exists.

Miscellaneous Knowledge Content:
1. You can pass a list with multiple URLs or files:

filter_none

edit
close

play_arrow

link
brightness_4
code

pdfkit.from_url(['google.com', 'geeksforgeeks.org', 'facebook.com'], 'shaurya.pdf')
pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')

chevron_right


2. Save content in a variable

filter_none

edit
close

play_arrow

link
brightness_4
code

# Use False instead of output path to save pdf to a variable
pdf = pdfkit.from_url('http://google.com', False)

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.