将画布转换为PDF

Kas*_*sta 34 javascript pdf-generation canvas

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

是否有另一种可能的方式,如canvas到img然后img到pdf?

能给我举个例子?

Fr3*_*r3d 73

您可以通过使用jsPDF库和toDataURL函数来实现此目的.

我做了一点演示:

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);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 很好,谢谢你:)有没有办法如何导出与img相同大小(宽度/高度)的PDF? (3认同)
  • @MateuszBartkowski 我认为这是一个错误。当有人编辑我的答案以获得代码片段时添加了它。 (3认同)

use*_*166 9

请参阅https://github.com/joshua-gould/canvas2pdf.此库创建了canvas元素的PDF表示,与将其中的图像嵌入PDF文档的其他建议解决方案不同.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();
Run Code Online (Sandbox Code Playgroud)

  • 由于此库不只是将画布渲染为jpeg并将其放入PDF中,因此它创建了高质量/高分辨率的pdf (2认同)
  • 增加了对图像的支持。请参见https://joshua-gould.github.io/canvas2pdf/demo.html上的图像示例。 (2认同)

Luy*_* Du 5

所以今天,jspdf-1.5.3。回答使 pdf 文件页面与画布完全相同的问题。经过多次不同组合的尝试,我想你必须做这样的事情。我们首先需要以正确的方向设置输出pdf文件的高度和宽度,否则侧面可能会被切断。然后我们从“pdf”文件本身获取尺寸,如果您尝试使用画布的尺寸,则侧面可能会再次被切断。我不确定为什么会发生这种情况,我最好的猜测是 jsPDF 转换库中其他单位的尺寸。

  // Download button
  $("#download-image").on('click', function () {
    let width = __CANVAS.width; 
    let height = __CANVAS.height;

    //set the orientation
    if(width > height){
      pdf = new jsPDF('l', 'px', [width, height]);
    }
    else{
      pdf = new jsPDF('p', 'px', [height, width]);
    }
    //then we get the dimensions from the 'pdf' file itself
    width = pdf.internal.pageSize.getWidth();
    height = pdf.internal.pageSize.getHeight();
    pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
    pdf.save("download.pdf");
  });
Run Code Online (Sandbox Code Playgroud)

从这里了解切换方向:https : //github.com/MrRio/jsPDF/issues/476