Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert canvas to PDF

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

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

Can you give me an example?

like image 379
Kasta Avatar asked May 15 '14 14:05

Kasta


People also ask

How do I turn a photo into a canvas?

function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.


1 Answers

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);    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>
like image 122
Fr3d Avatar answered Sep 26 '22 12:09

Fr3d