🌐
CodePen
codepen.io › amkid › pen › qKYwXo
jsPDF from html
function getPDF() { var doc = new jsPDF(); // We'll make our own renderer to skip this editor var specialElementHandlers = { '#getPDF': function(element, renderer){ return true; }, '.controls': function(element, renderer){ return true; } }; // All units are in the set measurement for the document // This can be changed to "pt" (points), "mm" (Default), "cm", "in" doc.fromHTML($('.zima').get(0), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('Generated.pdf'); }
🌐
jsPDF
artskydj.github.io › jsPDF › docs › jsPDF.html
jsPDF - Documentation
jsPDF.API.mymethod = function(){ // 'this' will be ref to internal API object. see jsPDF source // , so you can refer to built-in methods like so: // this.line(....) // this.text(....) } var pdfdoc = new jsPDF() pdfdoc.mymethod() // <- !!!!!!
🌐
Phppot
phppot.com › javascript › html-to-pdf-in-javascript-using-jspdf
HTML to PDF in Javascript using jsPDF with Example Download - Phppot
Example of JavaScript PDF creation on the client-side using jsPDF JavaScript library by reading and supplying the HTML file content.
🌐
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 - Now comes the star of the show, jsPDF part First, Set up jsPDF To use jsPDF, you need to include the library in your HTML file. You can either download the library and include it locally, or you can include it directly from a CDN.
🌐
MicroPyramid
micropyramid.com › blog › export-html-web-page-to-pdf-using-jspdf
Export HTML Web Page to PDF Using JsPDF | MicroPyramid
var doc = new jsPDF(); // We'll make our own renderer to skip this editor var specialElementHandlers = { '#editor': function(element, renderer){ return true; } }; // All units are in the set measurement for the document // This can be changed to "pt" (points), "mm" (Default), "cm", "in" doc.fromHTML($('body').get(0), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); We can also add Metadata to our Generating pdf: var doc = new jsPDF(); doc.text(20, 20, 'This PDF has a title, subject, author, keywords and a creator.'); // Optional - set properties on the document doc.setProp
🌐
findnerd
findnerd.com › list › view › Create-PDF-from-HTML-using-JSPDF › 28991
Create PDF from HTML using JSPDF
February 14, 2017 - Hello friends, welcome to findnerd. today i am going to tell you how to create pdf from html using jspdf. in this blog i am going to use fromhtml plugin to convert html page into pdf. copy and paste the following code into your file:<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head> <title>fromhtml ex</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="generator" content="geany 1.22" /> <link id="bootstrap-css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis
🌐
jsPDF
artskydj.github.io › jsPDF › docs › module-html.html
html - Documentation
var doc = new jsPDF(); doc.html(document.body, { callback: function (doc) { doc.save(); } });
Top answer
1 of 7
154

you can use pdf from html as follows,

Step 1: Add the following script to the header

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

or download locally

Step 2: Add HTML script to execute jsPDF code

Customize this to pass the identifier or just change #content to be the identifier you need.

 <script>
    function demoFromHTML() {
        var pdf = new jsPDF('p', 'pt', 'letter');
        // 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('Test.pdf');
            }, margins
        );
    }
</script>

Step 3: Add your body content

<a href="javascript:demoFromHTML()" class="button">Run Code</a>
<div id="content">
    <h1>  
        We support special element handlers. Register them with jQuery-style.
    </h1>
</div>

Refer to the original tutorial

See a working fiddle

2 of 7
19

You only need this link jspdf.min.js

It has everything in it.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
🌐
GitHub
github.com › parallax › jsPDF › issues › 2852
jspdf 2.0.0 migration fromHTML method · Issue #2852 · parallax/jsPDF
August 14, 2020 - So, previously I was using fromHTML() method to generate the contents of the PDF and print it out. I was not passing any arguments and printing occurred with default browser styles in spite I had some CSS rules applied to the DOM elements when they were simply displayed(not printed). Now, by using html() method, I've got PDF to build with those rules applied.
Published   Aug 14, 2020
Find elsewhere
🌐
npm
npmjs.com › package › jspdf
jspdf - npm
Some functions of jsPDF require optional dependencies. E.g. the html method, which depends on html2canvas and, when supplied with a string HTML document, dompurify. JsPDF loads them dynamically when required (using the respective module format, e.g. dynamic imports).
      » npm install jspdf
    
Published   Nov 19, 2025
Version   3.0.4
🌐
Reddit
reddit.com › r/vuejs › creating a pdf using jspdf.fromhtml
r/vuejs on Reddit: Creating a PDF using jspdf.fromHTML
September 24, 2020 -

So i was working on a personal project and was trying to use jsPDF to create a pdf file using HTML.

