简体   繁体   中英

Can't get div content using jsPDF

I was trying to generate PDF from HTML using jsPDF and html2canvas. It worked with full page, but not specific div using getElementById() . The console says

IndexSizeError: Index or size is negative or greater than the allowed amount html2canvas.js:2859

Here's my script

 <script>
        let doc = new jsPDF();

        doc.addHTML(document.getElementById('content'), function() {
            doc.save('html.pdf');
        });
    </script>

can anyone help me with this?

doc.addHTML() is actually deprecated now. The new vector-supporting API, doc.html() , works much better. See their sample for yourself. Here is the working code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" 
        integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
        crossorigin="anonymous"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<!-- html2canvas 1.0.0-alpha.11 or higher version is needed -->

<script>
    function download() {
        let pdf = new jsPDF('l', 'pt', 'a3');
        pdf.html(document.getElementById('content'), {
            callback: function (pdf) {
                pdf.save('test.pdf');
            }
        });
    }
</script>

Update: if you got a blank page, try different versions of html2canvas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM