DEV Community

Discussion on: Add an Image to a PDF file using Node.JS (script)

Collapse
 
fritzsierra profile image
Fritzsierra

Thank you for sharing your code, I have used it to be able to insert stamps in the upper right corner of all pages.

(async () => {
const pdfDoc = await PDFDocument.load(fs.readFileSync("CONSOLIDADO_FSIERRA_27-06-2020 03-32-27.pdf"));
const img = await pdfDoc.embedPng(fs.readFileSync("image.PNG"));

for (let i = 0; i < pdfDoc.getPageCount(); i++) {
let imagePage='';
imagePage = pdfDoc.getPage(i);
console.log(i+1)
console.log(imagePage.getWidth())
let xx=imagePage.getWidth()
console.log(imagePage.getHeight())
let yy=imagePage.getHeight()
imagePage.drawImage(img, {
x: xx-70,
y: yy-70,
width: 70,
height: 70

});
}

Collapse
 
dmshvetsov profile image
Dmitry Shvetsov

Nice!

BTW you can use github.com/adam-p/markdown-here/wi... to make your code looks great and readable.

Collapse
 
fritzsierra profile image
Fritzsierra

Hi Iamdi, a question, can you convert that code with the pdf-lib library to an executable? Thank you

Thread Thread
 
dmshvetsov profile image
Dmitry Shvetsov

You can use pkg npm package npmjs.com/package/pkg

Collapse
 
parthshah27 profile image
parthshah27

Hey @fritzsierra ,
In your code how can we set stamp height and width dynamically. I have used your logic to add stamp on pdf but not getting whole image as we specified fix height and width ?