HTML5 画布转 PDF

2022-01-17 00:00:00 javascript html html5-canvas

我正在使用 HTML5 并使用画布作为设计工具.但是,我想将我的画布保存在一个默认为 image/png 的 jpeg 文件中,并且我想在 PDF 中显示我的画布的预览.

I am working in HTML5 and using canvas as a designing tool. However, I want to save my canvas in a jpeg file with a default of image/png and I want to show the preview of my canvas in a PDF.

推荐答案

一个好的方法是结合使用 jspdf.js 和 html2canvas.

A good approach is to use a combination of jspdf.js and html2canvas.

<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/p4s5k59s/1222/

在 Google Chrome 38、IE11 和 Firefox 34 中测试.
对于 Safari,您可能需要将图像格式从 PNG 更改为 JPEG.

Tested in Google Chrome 38, IE11 and Firefox 34.
For Safari you might need to change the image format from PNG to JPEG.

相关文章