将画布转换为PDF [英] Convert canvas to PDF

查看:146
本文介绍了将画布转换为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用JavaScript直接将canvas转换为pdf( pdf.js 或类似的东西)?

Is it possible to directly convert canvas to pdf using JavaScript (pdf.js or something like that)?

还有另一种可能的方式,比如canvas到img然后img到pdf吗?

Is there another possible way like canvas to img and then img to pdf?

你能给我一个例子吗?

推荐答案

你可以通过利用 jsPDF 库和 toDataURL 功能。

You can achieve this by utilizing the jsPDF library and the toDataURL function.

我做了一点演示:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

// draw a blue cloud
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);
context.closePath();
context.lineWidth = 5;
context.fillStyle = '#8ED6FF';
context.fill();
context.strokeStyle = '#0000ff';
context.stroke();

download.addEventListener("click", function() {
  // only jpeg is supported by jsPDF
  var imgData = canvas.toDataURL("image/jpeg", 1.0);
  var pdf = new jsPDF();

  pdf.addImage(imgData, 'JPEG', 0, 0);
  pdf.save("download.pdf");
}, false);

<script src="//cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>


<canvas id="myCanvas" width="578" height="200"></canvas>
<button id="download">download</button>

这篇关于将画布转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