Categories
JavaScript Answers

How to convert canvas to PDF with JavaScript?

Spread the love

Sometimes, we want to convert canvas to PDF with JavaScript.

In this article we’ll look at how to convert canvas to PDF with JavaScript.

How to convert canvas to PDF with JavaScript?

To convert canvas to PDF with JavaScript, we use jsPDF.

For instance, we write

<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>

to add the jsPDF script, canvas and button.

Then we write

const canvas = document.getElementById("myCanvas");
const context = canvas.getContext("2d");

ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

download.addEventListener("click", () => {
  const imgData = canvas.toDataURL("image/jpeg", 1.0);
  const pdf = new jsPDF();

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

to get the canvas with getElementById.

And then we get its context with getContext.

Next we draw a rectangle with rect.

Then we add a click listen to the button with addEventListener.

In it, we call toDataURL to return a base64 URL string with the canvas content as a JPEG.

And then we call pdf.addImage to add the base64 string into the pdf.

Finally, we call save to save the image as download.pdf.

Conclusion

To convert canvas to PDF with JavaScript, we use jsPDF.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *