Check this working code.

You can check code on fiddle also.

<!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>
        <script type="text/javascript">
            var testDivElement = document.getElementById('someHtml');

            function savePDF() {
                var imgData;
                html2canvas($("#someHtml"), {
                    useCORS: true,
                    onrendered: function (canvas) {
                        imgData = canvas.toDataURL(
                           'image/png');
                        var doc = new jsPDF('p', 'pt', 'a4');
                        doc.addImage(imgData, 'PNG', 10, 10);
                        doc.save('sample-file.pdf');
                        window.open(imgData);
                    }
                });
            }


        </script>
        <style>
            .handsomeHtml {
                background: red;
            }

            .crazyFrog {
                background: url('http://e-cdn-images.deezer.com/images/artist/01eb92fc47bb8fb09adea9f763bb1c50/500x500.jpg');
                width: 500px;
                height: 500px;
            }
        </style>
    </head>
    <body>
        <div id="someHtml" class="handsomeHtml">
            Hello, handsome HTML
      <br />
            <img class="crazyFrog"></img>
        </div>
        <br />
        <button id="savePDFbutton" onclick="savePDF()">
            save pdf
        </button>
    </body>
    </html>
Answer from Vindhyachal Kumar on Stack Overflow
🌐
Pdfnoodle
pdfnoodle.com › blog › generating-pdfs-from-html-with-jspdf
Generating PDFs from HTML with jsPDF and javascript
January 30, 2025 - In this example, html2canvas captures the HTML element with the ID content, converts it into an image, and then jsPDF embeds that image into the PDF.
Top answer
1 of 16
325

jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:

  1. Go to https://github.com/MrRio/jsPDF and download the latest Version.
  2. Include the following Scripts in your project:
  • jspdf.js
  • jspdf.plugin.from_html.js
  • jspdf.plugin.split_text_to_size.js
  • jspdf.plugin.standard_fonts_metrics.js

If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:

<!DOCTYPE html>
<html>
  <body>
    <p id="ignorePDF">don't print this to pdf</p>
    <div>
      <p><font size="3" color="red">print this to pdf</font></p>
    </div>
  </body>
</html>

Then you use the following JavaScript code to open the created PDF in a PopUp:

var doc = new jsPDF();          
var elementHandler = {
  '#ignorePDF': function (element, renderer) {
    return true;
  }
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
    source,
    15,
    15,
    {
      'width': 180,'elementHandlers': elementHandler
    });

doc.output("dataurlnewwindow");

For me this created a nice and tidy PDF that only included the line 'print this to pdf'.

Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states:

Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.

Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:

var elementHandler = {
  '#ignoreElement': function (element, renderer) {
    return true;
  },
  '#anotherIdToBeIgnored': function (element, renderer) {
    return true;
  }
};

From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit to unrestrictive for the most usecases though:

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.

One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3 etc., which was enough for my purposes. Additionally it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:

<body>
  <ul>
    <!-- This is printed as the element contains a textnode -->        
    <li>Print me!</li>
  </ul>
  <div>
    <!-- This is not printed because jsPDF doesn't deal with the value attribute -->
    <input type="text" value="Please print me, too!">
  </div>
</body>
2 of 16
94

This is the simple solution. This works for me. You can use the javascript print concept and simple save this as pdf.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("#btnPrint").live("click", function () {
            var divContents = $("#dvContainer").html();
            var printWindow = window.open('', '', 'height=400,width=800');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write('</head><body >');
            printWindow.document.write(divContents);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        });
    </script>
</head>
<body>
    <form id="form1">
    <div id="dvContainer">
        This content needs to be printed.
    </div>
    <input type="button" value="Print Div Contents" id="btnPrint" />
    </form>
</body>
</html>
🌐
Decentro
decentro.tech › blog › engineering & apis › jspdf: what is it & how to use it to generate pdf from html
JsPDF: What Is It & How To Use It To Generate PDF from HTML - Decentro
June 12, 2024 - This makes it an ideal choice for ... we will use jsPDF to download an HTML file as a PDF, images, colors & backgrounds. PS: Stay tuned for the bonus section towards the end of the blog, which touches upon a presumably difficult use case killing two birds with one stone <PDF ...
🌐
CodexWorld
codexworld.com › home › convert html to pdf using javascript
Convert HTML to PDF using JavaScript - CodexWorld
July 10, 2024 - 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 ...
🌐
MicroPyramid
micropyramid.com › blog › export-html-web-page-to-pdf-using-jspdf
Export HTML Web Page to PDF Using JsPDF | MicroPyramid
In the above example, we passed an Image HTML DOM element as a first argument of the addImage function, however it can also be a base64 encoded image string. var imgData = 'data:image/jpeg;base64,/.......base64code.....iiigAoooo//2Q=='; var ...
🌐
HackMD
hackmd.io › @n6kGXbvAST2zb6hPLZ6sNQ › HJTVYZz8n
PDF Generation using jsPDF + html2canvas - HackMD
```javascript /** define your group of elements to print */ const elementIds = ['#content-id', '#content-id2', '#content-id3']; const canvases = await Promise.all( elementIds.map(id => { const element = document.getElementById(id); return html2canvas(element as HTMLElement); } ); const pdf = new jsPDF('p', 'pt', 'a4'); canvases.forEach(canvas => { // print canvas onto pdf // check if print the canvas will exceed page height // if exceed page height, addPage(); // otherwise, addImage() with proper x, y position }); pdf.save('myPDF.pdf'); ``` ## Tips and Tricks ### Remove unwanted DOM elements from generated PDF In some cases, certain DOM elements (e.g.
🌐
Tech Solution Stuff
techsolutionstuff.com › post › how-to-convert-html-to-pdf-using-jspdf
How To Convert HTML To PDF Using jsPDF
April 21, 2024 - <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script> <script> $(document).ready(function () { var form = $('.form'), cache_width = form.width(), a4 = [595.28, 841.89]; // for a4 size paper width and height $('#generate_pdf').on('click', function () { $('body').scrollTop(0); generatePDF(); }); function generatePDF() { getCanvas().then(function (canvas) { var img = canvas.toDataURL("image/png"), doc = new jsPDF({ unit: 'px', format: 'a4' }); doc.addImage(img, 'JPEG', 20, 20); doc.save('tech-html-to-pdf.pdf'); form.width(cache_width); }); } function getCanvas() { form.width((a4[0] * 1.33333) - 80).css('max-width', 'none'); return html2canvas(form, { imageTimeout: 2000, removeContainer: true }); } }); </script>
Find elsewhere
🌐
findnerd
findnerd.com › list › view › Adding-Image-to-PDF-Using-JSPDF › 28818
How to Add Multiple Image to PDF Using JSPDF Javascript Code
You can download jspdf.js file by clicking on this link: jspdf.js . 1) addImage: addImage will write image to pdf and convert images to Base64. Following parameters are required to add an image.
🌐
Nutrient
nutrient.io › blog › sdk › how to convert html to pdf using react
Generate PDFs from HTML in React with jsPDF
May 14, 2025 - This code grabs a snapshot of your styled DOM node with html2canvas, turns that canvas into a PNG, and drops it onto an A4 page in jsPDF. Finally, it triggers a download — which is named styled.pdf by default — so users get a pixel‑perfect copy. html2canvas is pixel‑based, so vector text becomes an image. For crisp text, use server‑side rendering or a true PDF layout engine. ... Drawbacks — The PDF is an image, so text can’t be searched or selected. For vector text, fall back to doc.html().
🌐
html2pdf.js
ekoopmans.github.io › html2pdf.js
html2pdf.js | Client-side HTML-to-PDF rendering using pure JS.
Rendered as image: html2pdf.js renders all content into an image, then places that image into a PDF. This means text is not selectable or searchable, and causes large file sizes. This is currently unavoidable, however recent improvements in jsPDF mean that it may soon be possible to render ...
🌐
PDFBolt
pdfbolt.com › blog › generate-html-to-pdf-with-jspdf
Generate PDFs with jsPDF: A Complete Guide to Client-Side PDF Creation | PDFBolt
March 13, 2025 - In some cases, you may want to capture the exact look of your web page – including all the applied styles – and convert it into a PDF. By combining html2canvas with jsPDF, you can capture an HTML element as an image and then embed it into a PDF.
🌐
GitHub
github.com › parallax › jsPDF › issues › 317
Converting an image from a url to pdf · Issue #317 · parallax/jsPDF
March 7, 2014 - parallax / jsPDF Public · ... · Issue body actions · HERE IS HTML CODE: img class="imagepdf " src="www.images.com/someimage" alt="Smiley face" height="42" width="42 ·...
Published   Jul 23, 2014
🌐
Phppot
phppot.com › javascript › html-to-pdf-in-javascript-using-jspdf
HTML to PDF in Javascript using jsPDF with Example Download - Phppot
It handles JavaScript validation and file type restrictions before starting PDF generation. It contains JavaScript to import and instantiate jsPDF. It uses htmltocanvas dependency to convert uploaded HTML file content into PDF. The below image shows the file structure of this HTML to PDF generation ...
🌐
CodePen
codepen.io › REMCOOLE › pen › xxOGoKo
html to pdf using jsPDF
$('.cmd').click(function () { var pdf = new jsPDF(); var specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; var $addr = $(this).closest('.res').find('.content'); var $temp = $('.content-template'); $temp.find('h3').text($addr.find('h3').text()); pdf.fromHTML($temp.html(), 15, 15, { 'width': 170, 'elementHandlers':specialElementHandlers } ); pdf.save('sample-file.pdf'); }); !
🌐
OpenReplay
blog.openreplay.com › generating-a-pdf-from-a-div-using-the-jspdf-library
Generating a PDF from a div using the jsPDF Library
html2pdf is a JavaScript library that combines the functionality of jsPDF and html2canvas to provide a comprehensive solution for generating PDFs from HTML content. It simplifies the process of creating PDFs by handling the conversion of HTML ...
🌐
DEV Community
dev.to › jringeisen › using-jspdf-html2canvas-and-vue-to-generate-pdfs-1f8l
Using jsPDF, html2Canvas, and Vue to generate PDF's. - DEV Community
October 29, 2021 - Now, once you've created your jsPDF object you'll need to use html2canvas to create an image which can then be converted to a pdf, like so: