Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas, convert canvas to PDF with jspdf.js

I am trying to convert HTML5 canvas to PDF in JavaScript but I get a black background PDF. I tried to change the background color but still get black. The following is code I am trying:

Canvas = document.getElementById("chart");
Context = Canvas.getContext("2d");

var imgData = Canvas.toDataURL('image/jpeg');
var pdf = new jsPDF('landscape');
pdf.addImage(imgData, 'JPEG', 0, 0, 1350, 750);
pdf.save('download.pdf');

If you have any idea, I'd appreciate it very much.

like image 500
user3289230 Avatar asked Nov 04 '14 09:11

user3289230


1 Answers

A good approach is to use combination of jspdf.js and html2canvas. I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

like image 200
Razan Paul Avatar answered Sep 24 '22 13:09

Razan Paul