Skip to content
Flamenco edited this page Dec 16, 2014 · 11 revisions

Overview

I originally needed to convert my native html5 canvas code to PDF. I implemented a plugin to mimic the canvas and context2d, redirecting all calls to jsPDF.

The nice thing about this approach (versus embedding canvas images in PDF) is that all text is selectable, searchable, scalable, and the files are 1/4 the size. As an added byproduct of this, general html5 canvas code can now be used to generate PDF files.

So for my next project (to convert HTML to PDF), I used the excellent project html2canvas.pdf to convert HTML to Canvas, but fed it a PDF Canvas instead of the HTML5 Canvas. It Worked :)

#Usage set paths as needed

Include the require.js script

<script src='../../libs/require/require.js'></script>

Require the config script, then require html2pdf. This will pull in all needed dependencies.

<script>
require_baseUrl_override = '../..';
require(['../../libs/require/config'], function(){
require(['html2pdf'], function(){
        var pdf = new jsPDF('p', 'pt', 'letter');
        var canvas = pdf.canvas;
        canvas.height = 72 * 11;
        canvas.width= 72 * 8.5;;
        
        var html = '<html><body>Hello <strong> World</strong></body></html>';

        // 'html' can also be the document.body element
        html2pdf(html, pdf, function(pdf) {        
                pdf.output('dataurlnewwindow');        
        });
}); //require
}); //require
</script>

Examples

These are the 2 html2canvas examples provided on the html2canvas.js site, converted to use jsPDF. It needs some work, but it cleanly divides the html rendering and the pdf rendering, using the PDF canvas as an adapter.

http://rawgit.com/Flamenco/jsPDF/master/examples/html2pdf/pdf.html

http://rawgit.com/Flamenco/jsPDF/master/examples/html2pdf/pdf2.html

Here are some more examples:

http://rawgit.com/Flamenco/jsPDF/master/examples/html2pdf/showcase.html

http://rawgit.com/Flamenco/jsPDF/master/examples/html2pdf/showcase_supported_html.html

http://rawgit.com/Flamenco/jsPDF/master/examples/html2pdf/tables.html

http://rawgit.com/Flamenco/jsPDF/master/examples/html2pdf/lists.html

http://rawgit.com/Flamenco/jsPDF/master/examples/html2pdf/auto_break.html

http://rawgit.com/Flamenco/jsPDF/master/examples/html2pdf/page_break.html

Clone this wiki locally