Categories
JavaScript Answers

How to Convert a Canvas’ Content to a PDF with JavaScript?

Spread the love

Sometimes, we want to convert a canvas’ content to a PDF with JavaScript.

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

Convert a Canvas’ Content to a PDF with JavaScript

To convert a canvas’ content to a PDF with JavaScript, we can use the jsPDF library.

For instance, we can write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js"></script>

<canvas id="myCanvas" width="200" height="200"></canvas>

<button>
  download
</button>

to add the jsPDF library with a script tag.

Then we add the canvas elements and button to download the PDF.

Next, we write:

const canvas = document.querySelector('canvas');
const download = document.querySelector('button');
const context = canvas.getContext('2d');
const {
  jsPDF
} = window.jspdf;
const pdf = new jsPDF();

context.fillStyle = 'yellow';
context.fillRect(0, 0, 100, 100);

download.addEventListener("click", () => {
  const imgData = canvas.toDataURL("image/jpeg", 1.0);
  pdf.addImage(imgData, 'JPEG', 0, 0);
  pdf.save("download.pdf");
}, false);

to get the canvas and the button with document.querySelector .

Then we get the canvas context with canvas.getContext .

Next, we create a new jsPDF instance with:

const {
  jsPDF
} = window.jspdf;
const pdf = new jsPDF();

Then we draw a yellow square with:

context.fillStyle = 'yellow';
context.fillRect(0, 0, 100, 100);

Next, we add a click handler to the button with:

download.addEventListener("click", () => {
  const imgData = canvas.toDataURL("image/jpeg", 1.0);
  pdf.addImage(imgData, 'JPEG', 0, 0);
  pdf.save("download.pdf");
}, false);

In the event handler, we call canvas.toDataURL with 'image/jpeg' to return the image data version of the canvas.

Then we pass that into pdf.addImage with 'JPEG' to add the image into the PDF.

Finally, we call pdf.save with the file name of the PDF.

Now when we click download, we see a PDF with a yellow square.

Conclusion

To convert a canvas’ content to a PDF with JavaScript, we can use the jsPDF library.

By John Au-Yeung

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

One reply on “How to Convert a Canvas’ Content to a PDF with JavaScript?”

This seems to convert the canvas content to a jpeg before adding the jpeg to the pdf. I believe the library canvas2pdf recreated the actual vectors within a pdf. Could you do a simple overview of using that library?

Leave a Reply

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