Export HTML Page to PDF on User Click Using JavaScript

Export HTML Page to PDF on User Click Using JavaScript
Project: Save HTML page to PDF document via Javascript
Author: Pritam Mullick
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to export HTML page to PDF on user click. It utilizes jQuery and jsPDF to convert the content of a specific HTML element to a downloadable PDF. When the user clicks the “Export to PDF” button, the code extracts the content from the ‘content’ div, converts it into a PDF document, and triggers the download process.

If you are developing web applications that display dynamic content, reports, or documents, you can use this code to allow users to download the displayed content as a PDF.

How to Export HTML Page to PDF on User Click Using JavaScript

1. To enable PDF download, start by creating a div with id “content” and insert the desired HTML content. Add an empty div with id “page.” Then, include a button with id “submit” to initiate the download.

<div id="content"> 
  <!-- Your HTML Content Goes Here -->
</div>
<div id="page"></div> 
<button id="submit">Export to  PDF</button>

2. To style your HTML content differently for the web browser and the PDF file, you can use CSS media queries. By utilizing @media screen for the web browser and @media print for the PDF file, you can apply specific styles for each medium.

@media screen {
         p {color: blue;}
 }
@media print {
         p {color: black;}
      }

3. Now, load the jQuery and jsPDF by adding the following CDN links before closing the <body> tag:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js'></script>

4. Finally, add the following JavaScript function between the <script> tag to initialize the jsPDF.

var doc = new jsPDF(); 
var specialElementHandlers = { 
    '#editor': function (element, renderer) { 
        return true; 
    } 
};
$('#submit').click(function () { 
    doc.fromHTML($('#content').html(), 15, 15, { 
        'width': 190, 
            'elementHandlers': specialElementHandlers 
    }); 
    doc.save('sample-page.pdf'); 
});

That’s it! hopefully, you have successfully created a feature to export HTML pages to PDF. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply