使用pdf.js将画布转换为PDF [英] Convert canvas to PDF using pdf.js

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

问题描述

请使用JS(pdf.js或类似的东西)直接将canvas转换为pdf?或者是这里的其他可行的方式像画布到img然后img的pdf?你能给我举个例子吗?我发现只有一个页面,但已经不存在。谢谢你的帮助。

解决方案

我的第一个答案stackoverflow,所以请忍受我:)



您可以使用 jsPDF 库和 toDataURL 函数。
我做了一些演示:



  var canvas = document.getElementById('myCanvas'); var context = canvas.getContext '2d'); //绘制一个蓝色cloudcontext.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(){// jsPDF支持jpeg var imgData = canvas.toDataURL(image / jpeg ,1.0); var pdf = new jsPDF(); pdf.addImage(imgData,'JPEG',0,0); var download = document.getElementById('download'); pdf.save(download.pdf);},false);  

 < script src =https://parall.ax/parallax/js/jspdf.js>< / script>< canvas id =myCanvaswidth =578height =200 >< / canvas>< button id =download>下载< / button>  

b $ b

please is posible to directly convert canvas to pdf using JS (pdf.js or something like that)? Or is here other posible way like canvas to img and then img to pdf? Can you give me example? I found only one page about that but already doesn't exist. Thank you for help.

解决方案

My first answer on stackoverflow, so please bear with me :)

You can achieve this by utilizing the jsPDF library and the toDataURL function. I made a little demonstration:

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);
  var download = document.getElementById('download');

  pdf.save("download.pdf");
}, false);

<script src="https://parall.ax/parallax/js/jspdf.js"></script>
<canvas id="myCanvas" width="578" height="200"></canvas>
<button id="download">download</button>

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

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