Reputation: 1577
I'm trying to add an image to a pdf using pdf-lib (https://github.com/Hopding/pdf-lib). It works fine when I do:
const { PDFDocument, StandardFonts, rgb } = PDFLib;
async function createPdf() {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
const jpgUrl = '/images/logo.jpg';
const jpgImageBytes = await fetch(jpgUrl).then((res) => res.arrayBuffer());
const jpgImage = await pdfDoc.embedJpg(jpgImageBytes);
page.drawImage(jpgImage, {
x: 7,
y: 800,
width: 196,
height: 30
});
}
const pdfBytes = await pdfDoc.save();
But when I'm wrapping some of the code in a function, it won't render the image:
const { PDFDocument, StandardFonts, rgb } = PDFLib;
async function createPdf() {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
async function image() {
const jpgUrl = '/images/logo.jpg';
const jpgImageBytes = await fetch(jpgUrl).then((res) => res.arrayBuffer());
const jpgImage = await pdfDoc.embedJpg(jpgImageBytes);
page.drawImage(jpgImage, {
x: 7,
y: 800,
width: 196,
height: 30
});
console.log('done');
}
image();
}
const pdfBytes = await pdfDoc.save();
It does not showing any errors and prints 'done' in the console as expected. Does it has to do with async functions (which I know very little about)?
Upvotes: 0
Views: 3516
Reputation: 1577
It was quite simple. I just needed to use 'await' when calling the image() function.
const { PDFDocument, StandardFonts, rgb } = PDFLib;
async function createPdf() {
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage();
async function image() {
const jpgUrl = '/images/logo.jpg';
const jpgImageBytes = await fetch(jpgUrl).then((res) => res.arrayBuffer());
const jpgImage = await pdfDoc.embedJpg(jpgImageBytes);
page.drawImage(jpgImage, {
x: 7,
y: 800,
width: 196,
height: 30
});
console.log('done');
}
await image();
}
const pdfBytes = await pdfDoc.save();
Upvotes: 2