DIV Contents

How To Convert HTML To PDF Using jsPDF

In this article, we will see how to convert HTML to pdf using jsPDF. Here, we will learn how to convert HTML to PDF using javascript. We are using jsPDF to generate PDF in javascript. It can generate PDFs from the client side. The jsPDF is very easy to use in javascript.

It also provides multiple options for generating PDF files. You can generate PDF files with images, and multiple pages, and also support different languages like Japanese, Arabic, Russian, etc.

So, let’s see jsPDF HTML to pdf convert, jsPDF HTML to pdf multiple pages, convert HTML to pdf using javascript, HTML to pdf in javascript using jsPDF.

jsPDF provides two different methods to use.

In this step, we will create an HTML file. So, add the following code to the file.

 

How To Convert HTML To PDF Using jsPDF- Techsolutionstuff

Company Name Employee Name Country
Dell Maria Germany
Asus Francisco Mexico
Apple Roland Austria
HP Helen UK
Lenovo Yoshi Canada

Now, add the style of this HTML page.

 table < font-family: arial, sans-serif; border-collapse: collapse; width: 100%; >td < border: 1px solid #dddddd; text-align: left; padding: 8px; >th < border: 1px solid #dddddd; text-align: left; padding: 8px; background-color: #111; color:white; >tr:nth-child(odd) 

Add the following script to the HTML page for converting it to pdf.

   

You might also like:

  • Read Also: How To Add AJAX Loader In jQuery
  • Read Also: Laravel 9 Send Email With PDF Attachment
  • Read Also: How To Generate PDF Using DomPDF In Laravel 9
  • Read Also: How To Integrate Paypal Payment Gateway In Laravel 8
Читайте также:  Не удается включить javascript

Источник

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

Источник

Easy way to convert HTML to PDF using Javascript

In previous article, we have explained about how to convert html to word using javascript or how to read pdf using Javascript or to read excel using Javascript, but in this article we will read about how to convert html into pdf using Javascript or JS easily with jsPDF library or without using any javascript library, we will see each method, one by one.

Convert HTML to PDF using jsPDF

Let’s consider example, for html to pdf using jsPDF library first, as it is much easier, so in this example, we will use jsPDF, you can download it from https://github.com/MrRio/jsPDF or you can also use cdn link ‘ https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js ‘

Once we have have downloaded jsPDF, just create it’s object » var doc = new jsPDF() » and then directly export HTML to PDF as shown below

function generatePDF() < var doc = new jsPDF(); //create jsPDF object doc.fromHTML(document.getElementById("test"), // page element which you want to print as PDF 15, 15, < 'width': 170 //set width >, function(a) < doc.save("HTML2PDF.pdf"); // save file name as HTML2PDF.pdf >); >

Let’s consider checking complete example, here is the HTML

     
This is p one

More Text to be printed on PDF

Dowload PDF

If you want to include image in HTML to PDF conversion using Javascript in jsPDF, you can include base64 code of the image, so here is the complete fiddle example, which includes image also in conversion.

More configuration using jsPDF

If you want to remove a part of PDF from complete page you can mention it in specialElementHandler function, here is the more explanation of configuration using jsPDF in comments with example

 var pdf = new jsPDF('p', 'pt', 'letter'); //letter = letter size pdf // source can be HTML-formatted string, or a reference // to an actual DOM element from which the text will be scraped. source = $('#content')[0]; // we support special element handlers. Register them with jQuery-style // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) // There is no support for any other type of selectors // (class, of compound) at this time. specialElementHandlers = < // element with id of "bypass" - jQuery style selector '#bypassme': function (element, renderer) < // true = "handled elsewhere, bypass text extraction" return true >>; margins = < top: 80, bottom: 60, left: 40, width: 522 >; // all coords and widths are in jsPDF instance's declared units // 'inches' in this case pdf.fromHTML( source, // HTML string or DOM elem ref. margins.left, // x coord margins.top, // y coord < 'width': margins.width, // max width of content on PDF 'elementHandlers': specialElementHandlers >, function (dispose) < // dispose: object with X, Y of the last line add to the PDF // this allow the insertion of new lines after html pdf.save('Filename.pdf'); >, margins );

Converting images to base64 using html2canvas

If you don’t have base64 image code, then you can convert html to pdf with images using HTML2Canvas with jsPDF.

HTML2Canvas will convert your images into base64 code and then it will help you print pdf more easily.

Here is the fiddle demo for it

HTML to PDF without using any Javascript library

In the above example, we were using jsPDF library, but now we will convert it using simple Javascript code, although this code doesn’t directly converts HTML to PDF, but it will open dialog to print or save HTML as PDF, here is the sample code

     

You can take a look at fiddle sample here

Fiddle example may ask you to allow pop-up.

Источник

Оцените статью