ChatGPT解决这个技术问题 Extra ChatGPT

How to properly use jsPDF library

I want to convert some of my divs into PDF and I've tried jsPDF library but with no success. It seems I can't understand what I need to import to make the library work. I've been through the examples and I still can't figure it out. I've tried the following:

<script type="text/javascript" src="js/jspdf.min.js"></script>

After jQuery and:

$("#html2pdf").on('click', function(){
    var doc = new jsPDF();
    doc.fromHTML($('body').get(0), 15, 15, {
        'width': 170
    });
    console.log(doc);
});

for testing purposes but I receive:

"Cannot read property '#smdadminbar' of undefined"

where #smdadminbar is the first div from the body.

the one which worked for me github.com/devrajatverma/jsPdfExample
Note for all who get here trying to figure out fromHTML or why it isn't documented in the jsPDF docs: "We are closing this issue, because we will not support any longer fromHTML and addHTML." (from issue#516)

S
Simon Bengtsson

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


Thanks for posting this, but I tried the exact code above (locally) and it generates a blank pdf document. It doesn't work at all with jquery 1.11.0 so i used the same jquery version as used on github.com/MrRio/jsPDF/blob/master/examples/js/jquery/…
Yes this is really good,,, But the output of JSPdf is overlapping with another elements of my table elements , How Can i solve it?.... I have changed the size of the fonts and made it as landscape mode , I tried most of the modifications , But nothing is working
I was only able to get this example to work by using the CloudFlare CDNs: <script src="cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/…> or <script src="cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/…> But I agree, documentation, and general variations in code source, contribute to the difficulty of using this plugin. Even these CDNs (which the JSfiddle use) vary from the "download locally" link @Well wisher references above.
how do I make this to print my CSS styles?
FYI. The fiddle provided in this answer uses .fromHTML which was deprecated in November 2018.
u
user890332

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>

Thanks, this was driving me nuts! Using the debug version of jspdf worked, where the other versions in any configuration did not. Maybe minification is breaking it somehow? or I'm doing it wrong.
This really helped me. I was using the original jspdf.js file and it wasn't working. Using jspdf.debug.js did the job.
Interesting why the production version is not working... I included all the plugins in html page and yet, only this debug version helped.
Hi, I tried this but I get error Error in function FileSaver@http://mrrio.github.io/jsPDF/dist/jspdf.debug.js:5875:18: get_URL(...).createObjectURL is not a function, same thing if I use the bower version. Any clue?
@omegastripes Looks like they updated the source; https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js
V
Vitalii Chmovzh

According to the latest version (1.5.3) there is no fromHTML() method anymore. Instead you should utilize jsPDF HTML plugin, see: https://rawgit.com/MrRio/jsPDF/master/docs/module-html.html#~html

You also need to add html2canvas library in order for it to work properly: https://github.com/niklasvh/html2canvas

JS (from API docs):

var doc = new jsPDF();   

doc.html(document.body, {
   callback: function (doc) {
     doc.save();
   }
});

You can provide HTML string instead of reference to the DOM element as well.


Doesnt seem to work anymore either - jQuery.Deferred exception: doc.html is not a function TypeError: doc.html is not a function
Did you find a solution? fromHTML is working in the latest download. But, svg elements are not rendered in the downloaded PDF.
@mythicalcoder I actually ended up writing my own class that will take the DOM tree and will construct the actual PDF using internal jsPDF APIs. That way it is actually a text and not a rasterized screenshot of your page.
Seems much better. Thanks for the reply.
p
pim

This is finally what did it for me (and triggers a disposition):

function onClick() { var pdf = new jsPDF('p', 'pt', 'letter'); pdf.canvas.height = 72 * 11; pdf.canvas.width = 72 * 8.5; pdf.fromHTML(document.body); pdf.save('test.pdf'); }; var element = document.getElementById("clickbind"); element.addEventListener("click", onClick);

Dsdas

Click

And for those of the KnockoutJS inclination, a little binding:

ko.bindingHandlers.generatePDF = {
    init: function(element) {

        function onClick() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            pdf.canvas.height = 72 * 11;
            pdf.canvas.width = 72 * 8.5;

            pdf.fromHTML(document.body);

            pdf.save('test.pdf');                    
        };

        element.addEventListener("click", onClick);
    }
};

Is there more to this snippet? When I try to run this I get an error that indicates 'pdf.canvas' is undefined. "Uncaught TypeError: Cannot set property 'height' of undefined"
Not sure what you mean? The snippet executes using the same code. So perhaps something is off in your implementation. Can you console.log(pdf) and share the output.
It must have been a caching issue or something, when I attempted it just now with the console.log() in there, the code executed correctly. I'm still getting the blank page issue, but that's a different story. Thanks.
also i have error "Cannot read property 'addEventListener'"
I am loving this jsPDF() library. BTW if anyone else finds this useful I just figured out the syntax for attaching a callback to run after the PDF has been generated: pdf.save("myfile.pdf", function(){ alert("pdf generation/save finished!"); });
A
Antwnina

how about in vuejs how is it applicable?

function onClick() { var pdf = new jsPDF('p', 'pt', 'letter'); pdf.canvas.height = 72 * 11; pdf.canvas.width = 72 * 8.5; pdf.fromHTML(document.body); pdf.save('test.pdf'); }; var element = document.getElementById("clickbind"); element.addEventListener("click", onClick);

Dsdas

Click


Thanks for posting the vuejs example of using jdpsf
P
Pedro Almeida

Shouldn't you also be using the jspdf.plugin.from_html.js library? Besides the main library (jspdf.js), you must use other libraries for "special operations" (like jspdf.plugin.addimage.js for using images). Check https://github.com/MrRio/jsPDF.


The jspdf.source.js seems to include all of the other libraries.
A
Akshay Tyagi

first, you have to create a handler.

var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

then write this code in click event:

doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers
        });

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );

assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.