Draw image in a PDF with a certain DPI

223 Views Asked by At

I am trying to draw an image in a pdf with PDF-Lib.

My purpose is to draw it in full size in a page of 6cm x 11.3cm.

I made the math conversion, if i want 300 DPI, it correspond to 780px x 1406px.

I made an image with these exact dimensions, and try to draw it :

    const width = 780
    const height = 1406
    let page: PDFPage
    page = pdfDoc.addPage([width, height]);
    const imageBytes = await fetch(MyImageAsString).then((response) => response.arrayBuffer());
    const image = await pdfDoc.embedPng(imageBytes);
    page.drawImage(image);

But when i open it (with Adobe for example) to measure it, the page is really big, about 27.5 cm x 49.5 cm

How to draw my image in the right size ?

1

There are 1 best solutions below

0
On BEST ANSWER

Both the page and image must be sized the same for what you want to achieve. The image isn't actually resized. It is drawn such that it occupies the specified size.

And both times the size is specified in point, equivalent to 1/72 inch. So a conversion from pixel to points is needed.

It will look something like this:

const imageWidth = 780 * 72 / 300
const imageHeight = 1406 * 72 / 300
let page: PDFPage
page = pdfDoc.addPage([imageWidth, imageHeight]);
const imageBytes = await fetch(MyImageAsString).then((response) => response.arrayBuffer());
const image = await pdfDoc.embedPng(imageBytes);
page.drawImage(image, {
  x: 0,
  y: 0,
  width: imageWidth,
  height: imageHeight,
});