File Attachment Annotations#
There are two ways to embed files - directly to a document (attaching a file to the whole document)
or as an embedded file on a "FileAttachment"
annotation.
Creating an Annotation File Attachment#
Embedding files onto annotation objects requires us to associate a buffer of file data against a "FileAttachment"
annotation object.
We need to:
Create a buffer with the contents of the file we want to attach.
Get a document reference to the file we want to add the attachment to.
Source the page we want to add the file attachment to.
Create a “FileAttachment” type annotation and set its position.
Create a file specification object and add the attached file data to it.
Associate the annotation with our newly created file specification object.
The following code exemplifies the steps outlined above:
EXAMPLE
let embedMe = fs.readFileSync("embedMe.doc")
let document = mupdf.Document.openDocument(fs.readFileSync("test.pdf"), "application/pdf")
let page = document.loadPage(0)
let annotation = page.createAnnotation("FileAttachment")
annotation.setRect([50,50,100,100])
let fileSpecObject = document.addEmbeddedFile("embedMe.doc",
"application/msword",
embedMe,
new Date(),
new Date(),
false)
annotation.setFileSpec(fileSpecObject)
fs.writeFileSync("output.pdf", document.saveToBuffer("incremental").asUint8Array())
The file attachment will appear as a “push pin” icon by default on the PDF document, clicking on the icon will open the attachment.
You can also change the look of the icon with setIcon()
for this annotation (to a paper clip for example) if required.
Removing an Embedded File on a File Attachment#
To remove an embedded file, retrieve the required “FileAttachment” annotation and set it to null
.
EXAMPLE
annotation.setFileSpec(null)
Code samples
Code samples are in TypeScript and assume that the following requirements are defined in your TypeScript file header as follows:
import * as fs from "fs"
import * as mupdfjs from "mupdf/mupdfjs"