mutool run script.js [ arguments ... ]
If invoked without any arguments, it will drop you into an interactive REPL (read-eval-print-loop). On the interactive prompt, if you prefix a line with an equal (‘=’) character it will automatically print the result of the line.
Create and edit PDF documents:
- pdf-create-lowlevel.js: Create a PDF document using only low-level functions.
- pdf-create.js: Create a PDF document using helper functions.
- pdf-merge.js: Merge pages from multiple PDF documents into one PDF file.
Graphics and the device interface:
- draw-document.js: Draw all pages in a document to PNG files.
- draw-device.js: Use device API to draw graphics and save as a PNG file.
- create-thumbnail.js: Create a PDF from rendered page thumbnails.
Several global functions that are common for command line shells are available:
Run the garbage collector to free up memory. Optionally report statistics on the garbage collection.
Load and execute script in ‘fileName’.
Print arguments to stdout, separated by spaces and followed by a newline.
Exit the shell.
Read the contents of a file and return them as a UTF-8 decoded string.
Read one line of input from stdin and return it as a string.
Print arguments to stdout, separated by spaces.
The 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.
Create a new empty buffer.
Create a new buffer with the contents of a file.
The number of bytes in the buffer.
Read/write the byte at index ‘n’. Will throw exceptions on out of bounds accesses.
Append a single byte to the end of the buffer.
Encode a Unicode character as UTF-8 and append to the end of the buffer.
Append arguments to the end of the buffer, separated by spaces, ending with a newline.
Append arguments to the end of the buffer, separated by spaces.
Append the contents of the ‘data’ buffer to the end of the buffer.
Write the contents of the buffer to a file.
Matrices and Rectangles
All dimensions are in points unless otherwise specified.
Matrices are simply 6-element arrays representing a 3-by-3 transformation matrix as
/ a b 0 \
| c d 0 |
\ e f 1 /
The identity matrix, shorthand for
Return a scaling matrix, shorthand for
Return a translation matrix, shorthand for
Concatenate matrices a and b. Bear in mind that matrix multiplication is not commutative.
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):
If the minimum x coordinate is bigger than the maximum x coordinate, MuPDF treats the rectangle as infinite in size.
Document and Page
MuPDF can open many document types (PDF, XPS, CBZ, EPUB, FB2 and a handful of image formats).
Open the named document.
Returns true if a password is required to open this password protected PDF.
Returns true if the password matches.
Return various metadata information. The common keys are: “format”, “encryption”, “info:Author”, and “info:Title”.
Document#layout(pageWidth, pageHeight, fontSize)
Layout a reflowable document (EPUB, FB2, or XHTML) to fit the specified page and font size.
Count the number of pages in the document. This may change if you call the layout function with different parameters.
Returns a Page object for the given page number. Page number zero (0) is the first page in the document.
Returns an array with the outline (table of contents). 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 true if the document is a PDF document.
Set user styles and whether to use publisher styles when laying out reflowable documents.
Returns a rectangle containing the page dimensions.
Page#run(device, transform, skipAnnotations)
Page#toPixmap(transform, colorspace, alpha, skipAnnotations)
Render the page into a Pixmap, using the transform and colorspace. If alpha is true, the page will be drawn on a transparent background, otherwise white.
Record the contents on the page into a DisplayList.
Extract the text on the page into a StructuredText object.
Search for ‘needle’ text on the page and return an array with rectangles of all matches found.
Return array of all annotations on the page.
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.
Returns true if the page is from a PDF document.
Returns a rectangle containing the location and dimension of the annotation.
Calls device functions to draw the annotation.
Annotation#toPixmap(transform, colorspace, alpha)
Render the annotation into a Pixmap, using the transform and colorspace.
Record the contents of the annotation into a DisplayList.
Returns the PDFObject/PDFAnnotation for the annotation, if the document is a PDF file.
StructuredText objects hold text from a page that has been analyzed and grouped into blocks, lines, and spans.
Search the text for all instances of ‘needle’, and return an array with rectangles of all matches found.
Return an array with rectangles needed to highlight a selection defined by the two corners of the rectangle.
Return the text from the selection defined by the two corners of the rectangle.
The default grayscale colorspace.
The default RGB colorspace.
The default RGB colorspace, but with components in reverse order.
The default CMYK colorspace.
A grayscale colorspace has one component, RGB has 3, CMYK has 4, and DeviceN may have any number of components.
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)
Create a new pixmap. The pixel data is not initialized; and will contain garbage.
Clear the pixels to the specified value. Pass 255 for white, or undefined for transparent.
Return the pixmap bounds.
Number of colors; plus one if an alpha channel is present.
True if alpha channel is present.
Number of bytes per row.
Image resolution in dots per inch.
Pixmap#getSample(x, y, k)
Get the value of component k at position x, y (relative to the image origin: 0, 0 is the top left pixel).
Save the pixmap as a PNG. Only works for Gray and RGB images.
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)
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.
DisplayList and DisplayListDevice
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.
Create an empty display list. The mediabox rect has the bounds of the page in points.
Play back the recorded device calls onto the device.
DisplayList#toPixmap(transform, colorspace, alpha)
Render display list to a pixmap. If alpha is true, it will render to a transparent background, otherwise white.
Extract the text in the display list into a StructuredText object.
Search the display list text for all instances of ‘needle’, and return an array with rectangles of all matches found.
Create a device for recording onto a display list.
Many of the methods take graphics objects as arguments: Path, Text, Image, and Shade.
The stroking state is a dictionary with keys for:
startCap, dashCap, endCap:
“Butt”, “Round”, “Square”, or “Triangle”.
Set startCap, dashCap, and endCap all at once.
“Miter”, “Round”, “Bevel”, or “MiterXPS”.
Thickness of the line.
Maximum ratio of the miter length to line width, before beveling the join instead.
Starting offset for dash pattern.
Array of on/off dash lengths.
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.
Device#fillPath(path, evenOdd, transform, colorspace, color, alpha)
Device#strokePath(path, stroke, transform)
Device#clipPath(path, evenOdd, transform, colorspace, color, alpha)
Device#clipStrokePath(path, stroke, transform)
Fill/stroke/clip a path.
Device#fillText(text, transform, colorspace, color, alpha)
Device#strokeText(text, stroke, transform, colorspace, color, alpha)
Device#clipStrokeText(text, stroke, transform)
Fill/stroke/clip a text object.
Invisible text that can be searched but should not be visible, such as for overlaying a scanned OCR image.
Device#fillShade(shade, transform, alpha)
Device#fillImage(shade, transform, alpha)
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.
Device#fillImageMask(shade, transform, colorspace, color, alpha)
An image mask is an image without color. Fill with the color where the image is opaque.
Clip graphics using the image to mask the areas to be drawn.
Device#beginMask(area, luminosity, backdropColorspace, backdropColor)
Create a soft mask. Any drawing commands between beginMask and endMask are grouped and used as a clip mask. 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.
Pop the clip mask installed by the last clipping operation.
Device#beginGroup(area, isolated, knockout, blendmode, alpha)
Push/pop a transparency blending group. Blendmode is one of the standard PDF blend modes: “Normal”, “Multiply”, “Screen”, etc. See the PDF reference for details on isolated and knockout.
Device#beginTile(areaRect, viewRect, xStep, yStep, transform)
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.
Tell the device that we are done and flush any pending output.
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.
Create a new empty path.
Lift and move the pen to the coordinate.
Draw a line to the coordinate.
Path#curveTo(x1, y1, x2, y2, x3, y3)
Draw a cubic bezier curve to (x3,y3) using (x1,y1) and (x2,y2) as control points.
Close the path by drawing a line to the last moveTo.
Path#rect(x1, y1, x2, y2)
Shorthand for moveTo, lineTo, lineTo, lineTo, closePath to draw a rectangle.
Call moveTo, lineTo, curveTo and closePath methods on the pathWalker to replay the path.
A Text object contains text.
Create a new empty text object.
Text#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’. WMode is 0 for horizontal writing, and 1 for vertical writing.
Text#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.
Call showGlyph on textWalker for each glyph in the text object.
Font objects can be created from TrueType, OpenType, Type1 or CFF fonts. In PDF there are also special Type3 fonts.
new Font(fontName or fileName)
Create a new font, either using a built-in font name or a filename. The built-in 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, and ZapfDingbats.
Get the font name.
Get the glyph index for a Unicode character. Glyph zero (.notdef) is returned if the font does not have a glyph for the character.
Return advance width for a glyph in either horizontal or vertical writing mode.
Image objects are similar to Pixmaps, but can contain compressed data.
new Image(pixmap or fileName)
Create a new image from a pixmap data, or load an image from a file.
Image size in pixels.
Image resolution in dots per inch.
Create a pixmap from the image. The scaledWidth and scaledHeight arguments are optional, but may be used to decode a down-scaled pixmap.
Document writer objects are used to create new documents in several formats.
new DocumentWriter(filename, format, options)
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 suffix. The options argument is a comma-separated list of flags and key-value pairs. See below for more details.
Begin rendering a new page. Returns a Device that can be used to render the page graphics.
Finish the page rendering. The argument must be the same device object that was returned by the beginPage method.
Finish the document and flush any pending output.The current output formats supported are CBZ,
The current output formats supported are CBZ, PNG and PDF.
The image format (CBZ, PNG, etc) output options are:
Rotate rendered pages N degrees counterclockwise.
resolution=N, x-resolution=N, y-resolution=N
Render each page to an image at N pixels per inch.
Render pages to fit N pixels wide (ignore resolution option).
Render pages to fit N pixels tall (ignore resolution option).
Render using specified colorspace.
Render pages with alpha channel and transparent background.
The PDF output options are:
optimize for web browsers.
remove unused objects.
Remove unused objects and compact cross-reference table.
Remove unused objects, compact cross-reference table, and remove duplicate objects.
Pretty-print objects with indentation.
ASCII hex encodes binary streams.
Compress embedded fonts.
Compress all streams.
Decompress all streams (except when compress-fonts or compress-images).
Clean up graphics commands in content streams.
PDFDocument and PDFObject
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().
Create a new empty PDF document.
Load a PDF document from file.
Write the PDF document to file. The write options are a string of comma-separated options (see the document writer options).
PDF Object Access
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.
The trailer dictionary. This contains indirect references to the Root and Info dictionaries.
Return the number of objects in the PDF. Object number 0 is reserved, and may not be used for anything.
Allocate a new numbered object in the PDF, and return an indirect reference to it. The object itself is uninitialized.
Delete the object referred to by the indirect reference.
PDFObjects are always bound to the document that created them. Do NOT mix and match objects from one document to another document!
Add ‘obj’ to the PDF as a numbered object, and return an indirect reference to it.
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.
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 the Filter and DecodeParms.
The following functions can be used to copy objects from one document to another:
PDFDocument#graftObject(sourceDocument, object, sourceGraftMap)
Deep copy an object into the destination document. The graft map may be null, but should be used if you are copying several objects from the same source document using multiple calls to graftObject.
Create a graft map for the source document, so that objects that have already been copied can be found again.
Arrays and dictionaries are recursively translated to PDF arrays and dictionaries. Be aware of cycles though! The translation does NOT cope with cyclic references!
PDFObject#get(key or index)
PDFObject#put(key or index, value)
PDFObject#delete(key or index)
Access dictionaries and arrays. Dictionaries and arrays can also be accessed using normal property syntax: obj.Foo = 42; delete obj.Foo; x = obj.
If the object is an indirect reference, return the object it points to; otherwise return the object itself.
Iterate over all the entries in a dictionary or array and call fun for each key-value pair.
Length of the array.
Append item to the end of the array.
The only way to access a stream is via an indirect object since all streams are numbered objects.
Is the object an indirect reference.
Return the object number the indirect reference points to.
True if the object is an indirect reference pointing to a stream.
Read the contents of the stream object into a Buffer.
Read the raw, uncompressed, contents of the stream object into a Buffer.
Update the object the indirect reference points to.
Update the contents of the stream the indirect reference points to. This will update the Length, Filter and DecodeParms automatically.
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.
Is the object the ‘null’ object?
Is the object a boolean?
Get the boolean primitive value.
Is the object a number?
Get the number primitive value.
Is the object a name?
Get the name as a string.
Is the object a string?
Convert a string to an array of byte values.
PDF Page Access
All page objects are structured into a page tree, which defines the order the pages appear in.
Number of pages in the document.
Return the page object for a page number. The first page is number zero.
Delete the numbered page.
Insert the page 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.
PDFDocument#addPage(mediabox, rotate, resources, contents)
Create a new page object. Note: this function does NOT add it to the page tree.
Create a PDF object from the Font object as a WinAnsiEncoding encoded simple font.
Create a PDF object from the Font object as an Identity-H encoded CID font.
Create a PDF object from the Image object.
PDF Annotations (WORK IN PROGRESS!)
Create a new blank annotation of a given type. The type must be one of the annotation subtypes listed in the PDF reference.
Delete the annotation from the page.
Return the annotation subtype.
Get/set the annotation flags.
Update the appearance stream to account for changes in the annotation.