Can't get div content using jsPDF

巧了我就是萌 提交于 2019-12-24 06:11:39

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/54497711/cant-get-div-content-using-jspdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!