How to convert a high resolution image to a PDF in JS?

Viewed 230

I'm trying to draw text on a canvas, convert that to an image, and then convert that to a PDF. Most of it is pretty straightforward, but jsPDF seems to always convert the images to PDFs at a ratio of 72 pixels per inch. This produces very blurry, low-resolution images, certainly not suitable for text.

blurry text of "test"

This is what generates that:

const size = [8.5, 11]; // Size in inches
const canvas = document.createElement("canvas");
canvas.width = size[0] * 72;
canvas.height = size[1] * 72;
const context = canvas.getContext("2d");
context.font = "12pt Arial";
context.textBaseline = "top";
context.fillText("test", 200, 100);
const image = canvas.toDataURL("image/png");

const pageOptions = {
    unit: "px",
    format: size.map(s => s * 72),
};
const doc = new jsPDF(pageOptions);
doc.addImage(image, "PNG", 0, 0, size[0] * 72, size[1] * 72);
doc.output('dataurlnewwindow');

If I change all the instances of 72 to say, 300, it will generate an absolutely huge image. If I change only the canvas size to 300 and the font size accordingly but leave everything with jsPDF at 72, it will do exactly what I want in Firefox, if a bit slow, but the resulting PDF will never actually render in Chrome. What's the problem with this code in Chromium-based browsers, and how do I fix it? Or is there a better way to do this?

1 Answers

You can set it when you create the object:

const doc = new jsPDF({
  unit: 'px', // set the units of measurement to px
  format: 'letter', // set the 'paper' size
  userUnit: 72, // set the DPI here. Web uses 72 but you can change to 150 or 300
})
Related