javascript

How to convert HTML text to PDF in JavaScript


In this article, you will learn about how to convert HTML text to PDF by using JavaScript.
Converting an HTML file into PDF is a very useful thing to do and you may save a bulk amount of data into a pdf file easily.

In JavaScript, you may convert your HTML file into PDF and to do so JavaScript comes with an amazing library named jsPDF. With the help of this library, you may convert your HTML text into pdf.

Let’s see the below code example step by step to doing this. Here, for example, we will convert an h1 text with some dummy data you may convert the bulk amount of data.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML To PDF</title>
</head>
<body>
    <div id="data">
        <h1>This is a demo of converting HTML to PDF</h1>
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ipsum saepe, nihil ipsa ab rem, natus atque odio vero ea voluptatum vitae repellendus eligendi commodi eius officiis eaque molestias sint! Et?</p>
     </div>
     
 <a href="javascript:htmlToPdf()">Download File As PDF</a>
 <script src="<https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js>" ></script>
 <script src="app.js"></script>
</body>
</html>

Here, we took simple text for converting and linking the jspdf library form cdn along with our own app,js file. You may download it from the site to your local machine and use it but to make things simple we are using the online version of it. Let’s see the JavaScript code below:

JavaScript

function htmlToPdf() {
    var doc = new jsPDF();
     doc.fromHTML(document.getElementById("data"), 
     15,
     15, 
     {'width': 170},
     function() 
      {
       doc.save("PDF_Documet.pdf");
     });
   }

Here, we have added the functionality of converting HTML data into pdf format and also define our file name as PDF_document while downloading the file. Let’s see the output below:

Output

You can see that a link has been generated and when we click on that link it will download a pdf file for us with the specific name that we have provided. Let’s open that file and see what happens in the below:

You can see that our HTML text is converted nicely into pdf along with the specific file name that we have provided.

This is how you can convert HTML text into PDF by using JavaScript. This article may give you a basic idea of these things but you may do a lot more things and to do so you need to visit the official website of jsPDF and try to implement things based on your necessary.


Share on social media

//