简体   繁体   English

pdf-lib 图像不显示

[英]pdf-lib image don't show

I'm trying to add an image to a pdf using pdf-lib ( https://github.com/Hopding/pdf-lib ).我正在尝试使用 pdf-lib ( https://github.com/Hopding/pdf-lib ) 将图像添加到 pdf 中。 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)?它是否与异步函数有关(我对此知之甚少)?

It was quite simple.这很简单。 I just needed to use 'await' when calling the image() function.我只需要在调用 image() 函数时使用“await”。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM