Hopding / pdf-lib

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

React Native - embed image into form #1416

Open TGTGamer opened 1 year ago

TGTGamer commented 1 year ago

What were you trying to do?

embed image into form

How did you attempt to do it?

import { PDFDocument } from 'pdf-lib'
export async function createReport(images) {
    const formPdfBytes = await fetch(require('./assets/pdf/report_template.pdf')).then(res => res.arrayBuffer());
    const pdfDoc = await PDFDocument.load(formPdfBytes)
    const form = pdfDoc.getForm()
    let count = 0
    for (const i of images) {
        console.log(i)
        const fetched = await fetch(i.link, {mode: 'no-cors'}).then((res) => res.arrayBuffer())
        const image = pdfDoc.embedJpg(fetched)
        form.getButton('image.'+count).setImage(fetched)
        form.getTextField('blade_name.'+count).setText(i.name?.toString() || "")
        form.getTextField('blade_comments.'+count).setText(i.damage?.toString() + ". " + i.location?.toString() || "")
        count++
    }
    form.flatten();
    const uri = await pdfDoc.saveAsBase64({dataUri: true})
    console.log('File has been saved to:', uri);
}

What actually happened?

TypeError: image.scaleToFit is not a function
    at ./node_modules/pdf-lib/es/api/form/PDFField.js.PDFField.createImageAppearanceStream (PDFField.js:338:1)
    at ./node_modules/pdf-lib/es/api/form/PDFButton.js.PDFButton.setImage (PDFButton.js:46:1)
    at pdf.js:81:1
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (asyncToGenerator.js:3:1)
    at _next (asyncToGenerator.js:22:1)
Uncaught (in promise) RangeError: Offset is outside the bounds of the DataView
    at DataView.getUint16 (<anonymous>)
    at Function.<anonymous> (JpegEmbedder.js:39:1)
    at step (tslib.es6.js:100:1)
    at Object.next (tslib.es6.js:81:1)
    at tslib.es6.js:74:1
    at new Promise (<anonymous>)
    at __awaiter (tslib.es6.js:70:1)
    at ./node_modules/pdf-lib/es/core/embedders/JpegEmbedder.js.JpegEmbedder.for (JpegEmbedder.js:35:1)
    at PDFDocument.<anonymous> (PDFDocument.js:958:1)

What did you expect to happen?

Form to embed image

How can we reproduce the issue?

Using a form, get button element and attempt to embed image following pdf-lib spec's.

Version

1.17.1

What environment are you running pdf-lib in?

Browser, React Native

Checklist

Additional Notes

No response

tfrancois commented 3 months ago

Any word on this yet? I am getting the same error.