Convert a webpage into PDF
Hello friends, many times while reading for a test, we’ve poor Internet connection. For such reasons, we make sure to save the webpage as a PDF. In this tutorial, I will tell you how to convert a webpage into PDF.
Convert a webpage into a PDF
In this tutorial, I will cover two things :
- How to convert an HTML code into a PDF
- How to convert a webpage into a PDF via its URL
Before starting, open your command prompt for Windows or Terminal for macOS/ Linux. Run the following command.
pip install pyhtml2pdf
How to convert an HTML code into PDF
I have imported two dependencies into my code: os and pyhtml2pdf. I’ve specifically imported the converter module for my usage. Now I need to get the URL of the webpage that I want to convert. However, I want to convert an HTML code. At first, I took the absolute path for my HTML file, sample.html
using the os.path.abspath()
function. Now I use the convert function of the converter module which takes the URL of the webpage and pdf file’s name as arguments.
Code :
import os from pyhtml2pdf import converter path = os.path.abspath('sample.html') converter.convert(f'file:///{path}', 'sample1.pdf')
Here, I have formatted the URL for my webpage and provided the pdf file’s name as sample1.pdf
.
Input :
<!DOCTYPE html> <Html> <Head> <title>CodeSpeedy </title> </Head> <Body> <h2>This is CodeSpeedy Technologies Pvt Ltd.</h2> <p> We are software development & app development company. </p> <p>We can turn your idea into digital reality.</p> <p>We provide digital and tech solutions for businesses. Our team is always committed to fulfill your requirements.</p> <p>Turns your idea into digital reality.</p> </p> </Body> </Html>
How to convert a webpage into a PDF via its URL
I’ve imported pyhtml2pdf’s converter
module. As mentioned before convert function of the converter module takes two parameters as input. First is the URL of the webpage and the other is the name of the PDF file.
Code :
from pyhtml2pdf import converter converter.convert('https://pypi.org', 'sample.pdf')
Now you can convert any webpage to a PDF file.
Leave a Reply