- doctor Brain
- Новые публикации
- JavaScript: сохраняем страницу в pdf
- HTML: Полезные примеры
- CSS: Ускоряем загрузку страницы
- JavaScript: 5 странностей
- JavaScript: конструктор сортировщиков
- Категории
- О нас
- Convert HTML to PDF using JavaScript
- Include jsPDF Library
- Load and Initiate jsPDF Class
- Generate PDF using JavaScript
- Convert HTML Content to PDF using JavaScript
- Useful Configurations
- Convert HTML Content to PDF with Images and Multiple Pages
- Conclusion
- How to trigger the direct download of a PDF with JavaScript
- Note
- Requirements
- Download directly PDF from URL
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 .
мир глазами веб-разработчика
Convert HTML to PDF using JavaScript
PDF file format is very useful to download bulk data in the web application. It helps the user to download dynamic content in file format for offline use. With export to PDF functionality, the HTML content is converted to a PDF document and downloaded as a PDF file. In the dynamic web application, a server-side script is used to convert HTML to PDF and generate PDF file using PHP.
If you want a client-side solution to generate PDF document, JavaScript is the easiest way to convert HTML to PDF. There are various JavaScript library is available to generate PDF from HTML. The jsPDF is one of the best library to convert HTML to PDF using JavaScript. In this tutorial, we will show you how to generate PDF document and convert HTML to PDF using JavaScript and jsPDF library.
In this example script, we will share code snippets to handle PDF creation and HTML to PDF conversion related operations using JavaScript.
Include jsPDF Library
The jQuery library is not required, just include the jsPDF library file to use the jsPDF class.
script src="js/jsPDF/dist/jspdf.umd.js"> script>
Note that: You don’t need to download the jsPDF library separately, all the required files are included in our source code package.
Load and Initiate jsPDF Class
Use the following line of code to initiate the jsPDF class and use the jsPDF object in JavaScript.
window.jsPDF = window.jspdf.jsPDF; var doc = new jsPDF();
Generate PDF using JavaScript
The following example shows how to use the jsPDF library to generate PDF file using JavaScript.
- Specify the content in text() method of jsPDF object.
- Use the addPage() method to add new page to PDF.
- Use the save() method to generate and download PDF file.
var doc = new jsPDF(); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript to generate a PDF.'); // Add new page doc.addPage(); doc.text(20, 20, 'Visit CodexWorld.com'); // Save the PDF doc.save('document.pdf');
Use the addImage() method to add image to PDF using jsPDF object.
doc.addImage("path/to/image.jpg", "JPEG", 15, 40, 180, 180);
Convert HTML Content to PDF using JavaScript
The following example shows how to use the jsPDF library to convert HTML to PDF and generate PDF file from HTML content using JavaScript.
- Retrieve the HTML content from the specific element by ID or class.
- Convert HTML content of the specific part of the web page and generate PDF.
- Save and download the HTML content as a PDF file.
window.jsPDF = window.jspdf.jsPDF; var doc = new jsPDF(); // Source HTMLElement or a string containing HTML. var elementHTML = document.querySelector("#contnet"); doc.html(elementHTML, < callback: function(doc) < // Save the PDF doc.save('sample-document.pdf'); >, x: 15, y: 15, width: 170, //target width in the PDF document windowWidth: 650 //window width in CSS pixels >);
Useful Configurations
The jsPDF library provides various methods and options to configure the PDF creation. Some of the useful methods of jsPDF class are given below that are commonly used to export HTML to PDF using jQuery.
Change Paper Orientation:
Use the orientation option to set the paper orientation of the PDF.
var doc = new jsPDF(< orientation: 'landscape' >); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript to generate a PDF.'); // Add new page doc.addPage(); doc.text(20, 20, 'Visit CodexWorld.com'); // Save the PDF doc.save('document.pdf');
Change Text Font:
Use setFont() method to set text font faces, text alignment and rotation in the PDF.
var doc = new jsPDF(); doc.text(20, 20, 'This is the default font.'); doc.setFont("courier", "normal"); doc.text("This is courier normal.", 20, 30); doc.setFont("times", "italic"); doc.text("This is times italic.", 20, 40); doc.setFont("helvetica", "bold"); doc.text("This is helvetica bold.", 20, 50); doc.setFont("courier", "bolditalic"); doc.text("This is courier bolditalic.", 20, 60); doc.setFont("times", "normal"); doc.text("This is centred text.", 105, 80, null, null, "center"); doc.text("And a little bit more underneath it.", 105, 90, null, null, "center"); doc.text("This is right aligned text", 200, 100, null, null, "right"); doc.text("And some more", 200, 110, null, null, "right"); doc.text("Back to left", 20, 120); doc.text("10 degrees rotated", 20, 140, null, 10); doc.text("-10 degrees rotated", 20, 160, null, -10); // Save the PDF doc.save('document.pdf');
Convert HTML Content to PDF with Images and Multiple Pages
In this example code snippet, we will show how to use the jsPDF library to convert HTML to PDF and generate PDF file from HTML content including images using JavaScript.
- The absolute or relative file paths can be used in the image src.
- The html2canvas library is required to convert HTML content (with images) to PDF document.
- The autoPaging option helps to break PDF document in multiple pages automatically.
window.jsPDF = window.jspdf.jsPDF; // Convert HTML content to PDF function Convert_HTML_To_PDF( ) < var doc = new jsPDF(); // Source HTMLElement or a string containing HTML. var elementHTML = document.querySelector("#contentToPrint"); doc.html(elementHTML, < callback: function(doc) < // Save the PDF doc.save('document-html.pdf'); >, margin: [10, 10, 10, 10], autoPaging: 'text', x: 0, y: 0, width: 190, //target width in the PDF document windowWidth: 675 //window width in CSS pixels >); >
html lang="en"> head> script src="js/html2canvas.min.js"> script> script src="js/jsPDF/dist/jspdf.umd.js"> script> script> /* Place custom JavaScript code here */ script> head> body> button onclick="Convert_HTML_To_PDF();">Convert HTML to PDF button> div id="contentToPrint"> h1>What is Lorem Ipsum? h1> p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. p> img src="path/to/image.jpg"> img src="path/to/image_2.jpeg"> div> body> html>
Conclusion
Our example code helps you to convert HTML to PDF and generate PDF file using JavaScript. You can easily add the Export to PDF functionality on the web page without depending on the server-side script. The PDF creation functionality can be enhanced with jsPDF configuration options as per your needs. Download our source code package to get all the required files including the jsPDF JavaScript library.
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question
How to trigger the direct download of a PDF with JavaScript
In most of the web applications today, the user doesn’t use an outdated browser, due to the basic requirements and features that the web app offers. This is a great advantage when we talk about the technical side, as you have many new APIs available. One of the advantages, is the availability of Blobs and the FileReader, that correctly worked can be used to download files directly from JavaScript without redirecting the user to a new website.
In this article, we’ll explain you how to download directly a PDF from a web URL in the browser easily.
Note
For the examples we are going to use a PDF hosted in the Mozilla Github IO website, that is absolutely free and has CORS headers, so it can be used everywhere to test.
Requirements
You will need the FileSaver library to achieve your goal. This library has support with UMD (Universal Module Definition) so you can use it in the browser and access it from the window or you can require it as a module with any bundler.
If you use NPM, you can install it in your project using:
npm install file-saver --save
And then you can just require the module as:
var FileSaver = require('file-saver'); var blob = new Blob(["Hello, world!"], ); FileSaver.saveAs(blob, "hello world.txt");
Alternatively, you can download a copy of the minified script and add in your HTML document with a script tag:
var blob = new Blob(["Hello, world!"], ); saveAs(blob, "hello world.txt");
Visit the official repository at Github for more information about this library.
Download directly PDF from URL
Thanks to FileSaver.js you will be able to save the data of a file in JavaScript as a download in your browser easily. FileSaver.js implements the saveAs FileSaver interface in browsers that do not natively support it. FileSaver.js is the solution to saving files on the client-side, and is perfect for webapps that need to generate files, or for saving sensitive information that shouldn’t be sent to an external server.
In this case, if you want to do it from a PDF that is available on the server, but for some reason you don’t want to open a new window for it, so the user won’t need to do right click, save PDF as etc, you can use easily this library to achieve it. In the following example, we are downloading a PDF from a simple URL, according to the architecture of your application, the PDF may be available only under certain conditions on the server to finally be served and processed internally by JavaScript:
var oReq = new XMLHttpRequest(); // The Endpoint of your server var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf"; // Configure XMLHttpRequest oReq.open("GET", URLToPDF, true); // Important to use the blob response type oReq.responseType = "blob"; // When the file request finishes // Is up to you, the configuration for error events etc. oReq.onload = function() < // Once the file is downloaded, open a new window with the PDF // Remember to allow the POP-UPS in your browser var file = new Blob([oReq.response], < type: 'application/pdf' >); // Generate file download directly in the browser ! saveAs(file, "mypdffilename.pdf"); >; oReq.send();
Once the download of the file finishes, the save process starts automatically. Note that if the browser doesn’t support the Blob API, you can add a polify to solve this inconvenient.