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