Welcome folks today in this blog post we will be converting html to pdf document with css styles included using wkhtmltopdf library in command line. All the full source code of the application is shown below
Get Started
In order to get started you need to install the below libraries or packages as shown below
pip install pdfkit
For this you need to install the wkhtmltopdf library executable inside your windows machine.
Usage
Now to use this module guys just create an app.py
file and copy paste the below code
1 2 3 4 5 |
import pdfkit pdfkit.from_url('http://google.com', 'out.pdf') pdfkit.from_file('test.html', 'out.pdf') pdfkit.from_string('Hello!', 'out.pdf') |
And inside this block of code we are importing the pdfkit library. We are using three methods of pdfkit which are as follows
from_url() —> Basically this method is used to take screenshot of website and export it to pdf document
from_file() —> Basically in this method we are converting the local html5 template with css styles to pdf document
from_string()—> Basically in this method we are converting the custom html to pdf document
Now if you execute the app.py filei inside the terminal you will see the below screenshot
Passing Multiple Files & URL’s to Convert to PDF Document
We can even pass multiple files and url’s to this very same function to convert it to pdf document. As you can see in the below section of code
1 2 |
pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf') pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf') |
As you can see we are using the []
operator to set the multiple urls’ and file names. Lastly we are exporting the multiple files to pdf document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'custom-header': [ ('Accept-Encoding', 'gzip') ], 'cookie': [ ('cookie-empty-value', '""') ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'no-outline': None } pdfkit.from_url('http://google.com', 'out.pdf', options=options) |
And now we are also passing the options to this from_url() method we will converting the url of the website to pdf document