- Code to Print and Save HTML Page as PDF using JavaScript
- Code to Print and Save HTML Page as PDF
- Tutorial to print HTML page
- What’s Next?
- doctor Brain
- Новые публикации
- JavaScript: сохраняем страницу в pdf
- HTML: Полезные примеры
- CSS: Ускоряем загрузку страницы
- JavaScript: 5 странностей
- JavaScript: конструктор сортировщиков
- Категории
- О нас
- HTML to PDF Button
- Webpage to PDF Button
- Additional Options
- Newsletter
- Download HTML Page as PDF Using JavaScript
- Steps to Download HTML Page as PDF Using JavaScript
- Include jQuery and jsPDF Library
- How to create a PDF from any HTML page or form using only JavaScript
- Install jsPDF
- Customize HTML to PDF conversion
- Customize PDF orientation
- Convert HTML form to PDF
Code to Print and Save HTML Page as PDF using JavaScript
Being a web developer, many times you need to allow the user to print or save HTML page as PDF.
Suppose you have a web form on your website and the user has to submit the data. After submitting the form, you can allow the user to print or save the HTML page as a PDF with all the user data. A user can use this data for future reference.
Another example. If you have a tutorial on your website, you can allow a user to print the tutorial so that the user can use it offline.
A simple solution to allow the user to print or save the HTML page as PDF will be very helpful. You don’t need any external tool to convert HTML to PDF.
Code to Print and Save HTML Page as PDF
Hope you are familiar with basic HTML tags. Call the Javascript function inside the HTML to print and save the webpage as PDF.
Tutorial to print HTML page
Click the button to print this page.
function printFunction()
- The window.print() is the inbuilt function to print the current window.
- The printFunction() is user define javascript function which you call from HTML object.
By clicking on the button, the user can save the HTML page as PDF or can download it.
The print() function supports almost all the popular web browsers like Google Chrome, Firefox, Internet Explorer, Opera, and Safari (Mac and other iOS web browsers).
What’s Next?
If you are a web developer or interested in web development, do check how the 20 best web form design practices have helped me grow professionally.
Javascript is one of the highest-paying programming languages and has very advanced programming features.
This is a simple JavaScript function to convert HTML to PDF or to print or save HTML page as PDF. You can run this code in an online HTML editor for testing.
For more of such content, stay tuned.
doctor Brain
В этой небольшой статье мы разберем вариант создания pdf-файла из данных HTML-страницы с помощью клиентской библиотеки html2pdf.js.
Для выполнения задчи нам понадобятся:
HTML-страница может содержать любой контент, который нужно сохранить в pdf-формате. Обычно это электронные билеты, счета, инвойсы и иные документы, в том числе qr-код.
После размещения необходимых данных на странице нужно подключить библиотеку html2pdf.js .
Саму библиотеку можно скачать и разместить на своем веб-сервере:
Также можно воспользоваться одним из многочисленных CDN-сервисов. Например, cdnjs:
https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.js
Следующим шагом мы создаем обертку для контента, подлежащего сохранению в формате pdf:
Конечно, еще нужна кнопка, по нажатию на которую будет генерироваться pdf-файл:
Наконец, напишем нужную нам функцию на ванильном JavaScript:
Новые публикации
JavaScript: сохраняем страницу в pdf
HTML: Полезные примеры
CSS: Ускоряем загрузку страницы
JavaScript: 5 странностей
JavaScript: конструктор сортировщиков
Категории
О нас
Frontend & Backend. Статьи, обзоры, заметки, код, уроки.
© 2021 dr.Brain .
мир глазами веб-разработчика
HTML to PDF Button
Add a «Save as PDF» to your webpages. Completely FREE!
Use our FREE HTML to PDF service to allow your visitors to download/save your web pages as PDF. No coding or signup required. All you need to do is add a simple HTML link to your web pages.
Webpage to PDF Button
Add the below line of HTML code to your website.
Important: The web page needs to be publicly accessible on the Internet. Our HTML to PDF conversion button will not work if your web page is password protected or hosted on a local development web server.
Feel free to contact us if you need any help.
Additional Options
You can add parameters to the URL to customize the generated PDF. For example:
Below is a list of all available parameters you can pass to the our HTML to PDF script:
- cache: Set this to 1 to enable caching of the generated PDF on our server. Default is 1. Set to 0 to disable caching.
- cache_for: Set this to the number of seconds you want to cache the PDF for. By default set to 86400 seconds (24 hours). Set to 0 to clear cache and generate a new PDF.
- print_media: Set this to 1 to use print media CSS. Click here for brief introduction to CSS media types.
- url: Set this to the URL of the page you want to convert to PDF. For example consider the following scenario, you want to add a HTML to PDF button on www.example.com/page-1.html but what this button to generate PDF for www.example.com/page-2.html. In this case you can set link to https://pdf-ace.com/pdfme?url=/page-2.html. Now whenever someone clicks this button, it will generate PDF for www.example.com/page-2.html.
Newsletter
Download HTML Page as PDF Using JavaScript
To store dynamic content from the web page or HTML page for future use PDF format is very helpful. This also can.
To store dynamic content from the web page or HTML page for future use PDF format is very helpful. This also can help download a big amount of data from the web application by exporting an HTML page to a PDF on the user’s click event using JavaScript functionality. Download HTML Page as PDF Using JavaScript, JavaScript has a huge amount of libraries available to generate PDF from HTML. But here we use jsPDF which is the best JavaScript library to convert and download HTML pages as PDF using JavaScript.
Here, In this tutorial, we will show you how to generate PDF from an HTML page using JavaScript and jQuery and also save an HTML page as a PDF using JavaScript with a live demo.
A video demonstration of the complete source code to download HTML page as PDF using JS is here,
Steps to Download HTML Page as PDF Using JavaScript
- Include jQuery and jsPDF library by using their CDN link.
- Create an HTML content div.
- Instantiate jsPDF class.
- Create a button-click function to generate and download PDF from HTML.
- Live Demo
Include jQuery and jsPDF Library
Here we include jQuery and jsPDF library for using jsPDF class and jQuery for button click and getting data from the div.
How to create a PDF from any HTML page or form using only JavaScript
With the jspdf library, we can easily convert any HTML page or form to a PDF:
import < jsPDF >from ‘jspdf’; const pdfContentEl = document.getElementById(‘pdf-content’); const doc = new jsPDF(); await doc.html(pdfContentEl.innerHTML).save(‘test.pdf’);
PDF is a popular file format we use to present and share documents with a fixed layout across different platforms and devices.
To start the conversion, we create a new jsPDF object with the constructor. Then we call the html() method, passing the element with the contents we want to be in the PDF. On the result, we call save() , passing our desired name of the output PDF file.
Let’s say we had HTML like this:
Here’s what we’re saving to PDF
with an output on the webpage like this:
When we click the “Save PDF” button, jsPDF will create a new PDF from the HTML element and download it as a file in the browser
Here’s what displays when we open the PDF:
Install jsPDF
To get started with the jsPDF library, we can install it from NPM with this command.
After the installation, we’ll be able to import it into a JavaScript file, like this:
For this file to work in the HTML, we can use a module bundler like Parcel, which is what I use.
With Parcel, we can include the script in the HTML like this:
We can use modern tools like TypeScript and ES module imports in the script, and it will work just fine because of Parcel.
As far as we run the HTML with npx parcel my-file.html after installing Parcel with npm install parcel .
Parcel makes the HTML available at localhost:1234 , as you might have seen in the demo above.
Customize HTML to PDF conversion
The jsPDF constructor accepts an options object that customizes the PDF conversion process.
For example, the orientation option sets the orientation of the resulting PDF.
By default, it’s portrait , but we can set it to landscape .
Customize PDF orientation
Here we specify a landscape export that is 2 by 4 inches.
Convert HTML form to PDF
jsPDF also works with HTML elements whose appearance can change dynamically from user interaction, like form inputs.
import < jsPDF >from ‘jspdf’; const doc = new jsPDF(); const savePdf = document.getElementById(‘save-pdf’); const formEl = document.getElementById(‘form’); savePdf.addEventListener(‘click’, async () => < await doc.html(formEl).save('test.pdf'); >);
In the webpage, we’ve put in some test values in the two form inputs, to see that they display in the PDF output.
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.