MuPDF & Javascript#

MuPDF can be used in two ways with Javascript as follows:

  • With mutool run.

  • With mupdf.js package for Node and browsers.

Both usages are, in fact, very similar and here we show code samples and the API for both.

APIs generally work for both environments, however if an API is specific to only one usage, then it is marked with the mutool only or wasm only.

Note

  • In the code examples, if you are developing for mutool run then the mupdf prefix is optional.

  • mutool run supports ECMAScript 5 syntax in strict mode, but not ECMAScript 6 and above.

Class A-Z Index#

Matrices and Rectangles#

These objects are not instantiated as such. All dimensions are in points unless otherwise specified.

Matrices#

Matrices are simply 6-element arrays representing a 3-by-3 transformation matrix as:

/ a b 0 \
| c d 0 |
\ e f 1 /

This matrix is represented in JavaScript as [a,b,c,d,e,f].

Matrix#

Properties

identity

The identity matrix, short hand for [1,0,0,1,0,0].

EXAMPLE

var m = mupdf.Matrix.identity;

Methods

scale(sx, sy)#

Returns a scaling matrix, short hand for [sx,0,0,sy,0,0].

Arguments
  • sx – X scale as a floating point number.

  • sy – Y scale as a floating point number.

Returns

[a,b,c,d,e,f].

EXAMPLE

var m = mupdf.Matrix.scale(2,2);
translate(tx, ty)#

Return a translation matrix, short hand for [1,0,0,1,tx,ty].

Arguments
  • tx – X translation as a floating point number.

  • ty – Y translation as a floating point number.

Returns

[a,b,c,d,e,f].

EXAMPLE

var m = mupdf.Matrix.translate(2,2);
rotate(theta)#

Return a rotation matrix, short hand for [cos(theta),sin(theta),-sin(theta),cos(theta),0,0].

Arguments
  • theta – Rotation value.

Returns

[a,b,c,d,e,f].

EXAMPLE

var m = mupdf.Matrix.rotate(90);
concat(a, b)#

Concatenate matrices a and b. Bear in mind that matrix multiplication is not commutative.

Arguments
  • a – Matrix “a”.

  • b – Matrix “b”.

Returns

[a,b,c,d,e,f].

EXAMPLE

var m = mupdf.Matrix.concat([1,1,1,1,1,1], [2,2,2,2,2,2]);
invert(matrix)#

Inverts the supplied matrix and returns the result.

Arguments
  • matrix – Matrix array.

Returns

[a,b,c,d,e,f].

EXAMPLE

var m = mupdf.Matrix.invert([1,0.5,1,1,1,1]);

Rectangles#

Rectangles are 4-element arrays, specifying the minimum and maximum corners (typically upper left and lower right, in a coordinate space with the origin at the top left with descending y): [ulx,uly,lrx,lry]. Rectangles are always X- and Y-axis aligned.

If the minimum x coordinate is bigger than the maximum x coordinate, MuPDF treats the rectangle as infinite in size.

Rect#

Methods

isEmpty(rect)#

Returns a boolean indicating if the rectangle is empty or not.

Arguments
  • rect – Rectangle array.

Returns

Boolean.

EXAMPLE

var isEmpty = mupdf.Rect.isEmpty([0,0,0,0]); // true
var isEmpty = mupdf.Rect.isEmpty([0,0,100,100]); // false
isValid(rect)#

Returns a boolean indicating if the rectangle is valid or not. Rectangles are considered “invalid” if lrx < ulx and/or if lry < uly.

Arguments
  • rect – Rectangle array.

Returns

Boolean.

EXAMPLE

var isValid = mupdf.Rect.isValid([0,0,100,100]); // true
var isValid = mupdf.Rect.isValid([0,0,-100,100]); // false
isInfinite(rect)#

Returns a boolean indicating if the rectangle is infinite or not.

Arguments
  • rect – Rectangle array.

Returns

Boolean.

EXAMPLE

var isInfinite = mupdf.Rect.isInfinite([0x80000000,0x80000000,0x7fffff80,0x7fffff80]); //true
var isInfinite = mupdf.Rect.isInfinite([0,0,100,100]); // false
transform(rect, matrix)#

Returns a rectangle generated by transforming the supplied rect by the matrix.

Arguments
  • rect – Rectangle array.

  • matrix – Matrix array.

Returns

[ulx,uly,lrx,lry].

EXAMPLE

var m = mupdf.Rect.transform([0,0,100,100], [1,0.5,1,1,1,1]);

Colors#

Colors are specified as arrays with the appropriate number of components for the color space. Each number is a floating point between 0 and 1 for the component value.

Therefore colors are represented as an array of up to 4 component values.

For example:

  • In the DeviceCMYK color space a color would be [Cyan,Magenta,Yellow,Black]. A full magenta color would therefore be [0,1,0,0].

  • In the DeviceRGB color space a color would be [Red,Green,Blue]. A full green color would therefore be [0,1,0].

  • In the DeviceGray color space a color would be [Black]. A full black color would therefore be [0].

Color parameters#

mutool only

This object is a dictionary with keys for:

renderingIntent

Either of “Perceptual”, “RelativeColorimetric”, “Saturation” or “AbsoluteColorimetric”.

blackPointCompensation

True if black point compensation is activated.

overPrinting

True if overprint is activated.

overPrintMode

The overprint mode. Can be either 0 or 1.

Alpha#

Alpha values are floats between 0 and 1, whereby 0 denotes full transparency & 1 denotes full opacity.


Object Protocols#

The following objects are standard JavaScript objects with assumed properties (i.e. they follow their outlined protocol). They are used throughout the mutool API to support object types for various methods.

File Specification Object#

This object is used to represent a file.

In order to retrieve information from this object see methods described within Embedded files in PDFs.

Embedded File Params Object#

Historical equivalent to Filespec Params Object. This Object contains metadata about a filespec, it has properties for:

filename

The name of the embedded file.

mimetype

The MIME type of the embedded file, or undefined if none exists.

size

The size in bytes of the embedded file contents.

creationDate

The creation date of the embedded file.

modificationDate

The modification date of the embedded file.

Filespec Params Object#

This Object contains metadata about a filespec, it has properties for:

filename

The name of the embedded file.

mimetype

The MIME type of the embedded file, or undefined if none exists.

size

The size in bytes of the embedded file contents.

creationDate

The creation date of the embedded file.

modificationDate

The modification date of the embedded file.

PDF Journal Object#

This Object contains a numbered array of operations and a reference into this list indicating the current position.

position

The current position in the journal.

steps

An array containing the name of each step in the journal.

Stroking State Object#

The stroking state is a dictionary with keys for:

  • startCap, dashCap, endCap

    “Butt”, “Round”, “Square”, or “Triangle”.

  • lineCap

    Set startCap, dashCap, and endCap all at once.

  • lineJoin

    “Miter”, “Round”, “Bevel”, or “MiterXPS”.

  • lineWidth

    Thickness of the line.

  • miterLimit

    Maximum ratio of the miter length to line width, before beveling the join instead.

  • dashPhase

    Starting offset for dash pattern.

  • dashes

    Array of on/off dash lengths.

EXAMPLE

{dashes:[5,10], lineWidth:3, lineCap:'Round'}

Outline Iterator Object#

This Object has properties for:

title

The title of the item.

uri

A URI pointing to the destination. Likely to be a document internal link that can be resolved by Document.resolveLink(), otherwise a link to a web page.

open

True if the item should be opened when shown in a tree view.

Text Layout Object#

A description of layouted text value from a text widget with keys:

matrix

Normal transform matrix for the layouted text.

invMatrix

Inverted transform matrix for the layouted text.

lines

An array of text lines belonging to the layouted text, a lines object contains:

  • x The X coordinate for the text line.

  • y The Y coordinate for the text line.

  • fontSize The text size used for the layouted text line.

  • index The index of the beginning of the line in the text string.

  • rect The bounding rectangle for the text line.

  • chars An array of characters in the text line.

    A chars object contains:

    • x The position of the character.

    • advance The advance of the character.

    • index The index of the character in the text string.

    • rect The bounding Rectangle for the character.

Signature Configuration Object#

A signature configuration object has properties with Boolean values as follows:

showLabels

Whether to include both labels and values or just values on the right hand side.

showDN

Whether to include the distinguished name on the right hand side.

showTextName

Whether to include the name of the signatory on the right hand side.

showDate

Whether to include the date of signing on the right hand side.

showGraphicName

Whether to include the signatory name on the left hand side.

showLogo

Whether to include the MuPDF logo in the background.

Placement Result Object#

filled

The rectangle of the actual area that was used.

more

True if more content remains to be placed, otherwise false if all content fits in the Story.

Default Appearance Text Object#

font

String representing the font.

size

Integer representing the size of the font.

color

Array representing the color value.


Buffer#

Buffer objects are used for working with binary data. They can be used much like arrays, but are much more efficient since they only store bytes.

new Buffer()#

Constructor method.

Create a new empty buffer.

Returns

Buffer.

EXAMPLE

var buffer = new mupdf.Buffer();
new Buffer(original)#

Constructor method.

Create a new buffer with a copy of the data from the original buffer.

Arguments
  • originalBuffer.

Returns

Buffer.

EXAMPLE

var buffer = new mupdf.Buffer(buffer);
readFile(fileName)#

mutool only

Constructor method.

Create a new buffer with the contents of a file.

Arguments
  • fileName – The path to the file to read.

Returns

Buffer.

EXAMPLE

var buffer = mupdf.readFile("my_file.pdf");

Instance properties

length

mutool only

The number of bytes in the buffer. Read-only.

[n]

mutool only

Read/write the byte at index ‘n’. Will throw exceptions on out of bounds accesses.

EXAMPLE

var byte = buffer[0];

Instance methods

getLength()#

wasm only

Returns the number of bytes in the buffer. Read-only.

Returns

Integer.

EXAMPLE

var length = buffer.getLength();
writeByte(b)#

Append a single byte to the end of the buffer.

Arguments
  • b – The byte value. Only the least significant 8 bits of the value are appended to the buffer.

EXAMPLE

buffer.writeByte(0x2a);
readByte(at)#

wasm only

Read the byte at the supplied index.

Arguments
  • atInteger.

EXAMPLE

buffer.readByte(0);
writeRune(c)#

mutool only

Encode a unicode character as UTF-8 and append to the end of the buffer.

Arguments
  • c – The character unicode codepoint.

EXAMPLE

buffer.writeRune(0x4f60); // To append U+4f60
buffer.writeRune(0x597d); // To append U+597d
buffer.writeRune(0xff01); // To append U+ff01
writeLine(...)#

Append arguments to the end of the buffer, separated by spaces, ending with a newline.

Arguments
  • ... – List of arguments.

EXAMPLE

buffer.writeLine("a line");
write(...)#

Append arguments to the end of the buffer, separated by spaces.

Arguments
  • ... – List of arguments.

EXAMPLE

buffer.write("hello", "world");
writeBuffer(data)#

Append the contents of the data buffer to the end of the buffer.

Arguments
  • data – Data buffer.

EXAMPLE

buffer.writeBuffer(anotherBuffer);
slice(start end)#

Create a new buffer containing a (subset of) the data in this buffer. Start and end are offsets from the beginning of this buffer, and if negative from the end of this buffer.

Arguments
  • start – Start index.

  • end – End index.

Returns

Buffer.

EXAMPLE

var buffer = new Buffer();
buffer.write("hello", "world"); // buffer contains "hello world"
var newBuffer = buffer.slice(1, -1); // newBuffer contains "ello worl"
save(fileName)#

mutool only

Write the contents of the buffer to a file.

Arguments
  • fileName – Filename to save to.

EXAMPLE

buffer.save("my_buffer_filename");
asUint8Array()#

wasm only

Returns the buffer as a Uint8Array.

Returns

Uint8Array.

EXAMPLE

var arr = buffer.asUint8Array();
asString()#

wasm only

Returns the buffer as a String.

Returns

String.

EXAMPLE

var str = buffer.asString();

Document#

MuPDF can open many document types (PDF, XPS, CBZ, EPUB, FB2 and a handful of image formats).

new Document.openDocument(fileName, fileType)#

Constructor method.

Open the named document.

Arguments
  • fileName – File name to open.

  • fileType – File type.

Returns

Document.

EXAMPLE

var document = new mupdf.Document.openDocument("my_pdf.pdf", "application/pdf");

Instance methods

needsPassword()#

Returns true if a password is required to open a password protected PDF.

Returns

Boolean.

EXAMPLE

var needsPassword = document.needsPassword();
authenticatePassword(password)#

Returns a bitfield value against the password authentication result.

Arguments
  • password – The password to attempt authentication with.

Returns

Integer.

Bitfield value

Description

0

Failed

1

No password needed

2

Is User password and is okay

4

Is Owner password and is okay

6

Is both User & Owner password and is okay

EXAMPLE

var auth = document.authenticatePassword("abracadabra");
hasPermission(permission)#

Returns true if the document has permission for the supplied permission String parameter.

Arguments
  • permissionString The permission to seek for, e.g. “edit”.

Returns

Boolean.

String

Description

print

Can print

edit

Can edit

copy

Can copy

annotate

Can annotate

form

Can fill out forms

accessibility

Can copy for accessibility

assemble

Can manage document pages

print-hq

Can print high-quality

EXAMPLE

var canEdit = document.hasPermission("edit");
getMetaData(key)#

Return various meta data information. The common keys are: format, encryption, info:ModDate, and info:Title.

Arguments
  • keyString.

Returns

String.

EXAMPLE

var format = document.getMetaData("format");
var modificationDate = doc.getMetaData("info:ModDate");
var author = doc.getMetaData("info:Author");
setMetaData(key, value)#

Set document meta data information field to a new value.

Arguments
  • keyString.

  • valueString.

EXAMPLE

document.setMetaData("info:Author", "My Name");
isReflowable()#

Returns true if the document is reflowable, such as EPUB, FB2 or XHTML.

Returns

Boolean.

EXAMPLE

var isReflowable = document.isReflowable();

Note

This will always return false in the WASM context as there is no HTML/EPUB support in WASM.

layout(pageWidth, pageHeight, fontSize)#

Layout a reflowable document (EPUB, FB2, or XHTML) to fit the specified page and font size.

Arguments
  • pageWidthInt.

  • pageHeightInt.

  • fontSizeInt.

EXAMPLE

document.layout(300,300,16);
countPages()#

Count the number of pages in the document. This may change if you call the layout function with different parameters.

Returns

Int.

EXAMPLE

var numPages = document.countPages();
loadPage(number)#

Returns a Page (or PDFPage) object for the given page number. Page number zero (0) is the first page in the document.

Returns

Page or PDFPage.

EXAMPLE

var page = document.loadPage(0); // loads the 1st page of the document
loadOutline()#

Returns an array with the outline (also known as “table of contents” or “bookmarks”). In the array is an object for each heading with the property ‘title’, and a property ‘page’ containing the page number. If the object has a ‘down’ property, it contains an array with all the sub-headings for that entry.

Returns

[...].

EXAMPLE

var outline = document.loadOutline();
outlineIterator()#

Returns an OutlineIterator for the document outline.

Returns

OutlineIterator.

EXAMPLE

var obj = document.outlineIterator();

Resolve a document internal link URI to a page index.

Arguments
  • uriString.

Returns

Integer.

EXAMPLE

var pageNumber = document.resolveLink(my_link);
resolveLinkDestination(uri)#

Resolve a document internal link URI to a link destination.

Arguments
  • uriString.

Returns

Link destination.

EXAMPLE

var linkDestination = document.resolveLinkDestination(uri);
isPDF()#

Returns true if the document is a PDF document.

Returns

Boolean.

EXAMPLE

var isPDF = document.isPDF();
asPDF()#

Returns a pdf version of the document (if possible). PDF documents return the same object. Documents that have an underlying PDF representation return that. Other document types return null.

Returns

PDFDocument.

EXAMPLE

var asPDF = document.asPDF();
formatLinkURI(linkDestination)#

Format a document internal link destination object to a URI string suitable for createLink().

Arguments
Returns

String.

EXAMPLE

var uri = document.formatLinkURI({chapter:0, page:42,
        type:"FitV", x:0, y:0, width:100, height:50, zoom:1});
document.createLink([0,0,100,100], uri);

Page#

The base class for a PDF Page.

Instance methods

getBounds()#

Returns a rectangle containing the page dimensions.

Returns

[ulx,uly,lrx,lry].

EXAMPLE

var rect = page.getBounds();
run(device, matrix)#

Calls device functions for all the contents on the page, using the specified transform matrix. The device can be one of the built-in devices or a JavaScript object with methods for the device calls. The matrix maps from user space points to device space pixels.

Arguments
  • device – The device object.

  • matrix[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

page.run(obj, mupdf.Matrix.identity);
runPageContents(device, matrix)#

This is the same as the run method above but it only considers the page itself and omits annotations and widgets.

Arguments
  • device – The device object.

  • matrix[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

page.runPageContents(obj, mupdf.Matrix.identity);
runPageAnnots(device, matrix)#

This is the same as the run method above but it only considers the page annotations.

Arguments
  • device – The device object.

  • matrix[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

page.runPageAnnots(obj, mupdf.Matrix.identity);
runPageWidgets(device, matrix)#

This is the same as the run method above but it only considers the page widgets.

Arguments
  • device – The device object.

  • matrix[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

page.runPageWidgets(obj, mupdf.Matrix.identity);
toPixmap(matrix, colorspace, alpha, showExtras)#

Render the page into a Pixmap, using the specified transform matrix and colorspace. If alpha is true, the page will be drawn on a transparent background, otherwise white. If showExtras is true then the operation will include any page annotations and/or widgets.

Arguments
  • matrix[a,b,c,d,e,f]. The transform matrix.

  • colorspaceColorSpace.

  • alphaBoolean.

  • showExtrasBoolean.

Returns

Pixmap.

Note

In MuPDF WASM alpha & showExtras default to true unless otherwise specified. In mutool run alpha defaults to false and showExtras defaults to true unless otherwise specified.

EXAMPLE

var pixmap = page.toPixmap(mupdf.Matrix.identity, mupdf.ColorSpace.DeviceRGB, true, true);
toDisplayList(showExtras)#

Record the contents on the page into a DisplayList. If showExtras is true then the operation will include any page annotations and/or widgets.

Arguments
  • showExtrasBoolean.

Returns

DisplayList.

Note

In both MuPDF WASM and mutool run showExtras defaults to true unless otherwise specified.

EXAMPLE

var displayList = page.toDisplayList(true);
toStructuredText(options)#

Extract the text on the page into a StructuredText object. The options argument is a comma separated list of flags: “preserve-ligatures”, “preserve-whitespace”, “preserve-spans”, “preserve-images”, “inhibit-spaces”, “dehyphenate”, “structured”, “use-cid-for-unknown-unicode”, and “ignore-actualtext”.

Arguments
  • optionsString.

Returns

StructuredText.

EXAMPLE

var sText = page.toStructuredText("preserve-whitespace");

Search the page text for all instances of the needle value, and return an array of search hits. Each search hit is an array of rectangles corresponding to all characters in the search hit.

Arguments
  • needleString.

  • max_hitsInteger Defaults to 500 unless otherwise specified.

Returns

[...].

EXAMPLE

var results = page.search("my search phrase");

Note

The numbers are [ulx, uly, urx, ury, llx, lly, lrx, lry] for each rectangle against each result. These type of rectangles are know as “Quads” or “QuadPoints” in the PDF specification.

Return an array of all the links on the page. Each link is an object with a ‘bounds’ property, and either a ‘page’ or ‘uri’ property, depending on whether it’s an internal or external link. See: Link.

Returns

[...].

var links = page.getLinks();
var link = links[0];
var linkDestination = doc.resolveLink(link)

Note

If there are no links then an empty array is returned.

Create a new link within the rectangle on the page, linking to the destination URI string.

Arguments
  • rectRectangle for the link.

  • destinationUriString containing URI.

Returns

Link.

EXAMPLE

var link = page.createLink([0,0,100,100], "https://example.com");

Delete the link from the page.

Arguments

EXAMPLE

page.deleteLink(link_obj);
getLabel()#

Returns the page number as a string using the numbering scheme of the document.

Returns

String.

EXAMPLE

var label = page.getLabel();
isPDF()#

Returns true if the page is from a PDF document.

Returns

Boolean.

EXAMPLE

var isPDF = page.isPDF();

Note

As PDFPage extends Page this method will return false. It is only if we actually have an instance of a PDFPage when this method is overridden to return true.


StructuredText#

StructuredText objects hold text from a page that has been analyzed and grouped into blocks, lines and spans. To obtain a StructuredText instance use Page toStructuredText().

Instance methods

search(needle)#

Search the text for all instances of needle, and return an array with all matches found on the page.

Each match in the result is an array containing one or more QuadPoints that cover the matching text.

Arguments
  • needleString.

Returns

[...].

EXAMPLE

var result = sText.search("Hello World!");
highlight(p, q)#

Return an array with rectangles needed to highlight a selection defined by the start and end points.

Arguments
  • p – Start point in format [x,y].

  • q – End point in format [x,y].

Returns

[...].

EXAMPLE

var result = sText.highlight([100,100], [200,100]);
copy(p, q)#

Return the text from the selection defined by the start and end points.

Arguments
  • p – Start point in format [x,y].

  • q – End point in format [x,y].

Returns

String.

EXAMPLE

var result = sText.copy([100,100], [200,100]);
walk(walker)#

wasm only

Arguments
  • walker – Function with protocol methods, see example below for details.

Walk through the blocks (images or text blocks) of the structured text. For each text block walk over its lines of text, and for each line each of its characters. For each block, line or character the walker will have a method called.

EXAMPLE

var stext = pdfPage.toStructuredText();
stext.walk({
    beginLine: function (bbox, wmode, direction) {
        console.log("beginLine", bbox, wmode, direction);
    },
    beginTextBlock: function (bbox) {
        console.log("beginTextBlock", bbox);
    },
    endLine: function () {
        console.log("endLine");
    },
    endTextBlock: function () {
        console.log("endTextBlock");
    },
    onChar: function (utf, origin, font, size, quad, color) {
        console.log("onChar", utf, origin, font, size, quad, color);
    },
    onImageBlock: function (bbox, transform, image) {
        console.log("onImageBlock", bbox, transform, image);
    },
});

Note

On beginLine the direction parameter is a vector (e.g. [0, 1]) and can you can calculate the rotation as an angle with some trigonometry on the vector.

asJSON(scale)#

wasm only

Returns the instance in JSON format.

Arguments
  • scaleFloat Default: 1. Multiply all the coordinates by this factor to get the coordinates at another resolution. The structured text has all coordinates in points (72 DPI), however you may want to use the coordinates in the StructuredText data at another resolution.

Returns

String.

EXAMPLE

var json = sText.asJSON();

Note

If you want the coordinates to be 300 DPI then pass (300/72) as the scale parameter.


ColorSpace#

Properties

DeviceGray

The default grayscale colorspace.

DeviceRGB

The default RGB colorspace.

DeviceBGR

The default RGB colorspace, but with components in reverse order.

DeviceCMYK

The default CMYK colorspace.

DeviceLab

The default Lab colorspace.

Methods

new ColorSpace(from, name)#

wasm only

Constructor method.

Create a new ColorSpace.

Arguments
  • from – A buffer containing an ICC profile.

  • name – A user descriptive name.

Returns

ColorSpace.

EXAMPLE

var icc_colorspace = new mupdf.ColorSpace(fs.readFileSync("SWOP.icc"), "SWOP");
getNumberOfComponents()#

A grayscale colorspace has one component, RGB has 3, CMYK has 4, and DeviceN may have any number of components.

EXAMPLE

var cs = mupdf.ColorSpace.DeviceRGB;
var num = cs.getNumberOfComponents(); // 3
toString()#

Return name of ColorSpace.

Returns

String.

var cs = mupdf.ColorSpace.DeviceRGB;
var num = cs.toString(); // "DeviceRGB"
isGray()#

Returns true if the object is a gray color space.

Returns

Boolean.

var bool = colorSpace.isGray();
isRGB()#

Returns true if the object is an RGB color space.

Returns

Boolean.

var bool = colorSpace.isRGB();
isCMYK()#

Returns true if the object is a CMYK color space.

Returns

Boolean.

var bool = colorSpace.isCMYK();
isIndexed()#

Returns true if the object is an Indexed color space.

Returns

Boolean.

var bool = colorSpace.isIndexed();
isLab()#

Returns true if the object is a Lab color space.

Returns

Boolean.

var bool = colorSpace.isLab();
isDeviceN()#

Returns true if the object is a Device N color space.

Returns

Boolean.

var bool = colorSpace.isDeviceN();
isSubtractive()#

Returns true if the object is a subtractive color space.

Returns

Boolean.

var bool = colorSpace.isSubtractive();
getType()#

Returns a string indicating the type.

Returns

String One of “None”, “Gray”, “RGB”, “BGR”, “CMYK”, “Lab”, “Indexed”, “Separation”.

DefaultColorSpaces#

DefaultColorSpaces is an object with keys for:

getDefaultGray()#

Get the default gray colorspace.

Returns

ColorSpace.

getDefaultRGB()#

Get the default RGB colorspace.

Returns

ColorSpace.

getDefaultCMYK()#

Get the default CMYK colorspace.

Returns

ColorSpace.

getOutputIntent()#

Get the output intent.

Returns

ColorSpace.

setDefaultGray(colorspace)#
Arguments
  • colorspaceColorSpace.

setDefaultRGB(colorspace)#
Arguments
  • colorspaceColorSpace.

setDefaultCMYK(colorspace)#
Arguments
  • colorspaceColorSpace.

setOutputIntent(colorspace)#
Arguments
  • colorspaceColorSpace.


Pixmap#

A Pixmap object contains a color raster image (short for pixel map). The components in a pixel in the Pixmap are all byte values, with the transparency as the last component. A Pixmap also has a location (x, y) in addition to its size; so that they can easily be used to represent tiles of a page.

new Pixmap(colorspace, bounds, alpha)#

Constructor method.

Create a new pixmap. The pixel data is not initialized; and will contain garbage.

Arguments
  • colorspaceColorSpace.

  • bounds[ulx,uly,lrx,lry] Rectangle.

  • alphaBoolean.

Returns

Pixmap.

EXAMPLE

var pixmap = new mupdf.Pixmap(mupdf.ColorSpace.DeviceRGB, [0,0,100,100], true);

Instance methods

clear(value)#

Clear the pixels to the specified value. Pass 255 for white, or omit for transparent.

Arguments
  • value – Pixel value.

EXAMPLE

pixmap.clear(255);
pixmap.clear();
getBounds()#

Return the pixmap bounds.

Returns

[ulx,uly,lrx,lry] Rectangle.

EXAMPLE

var rect = pixmap.getBounds();
getWidth()#
Returns

Int The width value.

EXAMPLE

var w = pixmap.getWidth();
getHeight()#
Returns

Int The height value.

EXAMPLE

var h = pixmap.getHeight();
getNumberOfComponents()#

Number of colors; plus one if an alpha channel is present.

Returns

Int Number of color components.

EXAMPLE

var num = pixmap.getNumberOfComponents();
getAlpha()#

True if alpha channel is present.

Returns

Boolean.

EXAMPLE

var alpha = pixmap.getAlpha();
getStride()#

Number of bytes per row.

Returns

Int.

EXAMPLE

var stride = pixmap.getStride();
getColorSpace()#

Returns the ColorSpace for the Pixmap.

Returns

ColorSpace.

EXAMPLE

var cs = pixmap.getColorSpace();
setResolution(xRes, yRes)#

Set x & y resolution.

Arguments
  • xResInt X resolution in dots per inch.

  • yResInt Y resolution in dots per inch.

EXAMPLE

pixmap.setResolution(300, 300);
getXResolution()#

Returns the x resolution for the Pixmap.

Returns

Int Resolution in dots per inch.

EXAMPLE

var xRes = pixmap.getXResolution();
getYResolution()#

Returns the y resolution for the Pixmap.

Returns

Int Resolution in dots per inch.

EXAMPLE

var yRes = pixmap.getYResolution();
getSample(x, y, index)#

mutool only

Get the value of component index at position x, y (relative to the image origin: 0, 0 is the top left pixel).

Arguments
  • x – X co-ordinate.

  • y – Y co-ordinate.

  • index – Component index. i.e. For CMYK ColorSpaces 0 = Cyan, for RGB 0 = Red etc.

Returns

Int.

EXAMPLE

var sample = pixmap.getSample(0,0,0);
saveAsPNG(fileName)#

mutool only

Save the Pixmap as a PNG. Only works for Gray and RGB images.

Arguments
  • fileNameString.

EXAMPLE

pixmap.saveAsPNG("fileName.png");
saveAsJPEG(fileName, quality)#

mutool only

Save the Pixmap as a JPEG. Only works for Gray, RGB and CMYK images.

Arguments
  • fileNameString.

  • qualityInt.

EXAMPLE

pixmap.saveAsJPEG("fileName.jpg", 80);
saveAsPAM(fileName)#

mutool only

Save the Pixmap as a PAM.

Arguments
  • fileNameString.

EXAMPLE

pixmap.saveAsPAM("fileName.pam");
saveAsPNM(fileName)#

mutool only

Save the Pixmap as a PNM. Only works for Gray and RGB images without alpha.

Arguments
  • fileNameString.

EXAMPLE

pixmap.saveAsPNM("fileName.pnm");
saveAsPBM(fileName)#

mutool only

Save the Pixmap as a PBM. Only works for Gray and RGB images without alpha.

Arguments
  • fileNameString.

EXAMPLE

pixmap.saveAsPBM("fileName.pbm");
saveAsPKM(fileName)#

mutool only

Save the Pixmap as a PKM. Only works for Gray and RGB images without alpha.

Arguments
  • fileNameString.

EXAMPLE

pixmap.saveAsPKM("fileName.pkm");
invert()#

Invert all pixels. All components are processed, except alpha which is unchanged.

EXAMPLE

pixmap.invert();
invertLuminance()#

Transform all pixels so that luminance of each pixel is inverted, and the chrominance remains as unchanged as possible. All components are processed, except alpha which is unchanged.

EXAMPLE

pixmap.invertLuminance();
gamma(gamma)#

Apply gamma correction to Pixmap. All components are processed, except alpha which is unchanged.

Values >= 0.1 & < 1 = darken, > 1 & < 10 = lighten.

Arguments
  • gammaFloat.

EXAMPLE

pixmap.gamma(3);
tint(black, white)#
Tint all pixels in a RGB, BGR or Gray Pixmap.

Map black and white respectively to the given hex RGB values.

Arguments
  • blackInteger.

  • whiteInteger.

EXAMPLE

pixmap.tint(0xffff00, 0xffff00);
warp(points, width, height)#

Return a warped subsection of the Pixmap, where the result has the requested dimensions.

Arguments
  • points[x0, y0, x1, y1, x2, y2, x3, y3, x4, y4]

Points give the corner points of a convex quadrilateral within the Pixmap to be warped. :arg width: Int. :arg height: Int.

Returns

Pixmap.

EXAMPLE

var warpedPixmap = pixmap.warp([0,0,100,0,0,100,100,100],200,200);
convertToColorSpace(colorspace, proof, defaultColorSpaces, colorParams, keepAlpha)#

Convert pixmap into a new pixmap of a desired colorspace. A proofing colorspace, a set of default colorspaces and color parameters used during conversion may be specified. Finally a boolean indicates if alpha should be preserved (default is to not preserve alpha).

Arguments
  • colorspaceColorspace.

  • proofColorspace.

  • defaultColorSpacesDefaultColorSpaces.

  • colorParams[].

  • keepAlphaBoolean.

Returns

Pixmap.

getPixels()#

wasm only

Returns an array of pixels for the Pixmap.

Returns

[...].

EXAMPLE

var pixels = pixmap.getPixels();
asPNG()#

wasm only

Returns a buffer of the Pixmap as a PNG.

Returns

Buffer.

EXAMPLE

var buffer = pixmap.asPNG();
asPSD()#

wasm only

Returns a buffer of the Pixmap as a PSD.

Returns

Buffer.

EXAMPLE

var buffer = pixmap.asPSD();
asPAM()#

wasm only

Returns a buffer of the Pixmap as a PAM.

Returns

Buffer.

EXAMPLE

var buffer = pixmap.asPAM();
asJPEG(quality)#

wasm only

Returns a buffer of the Pixmap as a JPEG. Note, if the Pixmap has an alpha channel then an exception will be thrown.

Returns

Buffer.

EXAMPLE

var buffer = pixmap.asJPEG(80);
skewDetect()#

wasm only

Returns the angle of skew detected from Pixmap. Note, if the Pixmap is not Greyscale with no alpha then an exception will be thrown.

Returns

Float.

EXAMPLE

var angle = pixmap.skewDetect();
deskew(angle, border)#

wasm only

Returns a new Pixmap being the deskewed version of the supplied Pixmap. Note, if a Pixmap is supplied that is not RGB or Greyscale, or has alpha then an exception will be thrown.

Arguments
  • angleFloat. The angle to deskew.

  • borderString. “increase” increases the size of the pixmap so no pixels are lost. “maintain” maintains the size of the pixmap. “decrease” decreases the size of the page so no new pixels are shown.

Returns

Pixmap.

EXAMPLE

var deskewed = pixmap.deskew(angle, 0);

DrawDevice#

The DrawDevice can be used to render to a Pixmap; either by running a Page with it or by calling its methods directly.

new DrawDevice(transform, pixmap)#

Constructor method.

Create a device for drawing into a Pixmap. The Pixmap bounds used should match the transformed page bounds, or you can adjust them to only draw a part of the page.

Arguments
  • transform[a,b,c,d,e,f]. The transform matrix.

  • pixmapPixmap.

Returns

DrawDevice.

EXAMPLE

var drawDevice = new mupdf.DrawDevice(mupdf.Matrix.identity, pixmap);

DisplayList#

A display list records all the device calls for playback later. If you want to run a page through several devices, or run it multiple times for any other reason, recording the page to a display list and replaying the display list may be a performance gain since then you can avoid reinterpreting the page each time. Be aware though, that a display list will keep all the graphics required in memory, so will increase the amount of memory required.

new DisplayList(mediabox)#

Constructor method.

Create an empty display list. The mediabox rectangle should be the bounds of the page.

Arguments
Returns

DisplayList.

EXAMPLE

var displayList = new mupdf.DisplayList([0,0,100,100]);

Instance methods

run(device, transform)#

Play back the recorded device calls onto the device.

Arguments
  • deviceDevice.

  • transform[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

displayList.run(device, mupdf.Matrix.identity);
getBounds()#

Returns a rectangle containing the dimensions of the display list contents.

Returns

[ulx,uly,lrx,lry] Rectangle.

EXAMPLE

var bounds = displayList.getBounds();
toPixmap(transform, colorspace, alpha)#

Render display list to a Pixmap.

Arguments
  • transform[a,b,c,d,e,f]. The transform matrix.

  • colorspaceColorSpace.

  • alphaBoolean. If alpha is true, a transparent background, otherwise white.

Returns

Pixmap.

EXAMPLE

var pixmap = displayList.toPixmap(mupdf.Matrix.identity, mupdf.ColorSpace.DeviceRGB, false);
toStructuredText(options)#

Extract the text on the page into a StructuredText object. The options argument is a comma separated list of flags: “preserve-ligatures”, “preserve-whitespace”, “preserve-spans”, and “preserve-images”.

Arguments
  • optionsString.

Returns

StructuredText.

EXAMPLE

var sText = displayList.toStructuredText("preserve-whitespace");
search(needle, max_hits)#

Search the display list text for all instances of the needle value, and return an array of search hits. Each search hit is an array of rectangles corresponding to all characters in the search hit.

Arguments
  • needleString.

  • max_hitsInteger Use to limit number of results, defaults to 500.

Returns

[ [ Quad, Quad, ... ], [ Quad, Quad, ...], ... ].

EXAMPLE

var results = displayList.search("my search phrase");

DisplayListDevice#

new DisplayListDevice(displayList)#

Constructor method.

Create a device for recording onto a display list.

Arguments
  • displayListDisplayList.

Returns

DisplayListDevice.

EXAMPLE

var my_display_list = new mupdf.DisplayList([0,0,100,100]);
console.log("my_display_list="+my_display_list);
var displayListDevice = new mupdf.DisplayListDevice(my_display_list);

Device#

All built-in devices have the methods listed below. Any function that accepts a device will also accept a JavaScript object with the same methods. Any missing methods are simply ignored, so you only need to create methods for the device calls you care about.

Many of the methods take graphics objects as arguments: Path, Text, Image and Shade.

Colors are specified as arrays with the appropriate number of components for the color space.

The methods that clip graphics must be balanced with a corresponding popClip.

Instance methods

fillPath(path, evenOdd, transform, colorspace, color, alpha, colorParams)#

Fill a path.

Arguments

EXAMPLE

device.fillPath(path, false, mupdf.Matrix.identity, mupdf.ColorSpace.DeviceRGB, [1,0,0], true);
strokePath(path, stroke, transform, colorspace, color, alpha, colorParams)#

Stroke a path.

Arguments

EXAMPLE

device.strokePath(path,
                  {dashes:[5,10], lineWidth:3, lineCap:'Round'},
                  mupdf.Matrix.identity,
                  mupdf.ColorSpace.DeviceRGB,
                  [0,1,0],
                  0.5);
clipPath(path, evenOdd, transform)#

Clip a path.

Arguments
  • pathPath object.

  • evenOdd – The even odd rule to use.

  • transform[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

device.clipPath(path, true, mupdf.Matrix.identity);
clipStrokePath(path, stroke, transform)#

Clip & stroke a path.

Arguments

EXAMPLE

device.clipStrokePath(path, true, mupdf.Matrix.identity);
fillText(text, transform, colorspace, color, alpha, colorParams)#

Fill a text object.

Arguments

EXAMPLE

device.fillText(text, mupdf.Matrix.identity, mupdf.ColorSpace.DeviceRGB, [1,0,0], 1);
strokeText(text, stroke, transform, colorspace, color, alpha, colorParams)#

Stroke a text object.

Arguments

EXAMPLE

device.strokeText(text,
                  {dashes:[5,10], lineWidth:3, lineCap:'Round'},
                  mupdf.Matrix.identity, mupdf.ColorSpace.DeviceRGB,
                  [1,0,0],
                  1);
clipText(text, transform)#

Clip a text object.

Arguments
  • textText object.

  • transform[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

device.clipText(text, mupdf.Matrix.identity);
clipStrokeText(text, stroke, transform)#

Clip & stroke a text object.

Arguments

EXAMPLE

device.clipStrokeText(text, {dashes:[5,10], lineWidth:3, lineCap:'Round'},  mupdf.Matrix.identity);
ignoreText(text, transform)#

Invisible text that can be searched but should not be visible, such as for overlaying a scanned OCR image.

Arguments
  • textText object.

  • transform[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

device.ignoreText(text, mupdf.Matrix.identity);
fillShade(shade, transform, alpha, colorParams)#

Fill a shade (a.k.a. gradient).

Note

The details of gradient fills are not exposed to JavaScript yet.

Arguments

EXAMPLE

device.fillShade(shade, mupdf.Matrix.identity, true, {overPrinting:true});
fillImage(image, transform, alpha, colorParams)#

Draw an image. An image always fills a unit rectangle [0,0,1,1], so must be transformed to be placed and drawn at the appropriate size.

Arguments

EXAMPLE

device.fillImage(image, mupdf.Matrix.identity, false, {overPrinting:true});
fillImageMask(image, transform, colorspace, color, alpha, colorParams)#

An image mask is an image without color. Fill with the color where the image is opaque.

Arguments

EXAMPLE

device.fillImageMask(image, mupdf.Matrix.identity, mupdf.ColorSpace.DeviceRGB, 0xff00ff, true, {});
clipImageMask(image, transform)#

Clip graphics using the image to mask the areas to be drawn.

Arguments
  • imageImage object.

  • transform[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

device.clipImageMask(image, mupdf.Matrix.identity);
popClip()#

Pop the clip mask installed by the last clipping operation.

EXAMPLE

device.popClip();
beginMask(area, luminosity, backdropColorspace, backdropColor, backdropAlpha, colorParams)#

Create a soft mask. Any drawing commands between beginMask and endMask are grouped and used as a clip mask.

Arguments
  • areaPath Mask area.

  • luminosityBoolean If luminosity is true, the mask is derived from the luminosity (grayscale value) of the graphics drawn; otherwise the color is ignored completely and the mask is derived from the alpha of the group.

  • backdropColorspace – The ColorSpace.

  • backdropColor – The color value.

  • backdropAlpha – The alpha value.

  • colorParams – The color parameters object.

EXAMPLE

device.beginMask(path, true, mupdf.ColorSpace.DeviceRGB, 0xff00ff, false, {});
endMask()#

Ends the mask.

EXAMPLE

device.endMask();
beginGroup(area, colorspace, isolated, knockout, blendmode, alpha)#

Push/pop a transparency blending group. See the PDF reference for details on isolated and knockout.

Arguments
  • area[ulx,uly,lrx,lry] Rectangle. The blend area.

  • colorspaceColorSpace.

  • isolatedBoolean.

  • knockoutBoolean.

  • blendmode – Blendmode is one of the standard PDF blend modes: “Normal”, “Multiply”, “Screen”, etc.

  • alpha – The alpha value.

_images/isolated-and-knockout.png

EXAMPLE

device.beginGroup([0,0,100,100], mupdf.ColorSpace.DeviceRGB, true, true, "Multiply", 0.5);
endGroup()#

Ends the blending group.

EXAMPLE

device.endGroup();
beginTile(areaRect, viewRect, xStep, yStep, transform, id)#

Draw a tiling pattern. Any drawing commands between beginTile and endTile are grouped and then repeated across the whole page. Apply a clip mask to restrict the pattern to the desired shape.

Arguments
  • areaRect[ulx,uly,lrx,lry] Rectangle.

  • viewRect[ulx,uly,lrx,lry] Rectangle.

  • xStepInteger representing x step.

  • yStepInteger representing y step.

  • transform[a,b,c,d,e,f]. The transform matrix.

  • idInteger The purpose of id is to allow for efficient caching of rendered tiles. If id is 0, then no caching is performed. If it is non-zero, then it assumed to uniquely identify this tile.

EXAMPLE

device.beginTile([0,0,100,100], [100,100,200,200], 10, 10, mupdf.Matrix.identity, 0);
endTile()#

Ends the tiling pattern.

EXAMPLE

device.endTile();
beginLayer(tag)#

Begin a marked-content layer with the given tag.

Arguments
  • tagString.

EXAMPLE

device.beginLayer("my tag");
endLayer()#

End a marked-content layer.

EXAMPLE

device.endLayer();
renderFlags(set, clear)#

mutool only

Set/clear device rendering flags. Both set and clear are arrays where each element is a flag name:

"mask", "color", "uncacheable", "fillcolor-undefined", "strokecolor-undefined", "startcap-undefined", "dashcap-undefined", "endcap-undefined", "linejoin-undefined", "miterlimit-undefined", "linewidth-undefined", "bbox-defined", or "gridfit-as-tiled".

Arguments
  • set[].

  • clear[].

EXAMPLE

device.renderFlags(["mask","startcap-undefined"], []);
setDefaultColorSpaces(defaults)#

Change the set of default colorspaces for the device. See the DefaultColorSpaces object.

Arguments
  • defaultsObject.

EXAMPLE


beginStructure(standard, raw, uid)#

mutool only

Begin a standard structure element, the raw tag name and a unique identifier.

Arguments
  • standardString. One of the standard PDF structure names: “Document”, “Part”, “BlockQuote”, etc.

  • rawString. The tag name.

  • uidInteger. A unique identifier.

EXAMPLE

device.beginStructure("Document", "my_tag_name", 123);
endStructure()#

mutool only

End a standard structure element.

EXAMPLE

device.endStructure();
beginMetatext(type, text)#

mutool only

Begin meta text information.

Arguments
  • typeString. The type (either of "ActualText", "Alt", "Abbreviation", or "Title")

  • textString. The text value.

EXAMPLE

device.beginMetatext("Title", "My title");
endMetatext()#

mutool only

End meta text information.

EXAMPLE

device.endMetatext();
close()#

Tell the device that we are done, and flush any pending output. Ensure that no items are left on the stack before closing.

EXAMPLE

device.close();

Path#

A Path object represents vector graphics as drawn by a pen. A path can be either stroked or filled, or used as a clip mask.

new Path()#

Constructor method.

Create a new empty path.

Returns

Path.

EXAMPLE

var path = new mupdf.Path();

Instance methods

getBounds(stroke, transform)#

Return a bounding rectangle for the path.

Arguments
  • strokeFloat The stroke for the path.

  • transform[a,b,c,d,e,f]. The transform matrix for the path.

Returns

[ulx,uly,lrx,lry] Rectangle.

EXAMPLE

var rect = path.getBounds(1.0, mupdf.Matrix.identity);
moveTo(x, y)#

Lift and move the pen to the coordinate.

Arguments
  • x – X coordinate.

  • y – Y coordinate.

EXAMPLE

path.moveTo(10, 10);
lineTo(x, y)#

Draw a line to the coordinate.

Arguments
  • x – X coordinate.

  • y – Y coordinate.

EXAMPLE

path.lineTo(20,20);
curveTo(x1, y1, x2, y2, x3, y3)#

Draw a cubic bezier curve to (x3, y3) using (x1, y1) and (x2, y2) as control points.

Arguments
  • x1 – X1 coordinate.

  • y1 – Y1 coordinate.

  • x2 – X2 coordinate.

  • y2 – Y2 coordinate.

  • x3 – X3 coordinate.

  • y3 – Y3 coordinate.

EXAMPLE

path.curveTo(0, 0, 10, 10, 100, 100);
curveToV(cx, cy, ex, ey)#

Draw a cubic bezier curve to (ex, ey) using the start point and (cx, cy) as control points.

Arguments
  • cx – CX coordinate.

  • cy – CY coordinate.

  • ex – EX coordinate.

  • ey – EY coordinate.

EXAMPLE

path.curveToV(0, 0, 100, 100);
curveToY(cx, cy, ex, ey)#

Draw a cubic bezier curve to (ex, ey) using the (cx, cy) and (ex, ey) as control points.

Arguments
  • cx – CX coordinate.

  • cy – CY coordinate.

  • ex – EX coordinate.

  • ey – EY coordinate.

EXAMPLE

path.curveToY(0, 0, 100, 100);
closePath()#

Close the path by drawing a line to the last moveTo.

EXAMPLE

path.closePath();
rect(x1, y1, x2, y2)#

Shorthand for moveTo, lineTo, lineTo, lineTo, closePath to draw a rectangle.

Arguments
  • x1 – X1 coordinate.

  • y1 – Y1 coordinate.

  • x2 – X2 coordinate.

  • y2 – Y2 coordinate.

EXAMPLE

path.rect(0,0,100,100);
walk(pathWalker)#

mutool only

Call moveTo, lineTo, curveTo and closePath methods on the pathWalker object to replay the path.

Arguments
  • pathWalker – The path walker object. A user definable JavaScript object which can be used to trigger your own functions on the path methods.

Note

A path walker object has callback methods that are called when walk() walks over moveTo, lineTo, curveTo and closePath operators in a Path.

EXAMPLE

var myPathWalker = {
    moveTo: function (x, y) {
        //... do whatever ...
    },
    lineTo: function (x, y) {
        //... do whatever ...
    },
}
transform(transform)#

Transform path by the given transform matrix.

Arguments
  • transform[a,b,c,d,e,f]. The transform matrix for the path.

EXAMPLE

path.transform(mupdf.Matrix.scale(2,2));

Text#

A Text object contains text.

new Text()#

Constructor method.

Create a new empty text object.

Returns

Text.

EXAMPLE

var text = new mupdf.Text();

Instance methods

showGlyph(font, transform, glyph, unicode, wmode)#

Add a glyph to the text object.

Transform is the text matrix, specifying font size and glyph location. For example: [size,0,0,-size,x,y].

Glyph and unicode may be -1 for n-to-m cluster mappings. For example, the “fi” ligature would be added in two steps: first the glyph for the ‘fi’ ligature and the unicode value for ‘f’; then glyph -1 and the unicode value for ‘i’.

Arguments
  • fontFont object.

  • transform[a,b,c,d,e,f]. The transform matrix.

  • glyphInteger.

  • unicodeInteger.

  • wmode0 for horizontal writing, and 1 for vertical writing.

EXAMPLE

text.showGlyph(new mupdf.Font("Times-Roman"), mupdf.Matrix.identity, 21, 0x66, 0);
text.showGlyph(new mupdf.Font("Times-Roman"), mupdf.Matrix.identity, -1, 0x69, 0);
showString(font, transform, string)#

Add a simple string to the Text object. Will do font substitution if the font does not have all the unicode characters required.

Arguments
  • fontFont object.

  • transform[a,b,c,d,e,f]. The transform matrix.

  • string – String content for Text object.

EXAMPLE

text.showString(new mupdf.Font("Times-Roman"), mupdf.Matrix.identity, "Hello");
walk(textWalker)#

Call the showGlyph method on the textWalker object for each glyph in the text object.

Arguments
  • textWalker – The text walker object. A user definable JavaScript object which can be used to trigger your own functions on the text methods.

EXAMPLE

text.walk({
    beginSpan: function (font, transform, wmode, bidilevel, markupdirection, language) {
        // ... do whatever ...
    },
    showGlyph: function (font, transform, glyph, unicode, wmode, bidilevel) {
        // ... do whatever ...
    },
    endSpan: function () {
        // ... do whatever ...
    },
});

Font#

Font objects can be created from TrueType, OpenType, Type1 or CFF fonts. In PDF there are also special Type3 fonts.

new Font(ref)#

Constructor method.

Create a new font, either using a built-in font name or a file name.

The built-in standard PDF fonts are:

  • Times-Roman.

  • Times-Italic.

  • Times-Bold.

  • Times-BoldItalic.

  • Helvetica.

  • Helvetica-Oblique.

  • Helvetica-Bold.

  • Helvetica-BoldOblique.

  • Courier.

  • Courier-Oblique.

  • Courier-Bold.

  • Courier-BoldOblique.

  • Symbol.

  • ZapfDingbats.

The built-in CJK fonts are referenced by language code: zh-Hant, zh-Hans, ja, ko.

Arguments
  • ref – Font name or file name.

Returns

Font.

EXAMPLE

var font = new mupdf.Font("Times-Roman");

Instance methods

getName()#

Get the font name.

Returns

String.

EXAMPLE

var name = font.getName();
encodeCharacter(unicode)#

Get the glyph index for a unicode character. Glyph zero (.notdef) is returned if the font does not have a glyph for the character.

Arguments
  • unicode – The unicode character.

Returns

Glyph index.

EXAMPLE

var index = font.encodeCharacter(0x42);
advanceGlyph(glyph, wmode)#

Return advance width for a glyph in either horizontal or vertical writing mode.

Arguments
  • glyph – The glyph as unicode character.

  • wmode0 for horizontal writing, and 1 for vertical writing.

Returns

Width for the glyph.

EXAMPLE

var width = font.advanceGlyph(0x42, 0);
isBold()#

Returns true if font is bold.

Returns

Boolean.

EXAMPLE

var isBold = font.isBold();
isItalic()#

Returns true if font is italic.

Returns

Boolean.

EXAMPLE

var isItalic = font.isItalic();
isMono()#

Returns true if font is monospaced.

Returns

Boolean.

EXAMPLE

var isMono = font.isMono();
isSerif()#

Returns true if font is serif.

Returns

Boolean.

EXAMPLE

var isSerif = font.isSerif();

Image#

Image objects are similar to Pixmaps, but can contain compressed data.

new Image(ref)#

Constructor method.

Create a new image from a Pixmap data, or load an image file data.

Returns

Image.

EXAMPLE

var imageFromPixmap = new mupdf.Image(pixmap);
var imageFromBuffer = new mupdf.Image(buffer);

Instance methods

getWidth()#

Get the image width in pixels.

Returns

The width value.

EXAMPLE

var width = image.getWidth();
getHeight()#

Get the image height in pixels.

Returns

The height value.

EXAMPLE

var height = image.getHeight();
getXResolution()#

Returns the x resolution for the Image.

Returns

Int Image resolution in dots per inch.

EXAMPLE

var xRes = image.getXResolution();
getYResolution()#

Returns the y resolution for the Image.

Returns

Int Image resolution in dots per inch.

EXAMPLE

var yRes = image.getYResolution();
getColorSpace()#

Returns the ColorSpace for the Image.

Returns

ColorSpace.

EXAMPLE

var cs = image.getColorSpace();
getNumberOfComponents()#

Number of colors; plus one if an alpha channel is present.

Returns

Integer.

EXAMPLE

var num = image.getNumberOfComponents();
getBitsPerComponent()#

Returns the number of bits per component.

Returns

Integer.

EXAMPLE

var bits = image.getBitsPerComponent();
getInterpolate()#

Returns true if interpolated was used during decoding.

Returns

Boolean.

EXAMPLE

var interpolate = image.getInterpolate();
getColorKey()#

Returns an array with 2 * N integers for an N component image with color key masking, or null if masking is not used. Each pair of integers define an interval, and component values within that interval are not painted.

Returns

[...] or null.

EXAMPLE

var result = image.getColorKey();
getDecode()#

Returns an array with 2 * N numbers for an N component image with color mapping, or null if mapping is not used. Each pair of numbers define the lower and upper values to which the component values are mapped linearly.

Returns

[...] or null.

EXAMPLE

var arr = image.getDecode();
getOrientation()#

Returns the orientation of the image.

Returns

Integer.

EXAMPLE

var orientation = image.getOrientation();
setOrientation(orientation)#

Set the image orientation to the given orientation.

Arguments
  • orientationInteger Orientation value from the table below:

0

Undefined

1

0 degree ccw rotation. (Exif = 1)

2

90 degree ccw rotation. (Exif = 8)

3

180 degree ccw rotation. (Exif = 3)

4

270 degree ccw rotation. (Exif = 6)

5

flip on X. (Exif = 2)

6

flip on X, then rotate ccw by 90 degrees. (Exif = 5)

7

flip on X, then rotate ccw by 180 degrees. (Exif = 4)

8

flip on X, then rotate ccw by 270 degrees. (Exif = 7)

EXAMPLE

var orientation = image.setOrientation(4);
getImageMask()#

Returns true if this image is an image mask.

Returns

Boolean.

EXAMPLE

var mask = image.getImageMask();
getMask()#

Get another Image used as a mask for this one.

Returns

Image (or null).

EXAMPLE

var img = image.getMask();
toPixmap(scaledWidth, scaledHeight)#

Create a Pixmap from the image. The scaledWidth and scaledHeight arguments are optional, but may be used to decode a down-scaled Pixmap.

Arguments
  • scaledWidthFloat.

  • scaledHeightFloat.

Returns

Pixmap.

EXAMPLE

var pixmap = image.toPixmap();
var scaledPixmap = image.toPixmap(100, 100);

DocumentWriter#

DocumentWriter objects are used to create new documents in several formats.

new DocumentWriter(filename, format, options)#

mutool only

Constructor method.

Create a new document writer to create a document with the specified format and output options. If format is null it is inferred from the filename extension. The options argument is a comma separated list of flags and key-value pairs.

The output format & options are the same as in the mutool convert command.

Arguments
  • filename – The file name to output to.

  • format – The file format.

  • options – The options as key-value pairs.

Returns

DocumentWriter.

EXAMPLE

var writer = new mupdf.DocumentWriter("out.pdf", "PDF", "");
new DocumentWriter(buffer, format, options)#

wasm only

Constructor method.

Create a new document writer to create a document with the specified format and output options. The options argument is a comma separated list of flags and key-value pairs.

The output format & options are the same as in the mutool convert command.

Arguments
  • buffer – The buffer to output to.

  • format – The file format.

  • options – The options as key-value pairs.

Returns

DocumentWriter.

EXAMPLE

var writer = new mupdf.DocumentWriter(buffer, "PDF", "");

Instance methods

beginPage(mediabox)#

Begin rendering a new page. Returns a Device that can be used to render the page graphics.

Arguments
Returns

Device.

EXAMPLE

var device = writer.beginPage([0,0,100,100]);
endPage(device)#

Finish the page rendering. The argument must be the same Device object that was returned by the beginPage method.

Arguments
  • deviceDevice.

EXAMPLE

writer.endPage(device);
close()#

Finish the document and flush any pending output.

EXAMPLE

writer.close();

PDFDocument#

With MuPDF it is also possible to create, edit and manipulate PDF documents using low level access to the objects and streams contained in a PDF file. A PDFDocument object is also a Document object. You can test a Document object to see if it is safe to use as a PDFDocument by calling document.isPDF().

new PDFDocument()#

Constructor method.

Create a new empty PDF document.

Returns

PDFDocument.

EXAMPLE

var pdfDocument = new mupdf.PDFDocument();
new PDFDocument(fileName)#

mutool only

Constructor method.

Load a PDF document from file.

Returns

PDFDocument.

EXAMPLE

var pdfDocument = new mupdf.PDFDocument("my-file.pdf");

Instance methods

getVersion()#

Returns the PDF document version as an integer multiplied by 10, so e.g. a PDF-1.4 document would return 14.

Returns

Integer.

EXAMPLE

var version = pdfDocument.getVersion();
setLanguage(lang)#

wasm only

Sets the language for the document.

Arguments
  • langString.

EXAMPLE

pdfDocument.setLanguage("en");
getLanguage()#

wasm only

Gets the language for the document.

Returns

String.

EXAMPLE

var lang = pdfDocument.getLanguage();
rearrangePages(pages)#

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.

N.B. the PDFDocument should not be used for anything except saving after rearranging the pages (FIXME).

Arguments
  • pages – An array of page numbers (0-based).

EXAMPLE

var document = new Document.openDocument("my_pdf.pdf");
pdfDocument.rearrangePages([3,2]);
pdfDocument.save("fewer_pages.pdf", "garbage");
save(fileName, options)#

mutool only

Write the PDFDocument to file. The options are a string of comma separated options (see the mutool convert options).

Arguments
  • fileName – The name of the file to save to.

  • options – The options.

EXAMPLE

pdfDocument.save("my_fileName.pdf", "compress,compress-images,garbage=compact");
saveToBuffer(options)#

wasm only

Saves the document to a buffer. The options are a string of comma separated options (see the mutool convert options).

Arguments
  • options – The options.

Returns

Buffer.

EXAMPLE

var buffer = pdfDocument.saveToBuffer({"compress-images":true});
canBeSavedIncrementally()#

Returns true if the document can be saved incrementally, e.g. repaired documents or applying redactions prevents incremental saves.

Returns

Boolean.

EXAMPLE

var canBeSavedIncrementally = pdfDocument.canBeSavedIncrementally();
countVersions()#

Returns the number of versions of the document in a PDF file, typically 1 + the number of updates.

Returns

Integer.

EXAMPLE

var versionNum = pdfDocument.countVersions();
countUnsavedVersions()#

Returns the number of unsaved updates to the document.

Returns

Integer.

EXAMPLE

var unsavedVersionNum = pdfDocument.countUnsavedVersions();
validateChangeHistory()#

Check the history of the document, return 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.

Returns

Integer.

EXAMPLE

var changeHistory = pdfDocument.validateChangeHistory();
hasUnsavedChanges()#

Returns true if the document has been changed since it was last opened or saved.

Returns

Boolean.

EXAMPLE

var hasUnsavedChanges = pdfDocument.hasUnsavedChanges();
wasPureXFA()#

mutool only

Returns true if the document was an XFA form without AcroForm fields.

Returns

Boolean.

EXAMPLE

var wasPureXFA = pdfDocument.wasPureXFA();
wasRepaired()#

Returns true if the document was repaired when opened.

Returns

Boolean.

EXAMPLE

var wasRepaired = pdfDocument.wasRepaired();
setPageLabels(index, style, prefix, start)#

Sets the page label numbering for the page and all pages following it, until the next page with an attached label.

Arguments
  • indexInteger.

  • styleString 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).

  • prefixString.

  • startInteger The ordinal with which to start numbering.

EXAMPLE

pdfDocument.setPageLabels(0, "D", "Prefix", 1);
deletePageLabels(index)#

Removes any associated page label from the page.

Arguments
  • indexInteger.

EXAMPLE

pdfDocument.deletePageLabels(0);
getTrailer()#

The trailer dictionary. This contains indirect references to the “Root” and “Info” dictionaries. See: PDF object access.

Returns

PDFObject The trailer dictionary.

EXAMPLE

var dict = pdfDocument.getTrailer();
countObjects()#

Return the number of objects in the PDF. Object number 0 is reserved, and may not be used for anything. See: PDF object access.

Returns

Integer Object count.

EXAMPLE

var num = pdfDocument.countObjects();
createObject()#

Allocate a new numbered object in the PDF, and return an indirect reference to it. The object itself is uninitialized.

Returns

The new object.

EXAMPLE

var obj = pdfDocument.createObject();
deleteObject(obj)#

Delete the object referred to by an indirect reference or its object number.

Arguments
  • obj – The object to delete.

EXAMPLE

pdfDocument.deleteObject(obj);
formatURIWithPathAndDest(path, destination)#

Format a link URI given a system independent path (see table 3.40 in the 1.7 specification) to a remote document and a destination object or a destination string suitable for createLink().

Arguments
  • pathString An absolute or relative path to a remote document file.

  • destinationLink destiation or String referring to a destination using either a destination object or a destination name in the remote document.

appendDestToURI(uri, destination)#

Append a fragment representing a document destination to a an existing URI that points to a remote document. The resulting string is suitable for createLink().

Arguments
  • uriString An URI to a remote document file.

  • destinationLink destiation or String referring to a destination using either a destination object or a destination name in the remote document.


PDF JavaScript actions#

enableJS()#

Enable interpretation of document JavaScript actions.

EXAMPLE

pdfDocument.enableJS();
disableJS()#

Disable interpretation of document JavaScript actions.

EXAMPLE

pdfDocument.disableJS();
isJSSupported()#

Returns true if interpretation of document JavaScript actions is supported.

Returns

Boolean.

EXAMPLE

var jsIsSupported = pdfDocument.isJSSupported();
setJSEventListener(listener)#

mutool only

Calls the listener whenever a document JavaScript action triggers an event.

Arguments
  • listener{} The JavaScript listener function.

Note

At present this listener will only trigger when a document JavaScript action triggers an alert.

EXAMPLE

pdfDocument.setJSEventListener({
        onAlert: function(message) {
                print(message);
        }
});
bake(bakeAnnots, bakeWidgets)#

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.

Arguments
  • bakeAnnotsBoolean Whether to bake annotations or not. Defaults to true.

  • bakeWidgetsBoolean Whether to bake widgets or not. Defaults to true.


PDF Journalling#

enableJournal()#

Activate journalling for the document.

EXAMPLE

pdfDocument.enableJournal();
getJournal()#

Returns a PDF Journal Object.

Returns

Object PDF Journal Object.

EXAMPLE

var journal = pdfDocument.getJournal();
beginOperation(op)#

Begin a journal operation.

Arguments
  • opString The name of the operation.

EXAMPLE

pdfDocument.beginOperation("my_operation");
beginImplicitOperation()#

Begin an implicit journal operation. Implicit operations are operations that happen due to other operations, e.g. updating an annotation.

EXAMPLE

pdfDocument.beginImplicitOperation();
endOperation()#

End a previously started normal or implicit operation. After this it can be undone/redone using the methods below.

EXAMPLE

pdfDocument.endOperation();
abandonOperation()#

Abandon an operation. Reverts to the state before that operation began.

EXAMPLE

pdfDocument.abandonOperation();
canUndo()#

Returns true if undo is possible in this state.

Returns

Boolean.

EXAMPLE

var canUndo = pdfDocument.canUndo();
canRedo()#

Returns true if redo is possible in this state.

Returns

Boolean.

EXAMPLE

var canRedo = pdfDocument.canRedo();
undo()#

Move backwards in the undo history. Changes to the document after this throws away all subsequent history.

EXAMPLE

pdfDocument.undo();
redo()#

Move forwards in the undo history.

EXAMPLE

pdfDocument.redo();
saveJournal(filename)#

Save the journal to a file.

arg filename

File to save the journal to.

EXAMPLE

pdfDocument.saveJournal("test.journal");

PDF Object Access#

A PDF document contains objects, similar to those in JavaScript: arrays, dictionaries, strings, booleans, and numbers. At the root of the PDF document is the trailer object; which contains pointers to the meta data dictionary and the catalog object which contains the pages and other information.

Pointers in PDF are also 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.

PDF has two types of strings: /Names and (Strings). All dictionary keys are names.

Some dictionaries in PDF also have attached binary data. These are called streams, and may be compressed.

Note

PDFObjects are always bound to the document that created them. Do NOT mix and match objects from one document with another document!


addObject(obj)#

Add obj to the PDF as a numbered object, and return an indirect reference to it.

Arguments
  • obj – Object to add.

Returns

Object.

EXAMPLE

var ref = pdfDocument.addObject(obj);
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.

Arguments
  • bufferBuffer object.

  • object – The object to add the stream to.

Returns

Object.

EXAMPLE

var stream = pdfDocument.addStream(buffer, object);
addRawStream(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.

Arguments
  • bufferBuffer object.

  • object – The object to add the stream to.

Returns

Object.

EXAMPLE

var stream = pdfDocument.addRawStream(buffer, object);
newNull()#

Create a new null object.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newNull();
newBoolean(boolean)#

Create a new boolean object.

Arguments
  • boolean – The boolean value.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newBoolean(true);
newInteger(number)#

Create a new integer object.

Arguments
  • number – The number value.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newInteger(1);
newReal(number)#

Create a new real number object.

Arguments
  • number – The number value.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newReal(7.3);
newString(string)#

Create a new string object.

Arguments
  • stringString.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newString("hello");
newByteString(byteString)#

Create a new byte string object.

Arguments
  • byteStringString.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newByteString("hello");
newName(string)#

Create a new name object.

Arguments
  • string – The string value.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newName("hello");
newIndirect(objectNumber, generation)#

Create a new indirect object.

Arguments
  • objectNumberInteger.

  • generationInteger.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newIndirect(100, 0);
newArray(capacity)#

Create a new array object.

Arguments
  • capacityInteger Defaults to 8.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newArray();
newDictionary(capacity)#

Create a new dictionary object.

Arguments
  • capacityInteger Defaults to 8.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.newDictionary();

PDF Page Access#

All page objects are structured into a page tree, which defines the order the pages appear in.

countPages()#

Number of pages in the document.

Returns

Integer Page number.

EXAMPLE

var pageCount = pdfDocument.countPages();
loadPage(number)#

Return the PDFPage for a page number.

Arguments
  • numberInteger The page number, the first page is number zero.

Returns

PDFPage.

EXAMPLE

var page = pdfDocument.loadPage(0);
findPage(number)#

Return the PDFObject for a page number.

Arguments
  • numberInteger The page number, the first page is number zero.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.findPage(0);
findPageNumber(page)#

mutool only

Given a PDFPage instance, find the page number in the document.

Arguments
  • pagePDFPage instance.

Returns

Integer.

EXAMPLE

var pageNumber = pdfDocument.findPageNumber(page);
deletePage(number)#

Delete the numbered PDFPage.

Arguments
  • number – The page number, the first page is number zero.

EXAMPLE

pdfDocument.deletePage(0);
insertPage(at, page)#

Insert the PDFPage object in the page tree at the location. If at is -1, at the end of the document.

Pages consist of a content stream, and a resource dictionary containing all of the fonts and images used.

Arguments
  • at – The index to insert at.

  • page – The PDFPage to insert.

EXAMPLE

pdfDocument.insertPage(-1, page);
addPage(mediabox, rotate, resources, contents)#

Create a new PDFPage object. Note: this function does NOT add it to the page tree, use insertPage to do that.

Arguments
  • mediabox[ulx,uly,lrx,lry] Rectangle.

  • rotate – Rotation value.

  • resources – Resources object.

  • contents – Contents string. This represents the page content stream - see section 3.7.1 in the PDF 1.7 specification.

Returns

PDFObject.

EXAMPLE

var helvetica = pdfDocument.newDictionary();
helvetica.put("Type", pdfDocument.newName("Font"));
helvetica.put("Subtype", pdfDocument.newName("Type1"));
helvetica.put("Name", pdfDocument.newName("Helv"));
helvetica.put("BaseFont", pdfDocument.newName("Helvetica"));
helvetica.put("Encoding", pdfDocument.newName("WinAnsiEncoding"));
var fonts = pdfDocument.newDictionary();
fonts.put("Helv", helvetica);
var resources = pdfDocument.addObject(pdfDocument.newDictionary());
resources.put("Font", fonts);
var pageObject = pdfDocument.addPage([0,0,300,350], 0, resources, "BT /Helv 12 Tf 100 100 Td (MuPDF!)Tj ET");
pdfDocument.insertPage(-1, pageObject);

EXAMPLE

docs/examples/pdf-create.js#
// Create a PDF from scratch using helper functions.

// This example creates a new PDF file from scratch, using helper
// functions to create resources and page objects.
// This assumes a basic working knowledge of the PDF file format.

// Create a new empty document with no pages.
var pdf = new PDFDocument()

// Load built-in font and create WinAnsi encoded simple font resource.
var font = pdf.addSimpleFont(new Font("Times-Roman"))

// Load PNG file and create image resource.
var image = pdf.addImage(new Image("example.png"))

// Create resource dictionary.
var resources = pdf.addObject({
	Font: { Tm: font },
	XObject: { Im0: image },
})

// Create content stream data.
var contents =
	"10 10 280 330 re s\n" +
	"q 200 0 0 200 50 100 cm /Im0 Do Q\n" +
	"BT /Tm 16 Tf 50 50 TD (Hello, world!) Tj ET\n"

// Create a new page object.
var page = pdf.addPage([0,0,300,350], 0, resources, contents)

// Insert page object at the end of the document.
pdf.insertPage(-1, page)

// Save the document to file.
pdf.save("out.pdf", "pretty,ascii,compress-images,compress-fonts")
addSimpleFont(font, encoding)#

Create a PDFObject from the Font object as a simple font.

Arguments
  • fontFont.

  • encoding – The encoding to use. Encoding is either “Latin” (CP-1252), “Greek” (ISO-8859-7), or “Cyrillic” (KOI-8U). The default is “Latin”.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.addSimpleFont(new mupdf.Font("Times-Roman"), "Latin");
addCJKFont(font, language, wmode, style)#

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”).

Arguments
  • fontFont.

  • languageString.

  • wmode0 for horizontal writing, and 1 for vertical writing.

  • styleString.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.addCJKFont(new mupdf.Font("ja"), "ja", 0, "serif");
addFont(font)#

Create a PDFObject from the Font object as an Identity-H encoded CID font.

Arguments
  • fontFont.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.addFont(new mupdf.Font("Times-Roman"));
addImage(image)#

Create a PDFObject from the Image object.

Arguments
  • imageImage.

Returns

PDFObject.

EXAMPLE

var obj = pdfDocument.addImage(new mupdf.Image(pixmap));
loadImage(obj)#

Load an Image from a PDFObject (typically an indirect reference to an image resource).

Arguments
  • objPDFObject.

Returns

Image.

EXAMPLE

var image = pdfDocument.loadImage(obj);

Copying objects across PDFs#

The following functions can be used to copy objects from one PDF document to another:

newGraftMap()#

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.

Returns

PDFGraftMap.

EXAMPLE

var graftMap = pdfDocument.newGraftMap();
graftObject(object)#

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.

Arguments
  • object – Object to graft.

EXAMPLE

pdfDocument.graftObject(obj);
graftPage(to, srcDoc, srcPageNumber)#

Graft a page and its resources at the given page number from the source document to the requested page number in the document.

Arguments
  • to – The page number to insert the page before. Page numbers start at 0 and -1 means at the end of the document.

  • srcDoc – Source document.

  • srcPageNumber – Source page number.

EXAMPLE

This would copy the first page of the source document (0) to the last page (-1) of the current PDF document.

pdfDocument.graftPage(-1, srcDoc, 0);

Embedded/Associated files in PDFs#

addEmbeddedFile(filename, mimetype, contents, creationDate, modificationDate, addChecksum)#

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.

Arguments
  • filenameString.

  • mimetypeString See: Mimetype.

  • contentsBuffer.

  • creationDateDate.

  • modificationDateDate.

  • addChecksumBoolean.

Returns

Object File Specification Object.

Note

After embedding a file into a PDF, it can be connected to an annotation using PDFAnnotation.setFilespec().

EXAMPLE

var fileSpecObject = pdfDocument.addEmbeddedFile("my_file.jpg",
                                                 "image/jpeg",
                                                 buffer,
                                                 new Date(),
                                                 new Date(),
                                                 false);
getEmbeddedFiles()#

Returns the embedded files or null for the document.

Returns

Object File Specification Object.

getEmbeddedFileParams(fileSpecObject)#

Historical alias for getFilespecParams.

getFilespecParams(fileSpecObject)#

Return an object describing the file referenced by the fileSpecObject.

Arguments
Returns

Object Filespec Params Object.

EXAMPLE

var obj = pdfDocument.getFilespecParams(fileSpecObject);
getEmbeddedFileContents(fileSpecObject)#

Returns a Buffer with the contents of the embedded file referenced by the fileSpecObject.

Arguments
Returns

Buffer.

EXAMPLE

var buffer = pdfDocument.getEmbeddedFileContents(fileSpecObject);
verifyEmbeddedFileChecksum(fileSpecObject)#

Verify the MD5 checksum of the embedded file contents.

Arguments
Returns

Boolean.

EXAMPLE

var fileChecksumValid = pdfDocument.verifyEmbeddedFileChecksum(fileSpecObject);
countAssociatedFiles()#

Return the number of Associated Files on 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.

Returns

Integer

EXAMPLE

var count = pdfDocument.countAssociatedFiles();
associatedFile(n)#

Return the Filespec object that represents the nth Associated File on this document. 0 <= n < count, where count is the value given by countAssociatedFiles().

Return fileSpecObject

Object File Specification Object.

EXAMPLE

var obj = pdfDocument.associatedFile(0);

ZUGFeRD support in PDFs#

zugferdProfile()#

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”.

Returns

String.

EXAMPLE

var profile = pdfDocument.zugferdProfile();
zugferdVersion()#

Determine if the current PDF is a ZUGFeRD PDF, and, if so, return the version of the spec it claims to conforms to. This will return 0 for non-zugferd PDFs.

Returns

Float.

EXAMPLE

var version = pdfDocument.zugferdVersion();
zugferdXML()#

Return a buffer containing the embedded ZUGFeRD XML data from this PDF.

Returns

Buffer.

EXAMPLE

var buf = pdfDocument.zugferdXML();

PDFGraftMap#

Instance methods

graftObject(object)#

Use the graft map to copy objects, with the ability to remember previously copied objects.

Arguments
  • object – Object to graft.

EXAMPLE

var map = document.newGraftMap();
map.graftObject(obj);
graftPage(map, dstPageNumber, srcDoc, srcPageNumber)#

Graft a page and its resources at the given page number from the source document to the requested page number in the destination document connected to the map.

Arguments
  • dstPageNumber – The page number where the source page will be inserted. Page numbers start at 0, and -1 means at the end of the document.

  • srcDoc – Source document.

  • srcPageNumber – Source page number.

EXAMPLE

var map = dstdoc.newGraftMap();
map.graftObject(-1, srcdoc, 0);

PDFObject#

All functions that take PDFObjects, do automatic translation between JavaScript objects and PDFObjects using a few basic rules:

  • Null, booleans, and numbers are translated directly.

  • JavaScript strings are translated to PDF names, unless

they are surrounded by parentheses: “Foo” becomes the PDF name /Foo and “(Foo)” becomes the PDF string (Foo). - Arrays and dictionaries are recursively translated to PDF arrays and dictionaries. Be aware of cycles though! The translation does NOT cope with cyclic references! - The translation goes both ways: PDF dictionaries and arrays can be accessed similarly to JavaScript objects and arrays by getting and setting their properties.

Instance properties

length

Length of the array.

Instance methods

get(ref)#

Access dictionaries and arrays in the PDFObject.

Arguments
  • ref – Key or index.

Returns

The value for the key or index.

EXAMPLE

var dict = pdfDocument.newDictionary();
var value = dict.get("my_key");
var arr = pdfDocument.newArray();
var value = arr.get(1);
put(ref, value)#

Put information into dictionaries and arrays in the PDFObject. Dictionaries and arrays can also be accessed using normal property syntax: obj.Foo = 42; delete obj.Foo; x = obj[5].

Arguments
  • ref – Key or index.

  • value – The value for the key or index.

EXAMPLE

var dict = pdfDocument.newDictionary();
dict.put("my_key", "my_value");
var arr = pdfDocument.newArray();
arr.put(0, 42);
delete(ref)#

Delete a reference from a PDFObject.

Arguments
  • ref – Key or index.

EXAMPLE

pdfObj.delete("my_key");
var dict = pdfDocument.newDictionary();
dict.put("my_key", "my_value");
dict.delete("my_key");
var arr = pdfDocument.newArray();
arr.put(1, 42);
arr.delete(1);
resolve()#

If the object is an indirect reference, return the object it points to; otherwise return the object itself.

Returns

Object.

EXAMPLE

var resolvedObj = pdfObj.resolve();
compare(other_obj)#

mutool only

Compare the object to another one. Returns 0 on match, non-zero on mismatch. Streams always mismatch.

Arguments
  • otherPDFObject.

Returns

Boolean.

EXAMPLE

var match = pdfObj.compare(other_obj);
isArray()#
Returns

Boolean.

EXAMPLE

var result = pdfObj.isArray();
isDictionary()#
Returns

Boolean.

EXAMPLE

var result = pdfObj.isDictionary();
forEach(fun)#

Iterate over all the entries in a dictionary or array and call a function for each value-key pair.

Arguments
  • fun – Function in the format function(value,key){...}.

EXAMPLE

pdfObj.forEach(function(value,key){console.log("value="+value+",key="+key)});
push(item)#

Append item to the end of an array.

Arguments
  • item – Item to add.

EXAMPLE

pdfObj.push("item");
toString()#

Returns the object as a pretty-printed string.

Returns

String.

EXAMPLE

var str = pdfObj.toString();
valueOf()#

Convert primitive PDF objects to a corresponding primitive Null, Boolean, Number or String JavaScript objects. Indirect PDF objects get converted to the string “R” while PDF names are converted to plain strings. PDF arrays or dictionaries are returned unchanged.

Returns

Null | Boolean | Number | String.

EXAMPLE

var val = pdfObj.valueOf();
isIndirect()#

Is the object an indirect reference.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isIndirect();
asIndirect()#

Return the object number the indirect reference points to.

Returns

Integer.

EXAMPLE

var val = pdfObj.asIndirect();
isFilespec()#

Is the object a file specification (or a reference to a file specification).

Returns

Boolean.

EXAMPLE

var val = pdfObj.isFilespec();

PDF streams#

The only way to access a stream is via an indirect object, since all streams are numbered objects.

isStream()#

True if the object is an indirect reference pointing to a stream.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isStream();
readStream()#

Read the contents of the stream object into a Buffer.

Returns

Buffer.

EXAMPLE

var buffer = pdfObj.readStream();
readRawStream()#

Read the raw, uncompressed, contents of the stream object into a Buffer.

Returns

Buffer.

EXAMPLE

var buffer = pdfObj.readRawStream();
writeObject(obj)#

Update the object the indirect reference points to.

Arguments
  • obj – Object to update.

EXAMPLE

pdfObj.writeObject(obj);
writeStream(buffer)#

Update the contents of the stream the indirect reference points to. This will update the “Length”, “Filter” and “DecodeParms” automatically.

Arguments
  • bufferBuffer.

EXAMPLE

pdfObj.writeStream(buffer);
writeRawStream(buffer)#

Update the contents of the stream the indirect reference points to. The buffer must contain already compressed data that matches the “Filter” and “DecodeParms”. This will update the “Length” automatically, but leave the “Filter” and “DecodeParms” untouched.

Arguments
  • bufferBuffer.

EXAMPLE

pdfObj.writeRawStream(buffer);

Primitive Objects#

Primitive PDF objects such as booleans, names, and numbers can usually be treated like JavaScript values. When that is not sufficient use these functions:

isNull()#

Returns true if the object is a null object.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isNull();
isBoolean()#

Returns true if the object is a Boolean object.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isBoolean();
asBoolean()#

Get the boolean primitive value.

Returns

Boolean.

EXAMPLE

var val = pdfObj.asBoolean();
isInteger()#

Returns true if the object is an Integer object.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isInteger();
isNumber()#

Returns true if the object is a Number object.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isNumber();
asNumber()#

Get the number primitive value.

Returns

Integer.

EXAMPLE

var val = pdfObj.asNumber();
isName()#

Returns true if the object is a Name object.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isName();
asName()#

Get the name as a string.

Returns

String.

EXAMPLE

var val = pdfObj.asName();
isReal()#

Returns true if the object is a Real object.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isReal();
isString()#

Returns true if the object is a String object.

Returns

Boolean.

EXAMPLE

var val = pdfObj.isString();
asString()#

Convert a “text string” to a JavaScript unicode string.

Returns

String.

EXAMPLE

var val = pdfObj.asString();
asByteString()#

Convert a string to an array of byte values.

Returns

[...].

EXAMPLE

var val = pdfObj.asByteString();

PDFPage#

Extends Page.

Instance methods

getAnnotations()#

Return array of all annotations on the page.

Returns

[...].

EXAMPLE

var annots = pdfPage.getAnnotations();
createAnnotation(type)#

Create a new blank annotation of a given type.

Arguments
Returns

PDFAnnotation.

EXAMPLE

var annot = pdfPage.createAnnotation("Text");

Annotation types

Note

Annotation types are also referred to as “subtypes”.

Name

Supported

Notes

Text

Yes

Link

Yes

Please use Page.createLink().

FreeText

Yes

Square

Yes

Circle

Yes

Line

Yes

Polygon

Yes

PolyLine

Yes

Highlight

Yes

Underline

Yes

Squiggly

Yes

StrikeOut

Yes

Redact

Yes

Stamp

Yes

Caret

Yes

Ink

Yes

Popup

No

FileAttachment

Yes

Sound

No

Movie

No

RichMedia

No

Widget

No

Screen

No

PrinterMark

No

TrapNet

No

Watermark

No

3D

No

Projection

No

deleteAnnotation(annot)#

Delete the annotation from the page.

Arguments
  • annotPDFAnnotation.

EXAMPLE

pdfPage.deleteAnnotation(annot);
getWidgets()#

Return array of all widgets on the page.

Returns

[...].

EXAMPLE

var widgets = pdfPage.getWidgets();
update()#

Loop through all annotations of the page and update them. Returns true if re-rendering is needed because at least one annotation was changed (due to either events or JavaScript actions or annotation editing).

EXAMPLE

pdfPage.update();
applyRedactions(blackBoxes, imageMethod)#

Applies redactions to the page.

Arguments
  • blackBoxesBoolean Whether to use black boxes at each redaction or not.

  • imageMethodInteger. 0 for no redactions, 1 to redact entire images, 2 for redacting just the covered pixels.

Note

Redactions are secure as they remove the affected content completely.

EXAMPLE

pdfPage.applyRedactions(true, 1);
process(processor)#

Run through the page contents stream and call methods on the supplied PDF processor.

Arguments
  • processor – User defined function.

EXAMPLE

pdfPage.process(processor);
toPixmap(transform, colorspace, alpha, renderExtra, usage, box)#

Render the page into a Pixmap using the given colorspace and alpha while applying the transform. Rendering of annotations/widgets can be disabled. A page can be rendered for e.g. “View” or “Print” usage.

Arguments
  • transform[a,b,c,d,e,f] The transform matrix.

  • colorspaceColorSpace.

  • alphaBoolean.

  • renderExtraBoolean Whether annotations and widgets should be rendered.

  • usageString “View” or “Print”.

  • boxString Default is “CropBox”.

Returns

Pixmap.

EXAMPLE

var pixmap = pdfPage.toPixmap(mupdf.Matrix.identity,
                              mupdf.ColorSpace.DeviceRGB,
                              false,
                              true,
                              "View",
                              "CropBox");
createSignature(name)#

Create a new signature widget with the given name as field label.

Arguments
  • nameString The desired field label.

Returns

PDFWidget.

EXAMPLE

var signatureWidget = pdfPage.createSignature("test");
countAssociatedFiles()#

Return the number of Associated Files on this page. Note that this is the number of files associated to this page, not necessarily the total number of files associated with elements throughout the entire document.

Returns

Integer

EXAMPLE

var count = pdfPage.countAssociatedFiles();
associatedFile(n)#

Return the Filespec object that represents the nth Associated File on this page. 0 <= n < count, where count is the value given by countAssociatedFiles().

Return fileSpecObject

Object File Specification Object.

EXAMPLE

var obj = pdfPage.associatedFile(0);

PDFAnnotation#

PDF Annotations belong to a specific PDFPage and may be created/changed/removed. Because annotation appearances may change (for several reasons) it is possible to scan through the annotations on a page and query them to see whether a re-render is necessary. Finally redaction annotations can be applied to a PDFPage, destructively removing content from the page.

To get the annotations on a page see: PDFPage getAnnotations(), to create an annotation see: PDFPage createAnnotation().

Instance methods

getBounds()#

Returns a rectangle containing the location and dimension of the annotation.

Returns

[ulx,uly,lrx,lry] Rectangle.

EXAMPLE

var bounds = annotation.getBounds();
run(device, transform)#

Calls the device functions to draw the annotation.

Arguments
  • deviceDevice.

  • transform[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

annotation.run(device, mupdf.Matrix.identity);
toPixmap(transform, colorspace, alpha)#

Render the annotation into a Pixmap, using the transform and colorspace.

Arguments
  • transform[a,b,c,d,e,f]. The transform matrix.

  • colorspaceColorSpace.

  • alphaBoolean.

Returns

Pixmap.

EXAMPLE

var pixmap = annotation.toPixmap(mupdf.Matrix.identity, mupdf.ColorSpace.DeviceRGB, true);
toDisplayList()#

Record the contents of the annotation into a DisplayList.

Returns

DisplayList.

EXAMPLE

var displayList = annotation.toDisplayList();
getObject()#

Get the underlying PDFObject for an annotation.

Returns

PDFObject.

EXAMPLE

var obj = annotation.getObject();
process(processor)#

mutool only

Run through the annotation appearance stream and call methods on the supplied PDF processor.

Arguments
  • processor – User defined function.

EXAMPLE

annotation.process(processor);
setAppearance(appearance, state, transform, displayList)#

Set the annotation appearance stream for the given appearance. The desired appearance is given as a transform along with a display list.

Arguments
  • appearanceString Appearance stream (“N”, “R” or “D”).

  • stateString The annotation state to set the appearance for or null for the current state. Only widget annotations of pushbutton, check box, or radio button type have states, which are “Off” or “Yes”. For other types of annotations pass null.

  • transform[a,b,c,d,e,f]. The transform matrix.

  • displayListDisplayList.

EXAMPLE

annotation.setAppearance("N", null, mupdf.Matrix.identity, displayList);
setAppearance(appearance, state, transform, bbox, resources, contents)#

Set the annotation appearance stream for the given appearance. The desired appearance is given as a transform along with a bounding box, a PDF dictionary of resources and a content stream.

Arguments
  • appearanceString Appearance stream (“N”, “R” or “D”).

  • stateString The annotation state to set the appearance for or null for the current state. Only widget annotations of pushbutton, check box, or radio button type have states, which are “Off” or “Yes”. For other types of annotations pass null.

  • transform[a,b,c,d,e,f]. The transform matrix.

  • bbox[ulx,uly,lrx,lry] Rectangle.

  • resources – Resources object.

  • contents – Contents string.

EXAMPLE

annotation.setAppearance("N", null, mupdf.Matrix.identity, [0,0,100,100], resources, contents);
setAppearance(image)#

Set a stamp annotation’s appearance to that of an image.

Arguments
  • imageImage containing the desired appearance.

EXAMPLE

var img = new Image("photo.jpg");
annotation.setAppearance(img);

Appearance stream values

Value

Description

N

normal appearance

R

roll-over appearance

D

down (pressed) appearance

update()#

Update the appearance stream to account for changes in the annotation.

EXAMPLE

annotation.update();
getHot()#

mutool only

Get the annotation as being hot, i.e. that the pointer is hovering over the annotation.

Returns

Boolean.

EXAMPLE

annotation.getHot();
setHot(hot)#

mutool only

Set the annotation as being hot, i.e. that the pointer is hovering over the annotation.

Arguments
  • hotBoolean.

EXAMPLE

annotation.setHot(true);
getHiddenForEditing()#

Get a special annotation hidden flag for editing. This flag prevents the annotation from being rendered.

Returns

Boolean.

EXAMPLE

var hidden = annotation.getHiddenForEditing();
setHiddenForEditing(hidden)#

Set a special annotation hidden flag for editing. This flag prevents the annotation from being rendered.

Arguments
  • hiddenBoolean.

EXAMPLE

annotation.setHiddenForEditing(true);
getType()#

Return the annotation type.

Returns

String Annotation type.

EXAMPLE

var type = annotation.getType();
getFlags()#

Get the annotation flags.

Returns

Integer representaton of a bit-field of flags specified below.

EXAMPLE

var flags = annotation.getFlags();
setFlags(flags)#

Set the annotation flags.

Arguments
  • flagsInteger representaton of a bit-field of flags specified below.

EXAMPLE

annotation.setFlags(8); // Clears all other flags and sets NoZoom.

Annotation flags

Bit position

Name

1

Invisible

2

Hidden

3

Print

4

NoZoom

5

NoRotate

6

NoView

7

ReadOnly

8

Locked

9

ToggleNoView

10

LockedContents

getContents()#

Get the annotation contents.

Returns

String.

EXAMPLE

var contents = annotation.getContents();
setContents(text)#

Set the annotation contents.

Arguments
  • textString.

EXAMPLE

annotation.setContents("Hello World");
getBorder()#

mutool only

Get the annotation border line width in points.

Returns

Float.

EXAMPLE

var border = annotation.getBorder();
setBorder(width)#

mutool only

Set the annotation border line width in points. Use setBorderWidth() to avoid removing the border effect.

Arguments
  • widthFloat Border width.

EXAMPLE

annotation.setBorder(1.0);
getColor()#

Get the annotation color, represented as an array of 1, 3, or 4 component values.

Returns

The color value.

EXAMPLE

var color = annotation.getColor();
setColor(color)#

Set the annotation color, represented as an array of 1, 3, or 4 component values.

Arguments

EXAMPLE

annotation.setColor([0,1,0]);
getOpacity()#

Get the annotation opacity.

Returns

The opacity value.

EXAMPLE

var opacity = annotation.getOpacity();
setOpacity(opacity)#

Set the annotation opacity.

Arguments

EXAMPLE

annotation.setOpacity(0.5);
getCreationDate()#

Get the annotation creation date as a JavaScript Date object.

Returns

Date.

EXAMPLE

var date = annotation.getCreationDate();
setCreationDate(date)#

Set the creation date.

Arguments
  • dateDate.

EXAMPLE

annotation.setCreationDate(new Date());
getModificationDate()#

Get the annotation modification date as a JavaScript Date object.

Returns

Date.

EXAMPLE

var date = annotation.getModificationDate();
setModificationDate(date)#

Set the modification date.

Arguments
  • dateDate.

EXAMPLE

annotation.setModificationDate(new Date());
getQuadding()#

Get the annotation quadding (justification).

Returns

Quadding value, 0 for left-justified, 1 for centered, 2 for right-justified.

EXAMPLE

var quadding = annotation.getQuadding();
setQuadding(value)#

Set the annotation quadding (justification).

Arguments
  • valueNumber. Quadding value, 0 for left-justified, 1 for centered, 2 for right-justified.

EXAMPLE

annotation.setQuadding(1);
getLanguage()#

Get the annotation language (or get the inherited document language).

Returns

String.

EXAMPLE

var language = annotation.getLanguage();
setLanguage(language)#

Set the annotation language.

Arguments
  • languageString.

EXAMPLE

annotation.setLanguage("en");

These properties are only present for some annotation types, so support for them must be checked before use.

hasRect()#

Returns whether the annotation is capable of supporting a bounding box.

Returns

Boolean.

EXAMPLE

var hasRect = annotation.hasRect();
getRect()#

Get the annotation bounding box.

Returns

Array. [ulx,uly,lrx,lry] Rectangle.

EXAMPLE

var rect = annotation.getRect();
setRect(rect)#

Set the annotation bounding box.

Arguments
  • rectArray. [ulx,uly,lrx,lry] Rectangle.

EXAMPLE

annotation.setRect([0,0,100,100]);
getDefaultAppearance()#

Get the default text appearance used for free text annotations.

Returns

{font:String, size:Integer, color:[r,g,b]} Returns a default text appearance with the key/value pairs.

EXAMPLE

var appearance = annotation.getDefaultAppearance();
setDefaultAppearance(font, size, color)#

Set the default text appearance used for free text annotations.

Arguments
  • fontString (“Helv” = Helvetica, “TiRo” = Times New Roman, “Cour” = Courier).

  • sizeInteger.

  • colorArray. The color value.

EXAMPLE

annotation.setDefaultAppearance("Helv", 16, [0,0,0]);
hasInteriorColor()#

Returns whether the annotation has support for an interior color.

Returns

Boolean.

EXAMPLE

var hasInteriorColor = annotation.hasInteriorColor();
getInteriorColor()#

Gets the annotation interior color.

Returns

The color value.

EXAMPLE

var interiorColor = annotation.getInteriorColor();
setInteriorColor(color)#

Sets the annotation interior color.

Arguments

EXAMPLE

annotation.setInteriorColor([0,1,1]);
hasAuthor()#

Returns whether the annotation has support for an author.

Returns

Boolean.

EXAMPLE

var hasAuthor = annotation.hasAuthor();
getAuthor()#

Gets the annotation author.

Returns

String.

EXAMPLE

var author = annotation.getAuthor();
setAuthor(author)#

Sets the annotation author.

Arguments
  • authorString.

EXAMPLE

annotation.setAuthor("Jane Doe");
hasLineEndingStyles()#

Checks the support for line ending styles.

Returns

Boolean.

EXAMPLE

var hasLineEndingStyles = annotation.hasLineEndingStyles();
getLineEndingStyles()#

Gets the line ending styles object.

Returns

{start:String, end:String} Returns an object with the key/value pairs.

EXAMPLE

var lineEndingStyles = annotation.getLineEndingStyles();
setLineEndingStyles(start, end)#

Sets the line ending styles object.

Arguments
  • startString.

  • endString.

EXAMPLE

annotation.setLineEndingStyles("Square", "OpenArrow");

Line ending names

“None”

“Square”

“Circle”

“Diamond”

“OpenArrow”

“ClosedArrow”

“Butt”

“ROpenArrow”

“RClosedArrow”

“Slash”

Line Leaders#

In a PDF line annotation, “line leaders” refer to visual elements that can be added to the endpoints of a line annotation to enhance its appearance or meaning.

Leader lines explained
setLineLeader(ll)#

mutool only

Sets the line leader length.

Arguments
  • llNumber. The length of leader lines that extend from each endpoint of the line perpendicular to the line itself. A positive value means that the leader lines appear in the direction that is clockwise when traversing the line from its starting point to its ending point a negative value indicates the opposite direction.

Note

Setting a value of 0 effectivley removes the line leader.

getLineLeader()#

mutool only

Gets the line leader length.

Returns

Number

setLineLeaderExtension(lle)#

mutool only

Sets the line leader extension.

Arguments
  • lleNumber. A non-negative number representing the length of leader line extensions that extend from the line proper 180 degrees from the leader lines.

Note

Setting a value of 0 effectivley removes the line leader extension.

getLineLeaderExtension()#

mutool only

Gets the line leader extension.

Returns

Number

setLineLeaderOffset(llo)#

mutool only

Sets the line leader offset.

Arguments
  • lloNumber. A non-negative number representing the length of the leader line offset, which is the amount of empty space between the endpoints of the annotation and the beginning of the leader lines.

Note

Setting a value of 0 effectivley removes the line leader offset.

getLineLeaderOffset()#

mutool only

Gets the line leader offset.

Returns

Number

setLineCaption(enable)#

mutool only

Sets whether line caption is enabled or not.

Arguments
  • enableBoolean.

Note

When line captions are enabled then using the setContents() method on the Line will graphically render the caption contents onto the line.

getLineCaption()#

mutool only

Returns whether the line caption is enabled or not.

Returns

Boolean.

setLineCaptionOffset(point)#

mutool only

Sets any line caption offset.

Arguments
  • pointArray. A point, [x, y], specifying the offset of the caption text from its normal position. The first value is the horizontal offset along the annotation line from its midpoint, with a positive value indicating offset to the right and a negative value indicating offset to the left. The second value is the vertical offset perpendicular to the annotation line, with a positive value indicating a shift up and a negative value indicating a shift down.

Offset caption explained

Note

Setting a point of [0,0] effectivley removes the caption offset.

getLineCaptionOffset()#

mutool only

Returns the line caption offset as a point, [x, y].

Returns

Array.


Callouts#

Callouts are used with “FreeText” annotations and allow for a graphical line to point to an area on a page.

Callout annotation
hasCallout()#

mutool only

Returns whether the annotation is capable of supporting a callout or not.

Returns

Boolean.

setCalloutLine(points)#

mutool only

Takes an array of 2 or 3 points.

Arguments
  • points – [ [x1, y1], [x2, y2], [x3, y3]? ].

getCalloutLine()#

mutool only

Returns the array of points.

Returns

[ [x1, y1], [x2, y2], [x3, y3]? ].

setCalloutPoint(point)#

mutool only

Takes a point where the callout should point to.

Arguments
  • points[x,y].

getCalloutPoint()#

mutool only

Returns the callout point.

Returns

[x,y].

setCalloutStyle(style)#

mutool only

Sets the style of the callout line.

Arguments
getCalloutStyle()#

mutool only

Returns the callout style.

Returns

String.


hasIcon()#

Returns whether the annotation is capable of supporting an icon or not.

Returns

Boolean.

EXAMPLE

var hasIcon = annotation.hasIcon();
getIcon()#

Gets the annotation icon name, either one of the standard icon names, or something custom.

Returns

String.

EXAMPLE

var icon = annotation.getIcon();
setIcon(name)#

Sets the annotation icon name, either one of the standard icon names, or something custom. Note that standard icon names can be used to resynthesize the annotation apperance, but custom names cannot.

Arguments
  • nameString.

EXAMPLE

annotation.setIcon("Note");

Icon type

Icon name

File attachment

“Graph”

“PaperClip”

“PushPin”

“Tag”

Sound

“Mic”

“Speaker”

Stamp

“Approved”

“AsIs”

“Confidential”

“Departmental”

“Draft”

“Experimental”

“Expired”

“Final”

“ForComment”

“ForPublicRelease”

“NotApproved”

“NotForPublicRelease”

“Sold”

“TopSecret”

Text

“Comment”

“Help”

“Insert”

“Key”

“NewParagraph”

“Note”

“Paragraph”

hasLine()#

Returns whether the annotation is capable of supporting a line or not.

Returns

Boolean.

EXAMPLE

var hasLine = annotation.hasLine();
getLine()#

Get line end points, represented by an array of two points, each represented as an [x, y] array.

Returns

[[x,y],...].

EXAMPLE

var line = annotation.getLine();
setLine(endpoints)#

Set the two line end points, represented by an array of two points, each represented as an [x, y] array.

Arguments
  • endpoint1[x,y].

  • endpoint2[x,y].

EXAMPLE

annotation.setLine([100,100], [150, 175]);
hasPopup()#

Returns whether the annotation is capable of supporting a popup or not.

Returns

Boolean.

EXAMPLE

var hasPopup = annotation.hasPopup();
getPopup()#

Get annotation popup rectangle.

Returns

[ulx,uly,lrx,lry] Rectangle.

EXAMPLE

var popupRect = annotation.getPopup();
setPopup(rect)#

Set annotation popup rectangle.

Arguments

EXAMPLE

annotation.setPopup([0,0,100,100]);
hasOpen()#

Returns whether the annotation is capable of supporting an open state or not.

Returns

Boolean.

EXAMPLE

var hasOpen = annotation.hasOpen();
getIsOpen()#

Get annotation open state.

Returns

Boolean.

EXAMPLE

var isOpen = annotation.getIsOpen();
setIsOpen(state)#

Set annotation open state.

Arguments
  • stateBoolean.

EXAMPLE

annotation.setIsOpen(true);

Note

“Open” refers to whether the annotation is display in an open state when the page is loaded. A Text Note annotation is considered “Open” if the user has clicked on it to view its contents.

hasFilespec()#

Returns whether the annotation is capable of supporting the annotation file specification.

Returns

Boolean.

EXAMPLE

var hasFileSpec = annotation.hasFilespec();
getFilespec()#

Gets the file specification object.

Returns

Object File Specification Object.

EXAMPLE

var fileSpec = annotation.getFilespec(true);
setFilespec(fileSpecObject)#

Sets the file specification object.

Arguments

EXAMPLE

annotation.setFilespec({filename:"my_file.pdf",
                        mimetype:"application/pdf",
                        size:1000,
                        creationDate:date,
                        modificationDate:date});

The border drawn around some annotations can be controlled by:

hasBorder()#

Returns whether the annotation is capable of supporting border style.

Returns

Boolean.

EXAMPLE

var hasBorder = annotation.hasBorder();
getBorderStyle()#

Get the annotation border style, either of “Solid” or “Dashed”.

Returns

String.

EXAMPLE

var borderStyle = annotation.getBorderStyle();
setBorderStyle(style)#

Set the annotation border style, either of “Solid” or “Dashed”.

Arg

String.

EXAMPLE

annotation.setBorderStyle("Dashed");
getBorderWidth()#

Get the border width in points.

Returns

Float.

EXAMPLE

var w = annotation.getBorderWidth();
setBorderWidth(width)#

Set the border width in points. Retain any existing border effects.

Arguments
  • widthFloat.

EXAMPLE

annotation.setBorderWidth(1.5);
getBorderDashCount()#

Returns the number of items in the border dash pattern.

Returns

Integer.

EXAMPLE

var dashCount = annotation.getBorderDashCount();
getBorderDashItem(i)#

Returns the length of dash pattern item i.

Arguments
  • iInteger Item index.

Returns

Float.

EXAMPLE

var length = annotation.getBorderDashItem(0);
setBorderDashPattern(dashPattern)#

Set the annotation border dash pattern to the given array of dash item lengths. The supplied array represents the respective line stroke and gap lengths, e.g. [1,1] sets a small dash and small gap, [2,1,4,1] would set a medium dash, a small gap, a longer dash and then another small gap.

Arguments
  • dashpattern – [Float, Float, ….].

EXAMPLE

annotation.setBorderDashPattern([2.0, 1.0, 4.0, 1.0]);
clearBorderDash()#

Clear the entire border dash pattern for an annotation.

EXAMPLE

annotation.clearBorderDash();
addBorderDashItem(length)#

Append an item (of the given length) to the end of the border dash pattern.

Arguments
  • lengthFloat.

EXAMPLE

annotation.addBorderDashItem(10.0);

Annotations that have a border effect allows the effect to be controlled by:

hasBorderEffect()#

Returns whether the annotation is capable of supporting border effect.

Returns

Boolean.

EXAMPLE

var hasEffect = annotation.hasBorderEffect();
getBorderEffect()#

Get the annotation border effect, either of “None” or “Cloudy”.

Returns

String.

EXAMPLE

var effect = annotation.getBorderEffect();
setBorderEffect(effect)#

Set the annotation border effect, either of “None” or “Cloudy”.

Arg

String.

EXAMPLE

annotation.setBorderEffect("None");
getBorderEffectIntensity()#

Get the annotation border effect intensity.

Returns

Float.

EXAMPLE

var intensity = annotation.getBorderEffectIntensity();
setBorderEffectIntensity(intensity)#

Set the annotation border effect intensity. Recommended values are between 0 and 2 inclusive.

Arg

Float.

EXAMPLE

annotation.setBorderEffectIntensity(1.5);

Ink annotations consist of a number of strokes, each consisting of a sequence of vertices between which a smooth line will be drawn. These can be controlled by:

hasInkList()#

Returns whether the annotation is capable of supporting ink list.

Returns

Boolean.

EXAMPLE

var hasInkList = annotation.hasInkList();
getInkList()#

Get the annotation ink list, represented as an array of strokes, each an array of points each an array of its X/Y coordinates.

Returns

[...].

EXAMPLE

var inkList = annotation.getInkList();
setInkList(inkList)#

Set the annotation ink list, represented as an array of strokes, each an array of points each an array of its X/Y coordinates.

Arg

[...].

EXAMPLE

annotation.setInkList([
                          [
                              [0,0]
                          ],
                          [
                              [10,10], [20,20], [30,30]
                          ]
                      ]);
clearInkList()#

Clear the list of ink strokes for the annotation.

EXAMPLE

annotation.clearInkList();
addInkList(stroke)#

To the list of strokes, append a stroke, represented as an array of vertices each an array of its X/Y coordinates.

Arguments
  • stroke[].

EXAMPLE

annotation.addInkList(
                        [
                            [0,0]
                        ],
                        [
                            [10,10], [20,20], [30,30]
                        ]
                     );
addInkListStroke()#

Add a new empty stroke to the ink annotation.

EXAMPLE

annotation.addInkListStroke();
addInkListStrokeVertex(vertex)#

Append a vertex to end of the last stroke in the ink annotation. The vertex is an array of its X/Y coordinates.

Arguments
  • vertex[...].

EXAMPLE

annotation.addInkListStrokeVertex([0,0]);

Text markup and redaction annotations consist of a set of quadadrilaterals controlled by:

hasQuadPoints()#

Returns whether the annotation is capable of supporting quadpoints.

Returns

Boolean.

EXAMPLE

var hasQuadPoints = annotation.hasQuadPoints();
getQuadPoints()#

Get the annotation quadpoints, describing the areas affected by text markup annotations and link annotations.

Returns

[...].

EXAMPLE

var quadPoints = annotation.getQuadPoints();
setQuadPoints(quadPoints)#

Set the annotation quadpoints, describing the areas affected by text markup annotations and link annotations.

Arguments
  • quadPoints[...].

EXAMPLE

annotation.setQuadPoints([
                            [1,2,3,4,5,6,7,8],
                            [1,2,3,4,5,6,7,8],
                            [1,2,3,4,5,6,7,8]
                        ]);
clearQuadPoints()#

Clear the list of quad points for the annotation.

EXAMPLE

annotation.clearQuadPoints();
addQuadPoint(quadpoint)#

Append a single quad point as an array of 8 elements, where each pair are the X/Y coordinates of a corner of the quad.

Arguments
  • quadpoint[].

EXAMPLE

annotation.addQuadPoint([1,2,3,4,5,6,7,8]);

Polygon and polyline annotations consist of a sequence of vertices with a straight line between them. Those can be controlled by:

hasVertices()#

Returns whether the annotation is capable of supporting annotation vertices.

Returns

Boolean.

EXAMPLE

var hasVertices = annotation.hasVertices();
getVertices()#

Get the annotation vertices, represented as an array of vertices each an array of its X/Y coordinates.

Returns

[...].

EXAMPLE

var vertices = annotation.getVertices();
setVertices(vertices)#

Set the annotation vertices, represented as an array of vertices each an array of its X/Y coordinates.

Arguments
  • vertices[...].

EXAMPLE

annotation.setVertices([
                        [0,0],
                        [10,10],
                        [20,20]
                      ]);
clearVertices()#

Clear the list of vertices for the annotation.

EXAMPLE

annotation.clearVertices();
addVertex(vertex)#

Append a single vertex as an array of its X/Y coordinates.

Arguments
  • vertex[...].

EXAMPLE

annotation.addVertex([0,0]);
applyRedaction(blackBoxes, imageMethod)#

Applies redaction to the annotation.

Arguments
  • blackBoxesBoolean Whether to use black boxes at each redaction or not.

  • imageMethodInteger. 0 for no redactions, 1 to redact entire images, 2 for redacting just the covered pixels.

Note

Redactions are secure as they remove the affected content completely.

EXAMPLE

annotation.applyRedaction(true, 1);

PDFWidget#

Widgets refer to components which make up form items such as buttons, text inputs and signature fields.

To get the widgets on a page see: PDFPage getWidgets().

Instance methods

getFieldType()#

Return String indicating type of widget: “button”, “checkbox”, “combobox”, “listbox”, “radiobutton”, “signature” or “text”.

Returns

String.

EXAMPLE

var type = widget.getFieldType();
getFieldFlags()#

Return the field flags. Refer to the PDF specification for their meanings.

Returns

Integer which determines the bit-field value.

EXAMPLE

var flags = widget.getFieldFlags();
getRect()#

Get the widget bounding box.

Returns

[ulx,uly,lrx,lry] Rectangle.

EXAMPLE

var rect = widget.getRect();
setRect(rect)#

Set the widget bounding box.

Arguments

EXAMPLE

widget.setRect([0,0,100,100]);
getMaxLen()#

Get maximum allowed length of the string value.

Returns

Integer.

EXAMPLE

var length = widget.getMaxLen();
getValue()#

Get the widget value.

Returns

String.

EXAMPLE

var value = widget.getValue();
setTextValue(value)#

Set the widget string value.

Arguments
  • valueString.

EXAMPLE

widget.setTextValue("Hello World!");
setChoiceValue(value)#

Sets the value against the widget.

Arguments
  • valueString.

EXAMPLE

widget.setChoiceValue("Yes");
toggle()#

Toggle the state of the widget, returns 1 if the state changed.

Returns

Integer.

EXAMPLE

var state = widget.toggle();
getOptions()#

Returns an array of strings which represents the value for each corresponding radio button or checkbox field.

Returns

[...].

EXAMPLE

var options = widget.getOptions();
layoutTextWidget()#

mutool only

Layout the value of a text widget. Returns a Text Layout Object.

Returns

Object.

EXAMPLE

var layout = widget.layoutTextWidget();
isReadOnly()#

If the value is read only and the widget cannot be interacted with.

Returns

Boolean.

EXAMPLE

var isReadOnly = widget.isReadOnly();
getLabel()#

Get the field name as a string.

Returns

String.

EXAMPLE

var label = widget.getLabel();
getEditingState()#

mutool only

Gets whether the widget is in editing state.

Returns

Boolean.

EXAMPLE

var state = widget.getEditingState();
setEditingState(state)#

mutool only

Set whether the widget is in editing state.

Arguments
  • stateBoolean.

EXAMPLE

widget.getEditingState(false);

Note

When in editing state any changes to the widget value will not cause any side-effects such as changing other widgets or running JavaScript. This is intended for, e.g. when a text widget is interactively having characters typed into it. Once editing is finished the state should reverted back, before updating the widget value again.

update()#

Update the appearance stream to account for changes to the widget.

EXAMPLE

widget.update();

Signature Methods#

isSigned()#

mutool only

Returns true if the signature is signed.

Returns

Boolean.

EXAMPLE

var isSigned = widget.isSigned();
validateSignature()#

mutool only

Returns number of updates ago when signature became invalid. Returns 0 is signature is still valid, 1 if it became invalid during the last save, etc.

Returns

Integer.

EXAMPLE

var validNum = widget.validateSignature();
checkCertificate()#

mutool only

Returns “OK” if signature checked out OK, otherwise a text string containing an error message, e.g. “Self-signed certificate.” or “Signature invalidated by change to document.”, etc.

Returns

String.

EXAMPLE

var result = widget.checkCertificate();
getSignatory()#

mutool only

Returns a text string with the distinguished name from a signed signature, or a text string with an error message.

Returns

String.

EXAMPLE

var signatory = widget.getSignatory();
previewSignature(signer, signatureConfig, image, reason, location)#

mutool only

Return a Pixmap preview of what the signature would look like if signed with the given configuration. Reason and location may be undefined, in which case they are not shown.

Arguments
Returns

Pixmap.

EXAMPLE

var pixmap = widget.previewSignature(signer, {showLabels:true, showDate:true}, image, "", "");
sign(signer, signatureConfig, image, reason, location)#

mutool only

Sign the signature with the given configuration. Reason and location may be undefined, in which case they are not shown.

Arguments

EXAMPLE

widget.sign(signer, {showLabels:true, showDate:true}, image, "", "");
clearSignature()#

mutool only

Clear a signed signature, making it unsigned again.

EXAMPLE

widget.clearSignature();
incrementalChangesSinceSigning()#

mutool only

Returns true if there have been incremental changes since the signature widget was signed.

EXAMPLE

var changed = widget.incrementalChangesSinceSigning();

Widget Events#

eventEnter()#

mutool only

Trigger the event when the pointing device enters a widget’s active area.

EXAMPLE

widget.eventEnter();
eventExit()#

mutool only

Trigger the event when the pointing device exits a widget’s active area.

EXAMPLE

widget.eventExit();
eventDown()#

mutool only

Trigger the event when the pointing device’s button is depressed within a widget’s active area.

EXAMPLE

widget.eventDown();
eventUp()#

mutool only

Trigger the event when the pointing device’s button is released within a widget’s active area.

EXAMPLE

widget.eventUp();
eventFocus()#

mutool only

Trigger the event when the a widget gains input focus.

EXAMPLE

widget.eventFocus();
eventBlur()#

mutool only

Trigger the event when the a widget loses input focus.

EXAMPLE

widget.eventBlur();

PDFPKCS7Signer#

Creating a Signer

To create a signer object an instance of PDFPKCS7Signer is required.

new(filename, password)#

mutool only

Read a certificate and private key from a pfx file and create a signer to hold this information. Used with PDFWidget.sign().

Arguments
  • filenameString.

  • passwordString.

Returns

PDFPKCS7Signer.

EXAMPLE

var signer = new PDFPKCS7Signer(<file_name>, <password>);

OutlineIterator#

An outline iterator can be used to walk over all the items in an Outline and query their properties. To be able to insert items at the end of a list of sibling items, it can also walk one item past the end of the list. To get an instance of OutlineIterator use Document outlineIterator.

Note

In the context of a PDF file, the document’s Outline is also known as Table of Contents or Bookmarks.

Instance methods

item()#

Return an Outline Iterator Object or undefined if out of range.

Returns

Object.

EXAMPLE

var obj = outlineIterator.item();
next()#

Move the iterator position to “next”.

Returns

Int which is negative if this movement is not possible, 0 if the new position has a valid item, or 1 if the new position has no item but one can be inserted here.

EXAMPLE

var result = outlineIterator.next();
prev()#

Move the iterator position to “previous”.

Returns

Int which is negative if this movement is not possible, 0 if the new position has a valid item, or 1 if the new position has no item but one can be inserted here.

EXAMPLE

var result = outlineIterator.prev();
up()#

Move the iterator position “up”.

Returns

Int which is negative if this movement is not possible, 0 if the new position has a valid item, or 1 if the new position has no item but one can be inserted here.

EXAMPLE

var result = outlineIterator.up();
down()#

Move the iterator position “down”.

Returns

Int which is negative if this movement is not possible, 0 if the new position has a valid item, or 1 if the new position has no item but one can be inserted here.

EXAMPLE

var result = outlineIterator.down();
insert(item)#

Insert item before the current item. The position does not change.

Arguments
Returns

Int which is 0 if the current position has a valid item, or 1 if the position has no valid item.

EXAMPLE

var valid = outlineIterator.insert(item);
delete()#

Delete the current item. This implicitly moves to the next item.

Returns

Int which is 0 if the new position has a valid item, or 1 if the position contains no valid item, but one may be inserted at this position.

EXAMPLE

outlineIterator.delete();
update(item)#

Updates the current item properties with values from the supplied item’s properties.

Arguments

EXAMPLE

outlineIterator.update(item);

Archive#

mutool only

new Archive(path)#

Constructor method.

Create a new archive based either on a tar or zip file or the contents of a directory.

Arguments
  • pathString.

Returns

Archive.

EXAMPLE

var archive = new mupdf.Archive("example1.zip");
var archive2 = new mupdf.Archive("example2.tar");

Instance methods

getFormat()#

Returns a string describing the archive format.

Returns

String.

EXAMPLE

var archive = new mupdf.Archive("example1.zip");
print(archive.getFormat());
countEntries()#

Returns the number of entries in the archive.

Returns

Integer.

EXAMPLE

var archive = new mupdf.Archive("example1.zip");
var numEntries = archive.countEntries();
listEntry(idx)#

Returns the name of entry number idx in the archive.

Arguments
  • idxInteger.

Returns

String.

EXAMPLE

var archive = new mupdf.Archive("example1.zip");
var entry = archive.listEntry(0);
hasEntry(name)#

Returns true if an entry of the given name exists in the archive.

Arguments
  • nameString.

Returns

Boolean.

EXAMPLE

var archive = new mupdf.Archive("example1.zip");
var hasEntry = archive.hasEntry("file1.txt");
readEntry(name)#

Returns the contents of the entry of the given name.

Arguments
  • nameString.

Returns

String.

EXAMPLE

var archive = new mupdf.Archive("example1.zip");
var contents = archive.readEntry("file1.txt");

MultiArchive#

mutool only

new MultiArchive()#

Constructor method.

Create a new empty multi archive.

Returns

MultiArchive.

EXAMPLE

var multiArchive = new mupdf.MultiArchive();

Instance methods

mountArchive(subArchive, path)#

Add an archive to the set of archives handled by a multi archive. If path is null, the subArchive contents appear at the top-level, otherwise they will appear prefixed by the string path.

Arguments
  • subArchiveArchive.

  • pathString.

EXAMPLE

var archive = new mupdf.MultiArchive();
archive.mountArchive(new mupdf.Archive("example1.zip"), null);
archive.mountArchive(new mupdf.Archive("example2.tar"), "subpath");
print(archive.hasEntry("file1.txt"));
print(archive.hasEntry("subpath/file2.txt"));

Assuming that example1.zip contains a file1.txt and example2.tar contains file2.txt, the multiarchive now allows access to “file1.txt” and “subpath/file2.txt”.

TreeArchive#

mutool only

new TreeArchive()#

Constructor method.

Create a new empty tree archive.

Returns

TreeArchive.

EXAMPLE

var treeArchive = new mupdf.TreeArchive();

Instance methods

add(name, buffer)#

Add a named buffer to a tree archive.

Arguments
  • nameString.

  • bufferBuffer.

EXAMPLE

var buf = new mupdf.Buffer();
buf.writeLine("hello world!");
var archive = new mupdf.TreeArchive();
archive.add("file2.txt", buf);
print(archive.hasEntry("file2.txt"));

Story#

mutool only

new Story(contents, userCSS, em, archive)#

Constructor method.

Create a new story with the given contents, formatted according to the provided userCSS and em size, and an archive to lookup images, etc.

Arguments
  • contentsString HTML source code. If omitted, a basic minimum is generated.

  • userCSSString CSS source code. If provided, must contain valid CSS specifications.

  • emFloat The default text font size.

  • archive – An Archive from which to load resources for rendering. Currently supported resource types are images and text fonts. If omitted, the Story will not try to look up any such data and may thus produce incomplete output.

EXAMPLE

var story = new mupdf.Story(<contents>, <css>, <em>, <archive>);

Instance methods

document()#

Return an XML for an unplaced story. This allows adding content before placing the Story.

Returns

XML.

EXAMPLE

var xml = story.document();
place(rect)#

Place (or continue placing) a Story into the supplied rectangle, returning a Placement Result Object. Call draw() to draw the placed content before calling place() again to continue placing remaining content.

Arguments
Returns

Placement Result Object.

EXAMPLE

var result = story.place([0,0,100,100]);
draw(device, transform)#

Draw the placed Story to the given device with the given transform.

Arguments
  • deviceDevice.

  • transform[a,b,c,d,e,f]. The transform matrix.

EXAMPLE

story.draw(device, mupdf.Matrix.identity);

XML#

mutool only

This represents an HTML or an XML node. It is a helper class intended to access the DOM (Document Object Model) content of a Story object.

Instance methods

body()#

Return an XML for the body element.

Returns

XML.

EXAMPLE

var result = xml.body();
documentElement()#

Return an XML for the top level element.

Returns

XML.

EXAMPLE

var result = xml.documentElement();
createElement(tag)#

Create an element with the given tag type, but do not link it into the XML yet.

Arguments
  • tagString.

Returns

XML.

EXAMPLE

var result = xml.createElement("div");
createTextNode(text)#

Create a text node with the given text contents, but do not link it into the XML yet.

Arguments
  • textString.

Returns

XML.

EXAMPLE

var result = xml.createElement("Hello world!");
find(tag, attribute, value)#

Find the element matching the tag, attribute and value. Set either of those to null to match anything.

Arguments
  • tagString.

  • attributeString.

  • valueString.

Returns

XML.

EXAMPLE

var result = xml.find("tag", "attribute", "value");
findNext(tag, attribute, value)#

Find the next element matching the tag, attribute and value. Set either of those to null to match anything.

Arguments
  • tagString.

  • attributeString.

  • valueString.

Returns

XML.

EXAMPLE

var result = xml.findNext("tag", "attribute", "value");
appendChild(dom, childDom)#

Insert an element as the last child of a parent, unlinking the child from its current position if required.

Arguments
  • domXML.

  • childDomXML.

EXAMPLE

xml.appendChild(dom, childDom);
insertBefore(dom, elementDom)#

Insert an element before this element, unlinking the new element from its current position if required.

Arguments
  • domXML.

  • elementDomXML.

EXAMPLE

xml.insertBefore(dom, elementDom);
insertAfter(dom, elementDom)#

Insert an element after this element, unlinking the new element from its current position if required.

Arguments
  • domXML.

  • elementDomXML.

EXAMPLE

xml.insertAfter(dom, elementDom);
remove()#

Remove this element from the XML. The element can be added back elsewhere if required.

Returns

XML.

EXAMPLE

var result = xml.remove();
clone()#

Clone this element (and its children). The clone is not yet linked into the XML.

Returns

XML.

EXAMPLE

var result = xml.clone();
firstChild()#

Return the first child of the element as a XML, or null if no child exist.

Returns

XML | null.

EXAMPLE

var result = xml.firstChild();
parent()#

Return the parent of the element as a XML, or null if no parent exists.

Returns

XML | null.

EXAMPLE

var result = xml.parent();
next()#

Return the next element as a XML, or null if no such element exists.

Returns

XML | null.

EXAMPLE

var result = xml.next();
previous()#

Return the previous element as a XML, or null if no such element exists.

Returns

XML | null.

EXAMPLE

var result = xml.previous();
addAttribute(attribute, value)#

Add attribute with the given value, returns the updated element as an XML.

Arguments
  • attributeString.

  • valueString.

Returns

XML.

EXAMPLE

var result = xml.addAttribute("attribute", "value");
removeAttribute(attribute)#

Remove the specified attribute from the element.

Arguments
  • attributeString.

EXAMPLE

xml.removeAttribute("attribute");
attribute(attribute)#

Return the element’s attribute value as a String, or null if no such attribute exists.

Arguments
  • attributeString.

Returns

String | null.

EXAMPLE

var result = xml.attribute("attribute");
getAttributes()#

Returns a dictionary object with properties and their values corresponding to the element’s attributes and their values.

Returns

{}.

EXAMPLE

var dict = xml.getAttributes();

Global MuPDF methods#

print(...)#

mutool only

Print arguments to stdout, separated by spaces and followed by a newline.

Arguments
  • ... – Arguments to print.

EXAMPLE

var document = new Document.openDocument("my_pdf.pdf");
print(document); // [object pdf_document]
write(...)#

mutool only

Print arguments to stdout, separated by spaces.

Arguments
  • ... – Arguments to print.

repr(object)#

mutool only

Format the object into a string with JavaScript syntax.

Arguments
  • object – Object to format.

EXAMPLE

var document = new Document.openDocument("my_pdf.pdf");
print(document.getJournal()); // "[object Object]"
print(repr(document.getJournal())); // "{position: 0, steps: []}"
gc(report)#

mutool only

Run the garbage collector to free up memory. Optionally report statistics on the garbage collection.

Arguments
  • reportBoolean If true then the results will be printed to stdout.

load(fileName)#

mutool only

Load and execute script in fileName.

Arguments
  • fileNameString JavaScript file to load.

read(fileName)#

mutool only

Read the contents of a file and return them as a UTF-8 encoded string.

Arguments
  • fileNameString.

readline()#

mutool only

Read one line of input from stdin and return it as a string.

Returns

String.

require(module)#

mutool only

Load a JavaScript module.

Arguments
  • module – Module to load.

setUserCSS(userStyleSheet, usePublisherStyles)#

mutool only

Set user styles and whether to use publisher styles when laying out reflowable documents.

Arguments
  • userStyleSheet – Link to CSS stylesheet file.

  • usePublisherStylesBoolean.

quit(exitStatus)#

mutool only

Terminate script execution and exit with the provided exit status.

Arguments
  • exitStatusInteger exit status to return.

PDF Processor#

A PDF processor provides callbacks that get called for each PDF operator handled by PDFPage process() & PDFAnnotation process() methods. The callbacks whose names start with op_ correspond to each PDF operator. Refer to the PDF specification for what these do and what the callback arguments are.

Methods#

Main methods#

  • push_resources(resources)

  • pop_resources()

General graphics state callbacks#

  • op_w(lineWidth)

  • op_j(lineJoin)

  • op_J(lineCap)

  • op_M(miterLimit)

  • op_d(dashPattern, phase)

  • op_ri(intent)

  • op_i(flatness)

  • op_gs(name, extGState)

Special graphics state#

  • op_q()

  • op_Q()

  • op_cm(a, b, c, d, e, f)

Path construction#

  • op_m(x, y)

  • op_l(x, y)

  • op_c(x1, y1, x2, y2, x3, y3)

  • op_v(x2, y2, x3, y3)

  • op_y(x1, y1, x3, y3)

  • op_h()

  • op_re(x, y, w, h)

Path painting#

  • op_S()

  • op_s()

  • op_F()

  • op_f()

  • op_fstar()

  • op_B()

  • op_Bstar()

  • op_b()

  • op_bstar()

  • op_n()

Clipping paths#

  • op_W()

  • op_Wstar()

Text objects#

  • op_BT()

  • op_ET()

Text state#

  • op_Tc(charSpace)

  • op_Tw(wordSpace)

  • op_Tz(scale)

  • op_TL(leading)

  • op_Tf(name, size)

  • op_Tr(render)

  • op_Ts(rise)

Text positioning#

  • op_Td(tx, ty)

  • op_TD(tx, ty)

  • op_Tm(a, b, c, d, e, f)

  • op_Tstar()

Text showing#

  • op_TJ(textArray)

  • op_Tj(stringOrByteArray)

  • op_squote(stringOrByteArray)

  • op_dquote(wordSpace, charSpace, stringOrByteArray)

Type 3 fonts#

  • op_d0(wx, wy)

  • op_d1(wx, wy, llx, lly, urx, ury)

Color#

  • op_CS(name, colorspace)

  • op_cs(name, colorspace)

  • op_SC_color(color)

  • op_sc_color(color)

  • op_SC_pattern(name, patternID, color)

    API not settled, arguments may change in the future.

  • op_sc_pattern(name, patternID, color)

    API not settled, arguments may change in the future.

  • op_SC_shade(name, shade)

    API not settled, arguments may change in the future.

  • op_sc_shade(name, shade)

    API not settled, arguments may change in the future.

  • op_G(gray)

  • op_g(gray)

  • op_RG(r, g, b)

  • op_rg(r, g, b)

  • op_K(c, m, y, k)

  • op_k(c, m, y, k)

Shadings, images and XObjects#

  • op_BI(image, colorspace)

  • op_sh(name, shade)

    API not settled, arguments may change in the future.

  • op_Do_image(name, image)

  • op_Do_form(xobject, resources)

Marked content#

  • op_MP(tag)

  • op_DP(tag, raw)

  • op_BMC(tag)

  • op_BDC(tag, raw)

  • op_EMC()

Compatibility#

  • op_BX()

  • op_EX()


This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of that license. Refer to licensing information at artifex.com or contact Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco, CA 94129, USA, for further information.

Discord logo