1

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 ?

Foxhunt
  • 764
  • 1
  • 9
  • 23
  • You need to scale the image, not the page. Pages in PDF are set at 72 units to the inch, so 780 units = 10.833 inches = 27.5166 cm wide and 1406 units = 19.527 inches = 49.600 cm. So you want to call addPage with a width of 6cm = 2.36 inches = 170 units and a height of 4.48 inches = 320.31 units. How you scale the image to fit the page I haven't a clue though, presumably 'image' is a complex container so you probably have to alter some of its properties. – KenS Jul 03 '23 at 19:11
  • I modified my question. The image i made is at 780px x 1406px, because thats what i want to draw – Foxhunt Jul 03 '23 at 19:26
  • 1
    Oh you are right ! Corrected ! – Foxhunt Jul 03 '23 at 23:24

1 Answers1

1

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,
});

Codo
  • 75,595
  • 17
  • 168
  • 206