Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsPDF + rasterizeHTML not working?

jsPDF's addHTML requires html2canvas.js or rasterizeHTML.js.

I want to use rasterizeHTML.js but it doesn't work. Couldn't find any example online.

Working with html2canvas.js:

html

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


<body>
    <p id="to-pdf">HTML content...</p>
</body>

js

var pdf = new jsPDF('p','pt','a4');
pdf.addHTML(document.body,function() {
    pdf.save('web.pdf');
});

Not working with rasterizeHTML.js (nothing happens; no errors):

html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rasterizehtml/1.2.2/rasterizeHTML.allinone.js"></script>


<body>
    <p id="to-pdf">HTML content...</p>
</body>

js

var pdf = new jsPDF('p','pt','a4');
pdf.addHTML(document.body,function() {
    pdf.save('web.pdf');
});

What am I missing?

like image 781
Shawn Avatar asked Aug 11 '16 22:08

Shawn


1 Answers

I had the same problem recently and managed to piece together a working example from various sources.

Basic HTML

<div id="canvas" width="100%">
    <table class='CSSTableGenerator'>
        <tr>
            <td>Item</td>
            <td>Cost</td>
            <td>Description</td>
            <td>Available</td>
        </tr>
        <tr>
            <td>Milk</td>
            <td>$1.00</td>
            <td>Cow puss</td>
            <td>Out Of Stock</td>
        </tr>
        <tr>
            <td>Milk</td>
            <td>$1.00</td>
            <td>white stuff</td>
            <td>Out Of Stock</td>
        </tr>
    </table>
</div>
<button id="download">Create PDF</button>

JS

$(document).ready(function () {
    $('#download').click(function () {
        html2canvas(document.getElementById('canvas'), {
            onrendered: function (canvas) {
                var imgData = canvas.toDataURL('image/png');
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('download.pdf');
            }
        });
    });
});

http://jsfiddle.net/andyg2/mtLqparw/

Resources

https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js

https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js

like image 82
Andy Gee Avatar answered Nov 08 '22 20:11

Andy Gee