Often you may need to convert webpage to PDF in Linux. This is required especially if you want to add an ‘export to pdf’ functionality to your application or website. In this article, we will learn how to convert webpage to PDF in Linux. You can use these steps in almost every Linux distribution.
How to Convert Webpage to PDF in Linux
We will look at two use cases. First, we will look at how to convert web page to PDF via web browser. This is useful if you want to convert HTML to PDF on an ad-hoc basis. Second, we will look at how to convert web page to PDF via terminal, using wkhtmltopdf utility. This is useful if you want to add an ‘export to PDF’ functionality.
1. Convert HTML to PDF via web browser
You can use the following steps with almost every web browser. Open the web page that you want to convert in your web browser. We have used Google Chrome for our example.
- Go to the browser settings menu (3 vertical dots) on top right corner, below close(X) button.
- Select Print option from dropdown. You can also enter Ctrl+P shortcut.
- Among the dropdown listing printers (known as Destination in some browsers), select ‘Save as PDF’ and click Save button.
Please note, it will convert the entire page to PDF.
2. Convert Web Page to PDF via terminal
There are plenty of utilities to convert web page to pdf via terminal. We will use wkhtmltopdf for our purpose.
Here is the command to install it on your system.
In this case, wkhtmltopdf is available in official repositories. So you can easily install it on your system.
$ sudo apt install wkhtmltopdf
In this case, you need to download the rpm file from its Github repository and install it. Replace 0.12.6.1 with the version you want to install.
# sudo yum -y install wget # wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox-0.12.6-1.centos8.x86_64.rpm # sudo dnf localinstall wkhtmltox-0.12.6-1.centos8.x86_64.rpm
Once you have installed wkhtmltopdf, you can easily convert web page to PDF with the following command.
$ wkhtmltopdf URL/domain filename.pdf
Here is an example to convert Google home page to pdf.
$ wkhtmltopdf google.com google.pdf
wkhtmltopdf offers many useful features. If you want to take 2 copies of your webpage use –copies option
$ wkhtmltopdf --copies 2 google.com google.pdf
If you want to exclude images, use –no-images.
$ wkhtmltopdf --no-images google.com google.pdf
Please note, wkhtmltopdf will not convert pages with iframes properly.
Nevertless, you can always embed this code in your application/website and add an ‘export as PDF’ feature.
In this article, we have learnt how to convert HTML to PDF. There are also many online tools like www.html2pdf.com to convert web pages to PDF documents.