I installed the library via npm and even tried importing it with a script tag:

<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>

But it doesn't matter what i do i always get the same error:

This is my code:

<template>
<div id="export">
<h2 class="element">
Umfrage: {{ element }}
</h2>
<div v-if="isRated">
<div v-for="(elem, index) in elements"
:key="index"
class="surveyElements">
<h2 class="element">
{{ elem }}
</h2>
<div v-for="(rating, i) in userRating"
:key="i"
class="element">
<div>
<h4 v-if="rating.rating[0].criteria">
{{ rating.rating[0].criteria }}
{{ (avarage.find(c => c.criteriaName == rating.rating[0].criteria).rating
/ avarage.find(c => c.criteriaName == rating.rating[0].criteria).count )}}
</h4>
{{ rating.fk_user }} {{ rating.rating[0].rating }}
</div>
</div>
<div id="canvasContainer">
<bar-chart :chart-data="datacollection" :options="null"></bar-chart>
</div>
<div id="buttons" v-if="!isPublic">
<ion-button size="large" class="buttonTemplate" id="withTemplate" u/click="publishSurvey()">
Umfrageauswertung Anonym veröffentlichen
</ion-button>
<ion-button size="large" class="buttonTemplate" id="withTemplate" u/click="pdfExport">
PDF-Export
</ion-button>
</div>
</template>

<script>

import jspdf from 'jspdf';

export default {

name: 'StatisticsContentSurveyElement',

methods: {

pdfExport(){
const doc = new jspdf();
const html = document.getElementById("export").innerHTML;
doc.fromHTML(html, 15,15, {
width: 150
});
doc.save("output.pdf");
}
}

What did i do wrong? I am happy for any advice.

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>
🌐
GitHub
github.com › parallax › jsPDF › issues › 34
Creating PDF from HTML · Issue #34 · parallax/jsPDF
June 21, 2012 - var htmlString ="<html><body ><label>INPUT TYPE</label></body></html>"; var doc = new jsPDF('landscape','pt'); doc.fromHTML(htmlString,100,100,{}); doc.output('datauri'); 👍React with 👍1toraritte · No one assigned · No labels · No labels · No type · No projects ·
Published   Sep 25, 2012
🌐
Mrrio
mrrio.github.io › jsPDF › examples › basic.html
jsPDF
var pdf = new jsPDF('p', 'pt', 'letter') // source can be HTML-formatted string, or a reference // to an actual DOM element from which the text will be scraped. , source = $('#fromHTMLtestdiv')[0] // we support special element handlers. Register them with jQuery-style // ID selector for either ...
🌐
C# Corner
c-sharpcorner.com › UploadFile › b629e0 › creating-pdf-from-html-through-jspdf
Creating PDF From HTML Using JSPDF
June 7, 2024 - function demoPDF() { var doc = new jsPDF(); doc.text(10, 10, 'Hello everybody'); doc.text(10, 20, 'My name is'); doc.text(10, 30, 'I have just created a simple pdf using jspdf'); doc.text(10, 40, 'Contact me at'); doc.setFont("times"); doc.setFontType("italic"); doc.text(50, 40, document.getElementById("email").value); // append email id in pdf doc.setFontType("bold"); doc.setTextColor(255, 0, 0); // set font color to red doc.text(60, 20, document.getElementById("fname").value); // append first name in pdf doc.text(100, 20, document.getElementById("lname").value); // append last name in pdf doc.addPage(); // add new page in pdf doc.setTextColor(165, 0, 0); doc.text(10, 20, 'extra page to write'); doc.save('katara.pdf'); // Save the PDF with name "katara"...
🌐
Phppot
phppot.com › javascript › jspdf-html-example
jsPDF HTML Example with html2canvas for Multiple Pages PDF - Phppot
The jsPDF core alone has many features to create PDF documents on the client side. But, for converting HTML to a multi-page PDF document, the core jsPDF library is enough. The latest version replaces the fromHTML plugin with the html.js plugin to convert HTML to PDF.
🌐
GitHub
github.com › parallax › jsPDF › issues › 1176
New html-method · Issue #1176 · parallax/jsPDF
April 14, 2017 - Hi, I've been working on a new html2pdf package that uses html2canvas + jsPDF to convert HTML content to PDF. I know there are already three existing jsPDF plugins for HTML: addHTML, fromHTML, and html2pdf (same name).
Published   Apr 14, 2017
🌐
Pdfnoodle
pdfnoodle.com › blog › generating-pdfs-from-html-with-jspdf
Generating PDFs from HTML with jsPDF and javascript
January 30, 2025 - Learn how to convert HTML to PDF using jsPDF, a popular JavaScript library. Follow our step-by-step guide to generate professional PDFs from templates.