Adding an Image to a PDF Form Using JavaScript
It’s possible to create image annotations using the UI using the corresponding toolbar button:
Pressing the button will open a file select dialog which will allow you to choose a PNG, JPEG or PDF file to use as attachment for the annotation.
Once the image is picked, the image annotation will be created in the current page with the selected image. When selected, you can use the UI to move it, resize it, or change its opacity:
The attachment is included along with the image annotation when changes are persisted to the document.
Images included using the UI can also be programmatically extracted if needed by passing the attachment ID to instance#getAttachment
, which will resolve to a Blob
containing the image file.
const attachmentBlob = await instance.getAttachment(imageAnnotation.imageAttachmentId);
Adding a button for importing image or PDF files
When in standalone mode, it’s possible to configure button form fields to open a dialog where the user can import a JPG, PNG, or PDF file from their device. The imported file is then added to a PDF, replacing the appearance of the button.
It’s possible to add this feature to your own buttons by setting the corresponding action
property:
const widget = new PSPDFKit.Annotations.WidgetAnnotation({ id: PSPDFKit.generateInstantId(), pageIndex: 0, formFieldName: "buttonIcon", boundingBox: new PSPDFKit.Geometry.Rect({ left: 100, top: 200, width: 100, height: 100, }), action: new PSPDFKit.Actions.JavaScriptAction({ script: "event.target.buttonImportIcon()", }), borderWidth: 0, }); const formField = new PSPDFKit.FormFields.ButtonFormField({ name: "buttonIcon", annotationIds: PSPDFKit.Immutable.List([widget.id]), }); instance.create([widget, formField]);
Notice the event.target.buttonImportIcon()
call in the JavaScript action. This is the method that triggers the image import dialog.