Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
6.6k stars 635 forks source link

embedJpg is writing a jpeg image to pdf as text not as an image #1634

Open BrianErickson-InfoCon opened 1 month ago

BrianErickson-InfoCon commented 1 month ago

What were you trying to do?

I'm trying to place a JPEG image into a PDF file

How did you attempt to do it?

export class MyPDFGenerator { async PDFAddPage( pdfDoc: PDFDocument, Input: string): Promise { let imgPage:PDFImage;

    try {
        const data = fs.readFileSync(Input, {flag: 'r'}); // uint8Array
        const imgPage = await pdfDoc.embedJpg(data);
        const page = pdfDoc.addPage();
        await page.drawImage(imgPage); // , {});
        }
    catch(err)
        {
        console.log("PDFAddPage: " + Input + " ERR: " + err);
        }
    // console.log("HERE");
    }

async TestAddPage(
    Input: string
    ) : Promise<void>
    {
    let sExpectedPDFName:string="/var/www/Output/MyTest2.pdf";

    const pdfDoc = await PDFDocument.create();

    const data = fs.readFileSync(Input, {flag: 'r'});
    const imgPage = await pdfDoc.embedJpg(data);
    const dimScale = imgPage.scale(1.0);
    const page = pdfDoc.addPage();
    await page.drawImage(imgPage, {x: 0, y: 0, width: dimScale.width, height: dimScale.height});

    fs.writeFileSync(sExpectedPDFName, await ((await pdfDoc).saveAsBase64()));
    }
}

const getPdf = new MyPDFGenerator;

async function MyTest2(): Promise<void>
{
let sInputFile:string="/var/www/Output/MyTest.jpg";

// let sExpectedPDFName:string="/var/www/Output/MyTest.pdf";

// const pdfDoc = await PDFDocument.create(); await getPdf.TestAddPage(sInputFile); // PDF Close --- // fs.writeFileSync(sExpectedPDFName, await ((await pdfDoc).saveAsBase64())); };

MyTest2();

What actually happened?

Image is written to PDF as text not an image

What did you expect to happen?

I expected a PDF file to contain the JPEG image in the PDF PDFProb.zip Include code, input JPEG image, and resulting output PDF file.

The example presented reproduces the problem.

How can we reproduce the issue?

tsc TestSample.ts node TestSample.js

Version

pdf-lib 1.17.1 Rocky Linux 9.3

What environment are you running pdf-lib in?

Node

Checklist

Additional Notes

I'm not certain what I'm doing wrong, but I seem to following the instructions outlined in the help.