Search code examples
javascriptjspdfhtml2canvas

Generating pdf from external html file and css


I have an external html file that I would like to print as a PDF but I'm having trouble getting the example code to work as intended and I'm obviously missing something trivial when implementing it.

This is my code so far:

function savePDF(data) {
    var parser = new DOMParser();
    var htmlDoc = parser.parseFromString(data, 'text/html'); 

    let pdf = new jsPDF('p','pt','a4');
    pdf.addHTML(
        htmlDoc.body, // HTML DOM element.
    );
    pdf.save("test.pdf");
} 

Where data is a string containing the html of the external webpage I wish to convert to a pdf.

Chrome is generating a TypeError: Cannot read property 'innerWidth' of null

This for example works perfectly (using fromHTML instead of addHTML) but the css/styling is missing:

function savePDF(data) {    
    var parser = new DOMParser();
    var htmlDoc = parser.parseFromString(data, 'text/html'); 
    
    let pdf = new jsPDF('p','pt','a4');
    pdf.fromHTML(htmlDoc.body.innerHTML, 0, 0, {},
        function(){pdf.save('test.pdf');
    });
} 

Sample html that I'm using:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>PDF Test</title>
    </head>
    <body>
        <div id="capture" style="padding: 10px; background: #f5da55">
                <h4 style="color: #000; ">Hello world!</h4>
        </div>
    </body>
</html>

Solution

  • As the documentation says the addHtml method is deprecated ( http://raw.githack.com/MrRio/jsPDF/master/docs/global.html#addHTML), so i played a bit with your example and if you updated your code like this it works. You still have to work a bit to fix the width of div in the pdf.

    <!DOCTYPE html>
            <html>
                <head>
                    <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.js"></script>
                </head>
                <body>
                    <div id="capture" style="padding: 10px; background: #f5da55;">
                            <h4 style="color: #000; ">Hello world!</h4>
                    </div>
                </body>
                <script type="text/javascript">
                    function savePDF(data) {
                        let pdf = new jsPDF('p','pt','a4');
                        pdf.html(data, {
                           callback: function (doc) {
                             doc.save("test.pdf");
                           }
                        });
                    } 
                    savePDF(document.body.innerHTML)
                </script>
            </html>