pdf-lib icon indicating copy to clipboard operation
pdf-lib copied to clipboard

React Native - embed image into form

Open TGTGamer opened this issue 2 years ago • 1 comments

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

  • [X] My report includes a Short, Self Contained, Correct (Compilable) Example.
  • [X] I have attached all PDFs, images, and other files needed to run my SSCCE.

Additional Notes

No response

TGTGamer avatar Mar 15 '23 00:03 TGTGamer

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

tfrancois avatar Jul 09 '24 12:07 tfrancois