I have developed a function that scales down the font size until the text width is smaller than the canvas width. This text is then added to a canvas containing a QR code.
Subsequently, this canvas is included in a PDF file.
The issue I am encountering is that while the QR code remains crisp and clean, the text becomes blurry.
Take a look at the resulting QR code with text in this screenshot:
https://i.sstatic.net/4mPxE.png
For comparison, here is the QR code at the same size and using the same font created in Word:
https://i.sstatic.net/MT6KU.png
Here are full-size screenshots to confirm they are the same size. Both were taken from the PDF file:
Below is the code responsible for generating this QR code with text:
printQRCode(){
const width = 150; // will be dynamic in the future
const ratio = 8 / 100;
const fontSize = width * ratio;
const text = `[${this.getCode()}]`;
toCanvas(text,
{errorCorrectionLevel: 'H', width},
(_err, canvas) => {
const ctx = canvas.getContext('2d');
this.setOptimalFontSizeForCanvas(ctx, fontSize, text, width);
ctx.fillText(text, this.getCenterPositionForCanvasText(ctx, text, width), width - 5);
const contentDataURL = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'px', 'a4');
pdf.addImage(contentDataURL, 'PNG', 0, 0, canvas.width, canvas.height);
pdf.autoPrint();
pdf.output('dataurlnewwindow');
});
}
setOptimalFontSizeForCanvas(ctx: CanvasRenderingContext2D, fontSize: number, text: string, width: number){
ctx.font = fontSize + 'px Arial';
do{
fontSize--;
ctx.font = fontSize + 'px Arial';
}while(ctx.measureText(text).width>width- Math.floor(width / 10));
}
What adjustments should I make to prevent the text from appearing blurry?
Edit:
I inspected the dataURL of the canvas and noticed that the original canvas is much smaller than the one ultimately printed on the PDF file. I attempted changing the input unit of the PNG to 'pt', which did reduce the canvas size, yet it still exceeds the image from the dataURL.
How can I accurately determine the necessary width and height to pass to the PNG function?