HTML5 canvas, convert canvas to PDF with jspdf.js

谁都会走 提交于 2019-12-03 00:16:08

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/

Scott Close

One very simple solution is that you are saving the image as jpeg. Saving instead as png works fine for my application. Of note, Blizzard's response also includes the print as png, and also produces non-black fill for transparent layers in the canvas.

  var canvas = event.context.canvas;
  var data = canvas.toDataURL('image/png');

instead of

  var canvas = event.context.canvas;
  var data = canvas.toDataURL('image/jpg');

I had the same problem, e.g. the first time when i create a pdf the canvas image is ok, but all the other next, came out black. No picture!

The workaround i found is as follows: after each call to pdf.addImage() i redraw the picture in the canvas. It works now fine for me.

EDIT: As requested, here some more details:

Let say i have a canvas drawing function like this (just an example, it doesn't matter):

function drawCanvas(cv) {
  for(var i=0; i<cv.height; i++) {
    for(var j=0, d=0; j<cv.width; j++) {
      cv.data[d] = 0xff0000;
      d += 4;
    }
  }
}

I had to fix my printing function as follows:

var cv=document.getElementById('canvas');
printPDF(cv) {
    var imgData=cv.toDataURL("image/jpeg", 1.0);
    var doc=new jsPDF("p","mm","a4");
    doc.addImage(imgData,'JPEG',15,40,180,180);
    drawCanvas(cv); // <--- this line is needed, draw again
}
drawCanvas(cv); // <--- draw my image to the canvas, ok
printPDF(cv); // first time is fine
printPDF(cv); // second time without repaint would be black

I admit, i did'nt investigate further, just happy that this works.

At first, you need to set the desired background color on the canvas before getting the data. Then, you need to draw jpeg image on the canvas.

Just change JPEG to PNG pdf.addImage(imgData, 'PNG', 0, 0, 1350, 750);

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