Converting HTML documents or Web Pages to PDF Documents can be a very useful feature for your application. For example your software is about billing, and you are generating invoices or other reports using html, then you might give an option to get the documents as PDFs as well. So in this post I will tell you about converting your HTML Documents to PDF Document.
I will be using the basics of Python here, but once you are familiar with the concept, you can apply it to everywhere.
Python HTML to PDF
For this post, I will be using a paid tool that is called DocRaptor. If you are using DocRaptor then converting HTML to PDF is very easy. And not just PDFs this tool supports other file formats as well.
Now let’s quickly see how we can convert a Web URL to HTML file using DocRaptor.
Installing DocRaptor
First we need to install the DocRaptor. And it is very easy you just need to run the following command.
1 2 3 |
pip install --upgrade docraptor |
Once you have installed it using pip you can easily convert your webpages or html code to pdf files.
Converting HTML to PDF
Here is a sample code that will convert a given Web Page URL to a PDF Document. You can also pass HTML code directly to get the PDF Document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import docraptor import shutil doc_api = docraptor.DocApi() doc_api.api_client.configuration.username = 'doc raptor api key' # doc_api.api_client.configuration.debug = True try: create_response = doc_api.create_hosted_doc({ "test": True, "document_url": "https://www.simplifiedpython.net/scrapy-python-tutorial/", "name": "docraptor-python.pdf", }) print(create_response.download_url) except docraptor.rest.ApiException as error: print(error.status) print(error.reason) |
On running the above code snippet, you will get the URL to the PDF File generated.
So that is all for this post, let me know in comments below if you need any additional help. Thank You.