The PDFDocument is a specialized subclass of Document which has additional methods that are only available for PDF files.
A PDF document contains objects: dictionaries, arrays, names, strings, numbers, booleans, and indirect references. Some dictionaries also have attached data. These are called streams, and may be compressed.
At the root of the PDF document is the trailer object; which contains pointers to the meta data dictionary and the catalog object, which in turn contains references to the pages and forms and everything else.
Pointers in PDF are called indirect references, and are of the form 32 0 R (where 32 is the object number, 0 is the generation, and R is magic syntax). All functions in MuPDF dereference indirect references automatically.
PDFObjects are always bound to the document that created them. Do NOT mix and match objects from one document with another document!
Create a brand new PDF document instance that begins empty with no pages.
To open an existing PDF document, use Document.openDocument().
only mutool run
Format a link URI given a system
independent path to a remote document and a destination object or a
destination string suitable for Page.prototype.createLink().
string) – An absolute or
relative path to a remote document file.Link | string) – Link or
string referring to a destination using either a destination object or a
destination name in the remote document.only mutool run
Append a fragment representing a document destination to a an
existing URI that points to a remote document. The resulting string is
suitable for Page.prototype.createLink().
string) – An URI to a remote
document file.Link | string | number) –
A Link or string referring to a destination using either a destination
object or a destination name in the remote document, or a page
number.Returns true if a password is required to open a password protected PDF.
var needsPassword = document.needsPassword()Returns a bitfield value against the password authentication result.
The values returned by this interface are interpreted like this:
| Bit | Description |
|---|---|
| 0 | Failed |
| 1 | No password needed |
| 2 | User password is okay |
| 4 | Owner password is okay |
string) – The password to
attempt authentication with.var auth = document.authenticatePassword("abracadabra")Returns true if the document has permission for the supplied permission parameter.
These are the recognized permission strings:
| String | The Document may… |
|---|---|
| … be printed. | |
| edit | … be edited. |
| copy | … be copied. |
| annotate | … have annotations added/removed. |
| form | … have form field contents edited. |
| accessibility | … be copied for accessibility. |
| assemble | … have its pages rearranged. |
| print-hq | … be printed in high quality be printed in high quality. |
string) – The permission
to seek for, e.g. “edit”.var canEdit = document.hasPermission("edit")Returns the PDF document version as an integer multiplied by 10, so e.g. a PDF-1.4 document would return 14.
var version = pdfDocument.getVersion()Set the document’s language code.
string)pdfDocument.setLanguage("en")Get the document’s language code.
var lang = pdfDocument.getLanguage()only mutool run
Returns whether the document was an XFA form without AcroForm fields.
var wasPureXFA = pdfDocument.wasPureXFA()Returns whether the document was repaired when opened.
var wasRepaired = pdfDocument.wasRepaired()Return an object whose properties and their values come from corresponding names/values from the given name tree.
var dests = pdfDocument.loadNameTree("Dests")
for (var p in dests) {
console.log("Destination: " + p)
}Create a new null object.
var obj = doc.newNull()Create a new boolean object.
boolean)var obj = doc.newBoolean(true)Create a new integer object.
number)var obj = doc.newInteger(1)Create a new real number object.
number)var obj = doc.newReal(7.3)Create a new string object.
string)var obj = doc.newString("hello")Create a new byte string object.
Uint8Array | Array of number)var obj = doc.newByteString([21, 31])Create a new name object.
string)var obj = doc.newName("hello")Create a new indirect object.
number)number)var obj = doc.newIndirect(42, 0)Create a new array object.
var obj = doc.newArray()Create a new dictionary object.
var obj = doc.newDictionary()The trailer dictionary. This contains indirect references to the “Root” and “Info” dictionaries.
var dict = doc.getTrailer()Return the number of objects in the PDF.
var num = doc.countObjects()Allocate a new numbered object in the PDF, and return an indirect reference to it. The object itself is uninitialized.
var obj = doc.createObject()Delete the object referred to by an indirect reference or its object number.
PDFObject | number) – Delete the
referenced object number.doc.deleteObject(obj)Add obj to the PDF as a numbered object, and return an indirect reference to it.
var ref = doc.addObject(obj)Create a stream object with the contents of buffer, add it to the PDF, and return an indirect reference to it. If object is defined, it will be used as the stream object dictionary.
Buffer | ArrayBuffer | Uint8Array | string) – Buffer whose
data to put into stream.PDFObject) – The object
to add the stream to.var stream = doc.addStream(buffer, object)Create a stream object with the contents of buffer, add it to the PDF, and return an indirect reference to it. If object is defined, it will be used as the stream object dictionary. The buffer must contain already compressed data that matches “Filter” and “DecodeParms” set in the stream object dictionary.
Buffer | ArrayBuffer | Uint8Array | string) – Buffer whose
data to put into stream.PDFObject) – The object
to add the stream to.var stream = doc.addRawStream(buffer, object)Enable or disable the page tree cache that is used to speed up page object lookups. The page tree cache is used unless explicitly disabled with this function.
Disabling the page tree cache reduces the number objects that we need to read from the file when loading a single page. However it will make page lookups slower overall!
boolean)Return the PDFObject for a page number.
number) – The page number, the
first page is number zero.var obj = pdfDocument.findPage(0)only mutool run
Find a given PDFPage and return its page number. If the page can not be found, returns -1.
PDFPage)var pageNumber = pdfDocument.findPageNumber(page)only mutool run
Find the destination corresponding to a specific named destination given as a name or byte string in the form of a PDFObject.
Returns null if the named destination does not exist.
var destination = pdfDocument.lookupDest(nameobj)Rearrange (re-order and/or delete) pages in the PDFDocument.
The pages in the document will be rearranged according to the input list. Any pages not listed will be removed, and pages may be duplicated by listing them multiple times.
The PDF objects describing removed pages will remain in the file and
take up space (and can be recovered by forensic tools) unless you save
with the “garbage” option set, see PDFDocument.prototype.save().
Array of number) – An array of
page numbers, each page number is 0-based.var document = new Document.openDocument("my_pdf.pdf")
pdfDocument.rearrangePages([3,2])
pdfDocument.save("fewer_pages.pdf", "garbage")Insert the page’s PDFObject into the
page tree at the page number specified by at (numbered from
0). If at is -1, the page is inserted at the end of the
document.
number) – The index to insert
at.PDFObject) – The
PDFObject representing the page to insert.pdfDocument.insertPage(-1, page)Delete the page at the given index.
number) – The page number, the
first page is number zero.pdfDocument.deletePage(0)Create a new PDFPage object. Note: this
function does NOT add it to the page tree, use PDFDocument.prototype.insertPage()
to do that.
Creation of page contents is described in detail in the PDF specification’s section on Content Streams.
var helvetica = pdfDocument.addSimpleFont(new mupdf.Font("Helvetica"), "Latin")
var fonts = pdfDocument.newDictionary()
fonts.put("F1", helvetica)
var resources = pdfDocument.addObject(pdfDocument.newDictionary())
resources.put("Font", fonts)
var pageObject = pdfDocument.addPage(
[0,0,300,350],
0,
resources,
"BT /F1 12 Tf 100 100 Td (Hello, world!) Tj ET"
)
pdfDocument.insertPage(-1, pageObject)Create a PDFObject from the Font object as a simple font.
Font)"Latin" | "Greek" | "Cyrillic") – Which 8-bit encoding to
use. Defaults to “Latin”.See Font.SIMPLE_ENCODING_LATIN,
etc.
var obj = pdfDocument.addSimpleFont(new mupdf.Font("Times-Roman"), "Latin")Create a PDFObject from the Font object as a UTF-16 encoded CID font for the given language (“zh-Hant”, “zh-Hans”, “ko”, or “ja”), writing mode (“H” or “V”), and style (“serif” or “sans-serif”).
Font)string)number) – 0 for
horizontal writing, and 1 for vertical writing.string)var obj = pdfDocument.addCJKFont(new mupdf.Font("ja"), "ja", 0, "serif")Create a PDFObject from the Font object as an Identity-H encoded CID font.
var obj = pdfDocument.addFont(new mupdf.Font("Times-Roman"))Create a PDFObject from the Image object.
var obj = pdfDocument.addImage(new mupdf.Image(pixmap))Load an Image from a PDFObject (typically an indirect reference to an image resource).
var image = pdfDocument.loadImage(obj)Embedded a file into the document. If a checksum is added then the file contents can be verified later. An indirect reference to a file specification object is returned.
The returned file
specification object can later be e.g. connected to an annotation
using PDFAnnotation.prototype.setFilespec().
string)string) – The MIME-type.Buffer | ArrayBuffer | Uint8Array | string)Date)Date)boolean) – Defaults to
false.var fileSpecObject = pdfDocument.addEmbeddedFile(
"my_file.jpg",
"image/jpeg",
buffer,
new Date(),
new Date(),
false
)Returns a record of any embedded files on the this PDFDocument.
Delete an embedded file by filename.
string) – Name of embedded
file to delete.doc.deleteEmbeddedFile("test.txt")Insert the given file specification as an embedded file using the given filename.
string) – Name of the file
to insert.PDFObject) – File
specification.pdfDocument.insertEmbeddedFile("test.txt", fileSpecObject)
pdfDocument.deleteEmbeddedFile("test.txt")Get the file specification parameters from the file specification.
PDFObject) – file
specification object.var obj = pdfDocument.getFilespecParams(fileSpecObject)Returns a Buffer with the contents of the
embedded file referenced by fileSpecObject.
Object) – file
specificationvar buffer = pdfDocument.getEmbeddedFileContents(fileSpecObject)only mutool run
Verify the MD5 checksum of the embedded file contents.
Object) – file
specification.var fileChecksumValid = pdfDocument.verifyEmbeddedFileChecksum(fileSpecObject)only mutool run
Check if the given object is a file
specification.
PDFObject)var isFilespec = pdfDocument.isFilespec(obj)Check if the given object is a file
specification representing a file embedded into the PDF
document.
PDFObject)var isFilespecObject = pdfDocument.isEmbeddedFile(obj)only mutool run
Return the number of associated files associated with this document. Note that this is the number of files associated at the document level, not necessarily the total number of files associated with elements throughout the entire document.
var count = pdfDocument.countAssociatedFiles()only mutool run
Return the file specification object that represents the nth associated file for this document.
n should be in the range
0 <= n < countAssociatedFiles().
Returns null if no associated file exists or index is out of range.
var obj = pdfDocument.associatedFile(0)Create a graft map on the destination document, so that objects that have already been copied can be found again. Each graft map should only be used with one source document. Make sure to create a new graft map for each source document used.
var graftMap = doc.newGraftMap()Deep copy an object into the destination document. This function will
not remember previously copied objects. If you are copying several
objects from the same source document using multiple calls, you should
use a graft map instead, see PDFDocument.prototype.newGraftMap().
var copiedObj = doc.graftObject(obj)Graft a page and its resources at the given page number from the source document to the requested page number in the document.
number) – The page number to
insert the page before. Page numbers start at 0 and -1 means at the end
of the document.PDFDocument) – Source
document.number) – Source page
number.This would copy the first page of the source document (0) to the last page (-1) of the current PDF document.
doc.graftPage(-1, srcDoc, 0)Activate journalling for the document.
pdfDocument.enableJournal()Returns a Javascript object with a property indicating the current position, and the names of each entry in the undo/redo journal history:
{ position: number, steps: Array of string }
var journal = pdfDocument.getJournal()Begin a journal operation. Each call to begin an operation should be
paired with a call to either PDFDocument.prototype.endOperation()
if the operation was successful, or to PDFDocument.prototype.abandonOperation()
if it failed.
string) – The name of the
operation.pdfDocument.beginOperation("Change annotation color")
// Change the annotation
pdfDocument.endOperation()Begin an implicit journal operation. Implicit operations are
operations that happen due to other operations, and that should not be
subdivided into separate undo steps. E.g. editing several attributes of
a PDFAnnotation might be desirable to
do in a single undo step. See PDFDocument.prototype.beginOperation()
for the requirements about paired calls.
pdfDocument.beginOperation("Complex operation")
pdfDocument.beginImplicitOperation()
pdfDocument.endOperation()
pdfDocument.beginImplicitOperation()
pdfDocument.endOperation()
pdfDocument.endOperation()End a previously started normal or implicit operation. After this it
can be undone and
redone.
pdfDocument.endOperation()Abandon a normal or implicit operation. Reverts to the state before that operation began. This is normally called if an operation failed for some reason.
pdfDocument.abandonOperation()Returns whether undo is possible in this state.
var canUndo = pdfDocument.canUndo()Returns whether redo is possible in this state.
var canRedo = pdfDocument.canRedo()Move backwards in the undo history. Changes to the document after this call will throw away all subsequent undo history.
pdfDocument.undo()Move forwards in the undo history.
pdfDocument.redo()only mutool run
Save the undo/redo journal to a file.
string) – File to save the
journal to.pdfDocument.saveJournal("test.journal")Return the number of optional content layer configurations in this document.
var configs = pdfDocument.countLayerConfigs()Return the name of configuration number n, where
n is 0 <= n < countLayerConfigs().
var name = pdfDocument.getLayerConfigName(0)Return the creator of configuration number n, where
n is 0 <= n < countLayerConfigs().
var creator = pdfDocument.getLayerConfigCreator(0)Select layer configuration number n, where
n is 0 <= n < countLayerConfigs().
var info = pdfDocument.selectLayerConfig(1)Return the number of optional content layer UI elements in this document given the selected optional content layer configuration.
Return the information about optional content layer UI element number
n, where n is
0 <= n < countLayerConfigUIs().
{ type: number, depth: number, selected: boolean, locked: boolean, text: string }Return the number of optional content layers in this document.
var layers = pdfDocument.countLayers()Return whether layer n is visible, where n
should be in the interval 0 <= n < countLayers().
number) – What layer to check
visibility of.var visible = pdfDocument.isLayerVisible(1)Set layer n to be visible or invisible, where
n is in the interval
0 <= n < countLayers().
Pages affected by a visibility change, need to be processed again for the layers to be visible/invisible.
number) – What layer to change
visibility for.boolean) – Whether the layer
should be visible.pdfDocument.setLayerVisible(1, true)Return the name of layer number n, where n
is 0 <= n < countLayers().
var name = pdfDocument.getLayerName(0)Sets the page label numbering for the page and all pages following it, until the next page with an attached label.
number) – The start page index
to start labeling from.string) – Can be one of the
following strings: “” (none), “D” (decimal), “R” (roman numerals
upper-case), “r” (roman numerals lower-case), “A” (alpha upper-case), or
“a” (alpha lower-case).string) – Define a prefix for
the labels.number) – The ordinal with
which to start numbering.doc.setPageLabels(0, "D", "Prefix", 1)Removes any associated page label from the page.
number)doc.deletePageLabels(0)Check the file for syntax errors, and run a repair pass if any are found. This is a costly operation, but may be necessary to prevent any changes to a document from being potentially lost.
If a syntax error is discovered after a file has been edited, those edits may be lost during the file repair pass. In practice this rarely happens because syntax errors that trigger a repair usually happen either when first opening the document or when loading a page; but you can never be certain!
Returns whether the document can be saved incrementally, e.g. repaired documents or applying redactions prevents incremental saves.
var canBeSavedIncrementally = pdfDocument.canBeSavedIncrementally()Saves the document to a Buffer.
string) – See PDF Write Options.var buffer = doc.saveToBuffer("garbage=2,compress=yes")Saves the document to a file.
string)string) – See PDF Write Optionsdoc.save("out.pdf", "incremental")Returns the number of versions of the document in a PDF file, typically 1 + the number of updates.
var versionNum = pdfDocument.countVersions()Returns true if the document has been changed since it was last opened or saved.
var hasUnsavedChanges = pdfDocument.hasUnsavedChanges()Returns the number of unsaved updates to the document.
var unsavedVersionNum = pdfDocument.countUnsavedVersions()Check the history of the document, and determine the last version
that checks out OK. Returns 0 if the entire history is OK,
1 if the next to last version is OK, but the last version
has issues, etc.
var changeHistory = pdfDocument.validateChangeHistory()Scan the document and establish which glyphs are used from each font, next rewrite the font files such that they only contain the used glyphs. By removing unused glyphs the size of the font files inside the PDF will be reduced.
pdfDocument.subsetFonts()Baking a document changes all the annotations and/or form fields (otherwise known as widgets) in the document into static content. It “bakes” the appearance of the annotations and fields onto the page, before removing the interactive objects so they can no longer be changed.
Effectively this removes the “annotation or “widget” type of these objects, but keeps the appearance of the objects.
boolean) – Whether to bake
annotations or not. Defaults to true.boolean) – Whether to
bake widgets or not. Defaults to true.Enable interpretation of document Javascript actions.
pdfDocument.enableJS()Disable interpretation of document Javascript actions.
pdfDocument.disableJS()Returns whether interpretation of document Javascript actions is supported. Interpretation of Javascript may be disabled at build time.
var jsIsSupported = pdfDocument.isJSSupported()only mutool run
Calls the listener whenever a document Javascript action triggers an event.
At present the only callback the listener will be used for is an alert event.
Object) – The Javascript
listener function.pdfDocument.setJSEventListener({
onAlert: function(message) {
print(message)
}
})only mutool run
Determine if the current PDF is a ZUGFeRD PDF, and, if so, return the profile type in use. Possible return values include: “NOT ZUGFERD”, “COMFORT”, “BASIC”, “EXTENDED”, “BASIC WL”, “MINIMUM”, “XRECHNUNG”, and “UNKNOWN”.
var profile = pdfDocument.zugferdProfile()only mutool run
Determine if the current PDF is a ZUGFeRD PDF, and, if so, return the version of the spec it claims to conform to. Returns 0 for non-zugferd PDFs.
var version = pdfDocument.zugferdVersion()only mutool run
Return a buffer containing the embedded ZUGFeRD XML data from this ZUGFeRD PDF.
var buf = pdfDocument.zugferdXML()