Using MuPDF with C#
This intends to be an introductory guide into how to use MuPDF with your C code and as such assumes at least an intermediate knowledge of programming with C.
Basic MuPDF usage example#
For an example of how to use MuPDF in the most basic way, see docs/examples/example.c
.
/*
How to use MuPDF to render a single page and print the result as
a PPM to stdout.
To build this example in a source tree and render first page at
100% zoom with no rotation, run:
make examples
./build/debug/example document.pdf 1 100 0 > page1.ppm
To build from installed sources, and render the same document, run:
gcc -I/usr/local/include -o example \
/usr/local/share/doc/mupdf/examples/example.c \
/usr/local/lib/libmupdf.a \
/usr/local/lib/libmupdfthird.a \
-lm
./example document.pdf 1 100 0 > page1.ppm
*/
#include <mupdf/fitz.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char *input;
float zoom, rotate;
int page_number, page_count;
fz_context *ctx;
fz_document *doc;
fz_pixmap *pix;
fz_matrix ctm;
int x, y;
if (argc < 3)
{
fprintf(stderr, "usage: example input-file page-number [ zoom [ rotate ] ]\n");
fprintf(stderr, "\tinput-file: path of PDF, XPS, CBZ or EPUB document to open\n");
fprintf(stderr, "\tPage numbering starts from one.\n");
fprintf(stderr, "\tZoom level is in percent (100 percent is 72 dpi).\n");
fprintf(stderr, "\tRotation is in degrees clockwise.\n");
return EXIT_FAILURE;
}
input = argv[1];
page_number = atoi(argv[2]) - 1;
zoom = argc > 3 ? atof(argv[3]) : 100;
rotate = argc > 4 ? atof(argv[4]) : 0;
/* Create a context to hold the exception stack and various caches. */
ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
if (!ctx)
{
fprintf(stderr, "cannot create mupdf context\n");
return EXIT_FAILURE;
}
/* Register the default file types to handle. */
fz_try(ctx)
fz_register_document_handlers(ctx);
fz_catch(ctx)
{
fz_report_error(ctx);
fprintf(stderr, "cannot register document handlers\n");
fz_drop_context(ctx);
return EXIT_FAILURE;
}
/* Open the document. */
fz_try(ctx)
doc = fz_open_document(ctx, input);
fz_catch(ctx)
{
fz_report_error(ctx);
fprintf(stderr, "cannot open document\n");
fz_drop_context(ctx);
return EXIT_FAILURE;
}
/* Count the number of pages. */
fz_try(ctx)
page_count = fz_count_pages(ctx, doc);
fz_catch(ctx)
{
fz_report_error(ctx);
fprintf(stderr, "cannot count number of pages\n");
fz_drop_document(ctx, doc);
fz_drop_context(ctx);
return EXIT_FAILURE;
}
if (page_number < 0 || page_number >= page_count)
{
fprintf(stderr, "page number out of range: %d (page count %d)\n", page_number + 1, page_count);
fz_drop_document(ctx, doc);
fz_drop_context(ctx);
return EXIT_FAILURE;
}
/* Compute a transformation matrix for the zoom and rotation desired. */
/* The default resolution without scaling is 72 dpi. */
ctm = fz_scale(zoom / 100, zoom / 100);
ctm = fz_pre_rotate(ctm, rotate);
/* Render page to an RGB pixmap. */
fz_try(ctx)
pix = fz_new_pixmap_from_page_number(ctx, doc, page_number, ctm, fz_device_rgb(ctx), 0);
fz_catch(ctx)
{
fz_report_error(ctx);
fprintf(stderr, "cannot render page\n");
fz_drop_document(ctx, doc);
fz_drop_context(ctx);
return EXIT_FAILURE;
}
/* Print image data in ascii PPM format. */
printf("P3\n");
printf("%d %d\n", pix->w, pix->h);
printf("255\n");
for (y = 0; y < pix->h; ++y)
{
unsigned char *p = &pix->samples[y * pix->stride];
for (x = 0; x < pix->w; ++x)
{
if (x > 0)
printf(" ");
printf("%3d %3d %3d", p[0], p[1], p[2]);
p += pix->n;
}
printf("\n");
}
/* Clean up. */
fz_drop_pixmap(ctx, pix);
fz_drop_document(ctx, doc);
fz_drop_context(ctx);
return EXIT_SUCCESS;
}
To limit the complexity and give an easier introduction this code has no error handling at all, but any serious piece of code using MuPDF should use error handling strategies.
Common function arguments#
Most functions in MuPDF’s interface take a context argument.
A context contains global state used by MuPDF inside functions when parsing or rendering pages of the document. It contains for example:
an exception stack (see error handling below),
a memory allocator (allowing for custom allocators)
a resource store (for caching of images, fonts, etc.)
a set of locks and (un-)locking functions (for multi-threading)
Without the set of locks and accompanying functions the context and its proxies may only be used in a single-threaded application.
Error handling#
MuPDF uses a set of exception handling macros to simplify error return and cleanup. Conceptually, they work a lot like C++’s try/catch system, but do not require any special compiler support.
The basic formulation is as follows:
fz_try(ctx)
{
// Try to perform a task. Never 'return', 'goto' or
// 'longjmp' out of here. 'break' may be used to
// safely exit (just) the try block scope.
}
fz_always(ctx)
{
// Any code here is always executed, regardless of
// whether an exception was thrown within the try or
// not. Never 'return', 'goto' or longjmp out from
// here. 'break' may be used to safely exit (just) the
// always block scope.
}
fz_catch(ctx)
{
// This code is called (after any always block) only
// if something within the fz_try block (including any
// functions it called) threw an exception. The code
// here is expected to handle the exception (maybe
// record/report the error, cleanup any stray state
// etc) and can then either exit the block, or pass on
// the exception to a higher level (enclosing) fz_try
// block (using fz_throw, or fz_rethrow).
}
The fz_always
block is optional, and can safely be omitted.
The macro based nature of this system has 3 main limitations:
Never return from within try (or ‘goto’ or longjmp
out of it). This upsets the internal housekeeping of the macros and will cause problems later on. The code will detect such things happening, but by then it is too late to give a helpful error report as to where the original infraction occurred.
The fz_try(ctx) { ... } fz_always(ctx) { ... } fz_catch(ctx) { ... }
is not one atomic C statement. That is to say, if you do:
if (condition)
fz_try(ctx) { ... }
fz_catch(ctx) { ... }
then you will not get what you want. Use the following instead:
if (condition) {
fz_try(ctx) { ... }
fz_catch(ctx) { ... }
}
The macros are implemented using setjmp
and longjmp
, and so the standard C restrictions on the use of those functions apply to fz_try
/ fz_catch
too. In particular, any “truly local” variable that is set between the start of fz_try
and something in fz_try
throwing an exception may become undefined as part of the process of throwing that exception.
As a way of mitigating this problem, we provide a fz_var()
macro that tells the compiler to ensure that that variable is not unset by the act of throwing the exception.
A model piece of code using these macros then might be:
house build_house(plans *p)
{
material m = NULL;
walls w = NULL;
roof r = NULL;
house h = NULL;
tiles t = make_tiles();
fz_var(w);
fz_var(r);
fz_var(h);
fz_try(ctx)
{
fz_try(ctx)
{
m = make_bricks();
}
fz_catch(ctx)
{
// No bricks available, make do with straw?
m = make_straw();
}
w = make_walls(m, p);
r = make_roof(m, t);
// Note, NOT: return combine(w,r);
h = combine(w, r);
}
fz_always(ctx)
{
drop_walls(w);
drop_roof(r);
drop_material(m);
drop_tiles(t);
}
fz_catch(ctx)
{
fz_throw(ctx, "build_house failed");
}
return h;
}
Things to note about this:
If make_tiles
throws an exception, this will immediately be handled by some higher level exception handler. If it succeeds, t
will be set before fz_try
starts, so there is no need to fz_var(t);
.
We try first off to make some bricks as our building material. If this fails, we fall back to straw. If this fails, we’ll end up in the fz_catch
, and the process will fail neatly.
We assume in this code that combine takes new reference to both the walls and the roof it uses, and therefore that w
and r
need to be cleaned up in all cases.
We assume the standard C convention that it is safe to destroy NULL
things.
Multi-threading#
First off, study the basic usage example in docs/examples/example.c and make sure you understand how it works as the data structures manipulated there will be referred to in this section too.
MuPDF can usefully be built into a multi-threaded application without the library needing to know anything about threading at all. If the library opens a document in one thread, and then sits there as a ‘server’ requesting pages and rendering them for other threads that need them, then the library is only ever being called from this one thread.
Other threads can still be used to handle UI requests etc, but as far as MuPDF is concerned it is only being used in a single threaded way. In this instance, there are no threading issues with MuPDF at all, and it can safely be used without any locking, as described in the previous sections.
This section will attempt to explain how to use MuPDF in the more complex case; where we genuinely want to call the MuPDF library concurrently from multiple threads within a single application.
MuPDF can be invoked with a user supplied set of locking functions. It uses these to take mutexes around operations that would conflict if performed concurrently in multiple threads. By leaving the exact implementation of locks to the caller MuPDF remains threading library agnostic.
The following simple rules should be followed to ensure that multi-threaded operations run smoothly:
“No simultaneous calls to MuPDF in different threads are allowed to use the same context.”
Most of the time it is simplest to just use a different context for every thread; just create a new context at the same time as you create the thread. For more details see “Cloning the context” below.
“No simultaneous calls to MuPDF in different threads are allowed to use the same document.”
Only one thread can be accessing a document at a time, but once display lists are created from that document, multiple threads at a time can operate on them.
The document can be used from several different threads as long as there are safeguards in place to prevent the usages being simultaneous.
“No simultaneous calls to MuPDF in different threads are allowed to use the same device.”
Calling a device simultaneously from different threads will cause it to get confused and may crash. Calling a device from several different threads is perfectly acceptable as long as there are safeguards in place to prevent the calls being simultaneous.
“An fz_locks_context must be supplied at context creation time, unless MuPDF is to be used purely in a single thread at a time.”
MuPDF needs to protect against unsafe access to certain structures/resources/libraries from multiple threads. It does this by using the user supplied locking functions. This holds true even when using completely separate instances of MuPDF.
“All contexts in use must share the same fz_locks_context (or the underlying locks thereof).”
We strongly recommend that
fz_new_context
is called just once, andfz_clone_context
is called to generate new contexts from that. This will automatically ensure that the same locking mechanism is used in all MuPDF instances. For now, we do support multiple completely independent contexts being created using repeated calls tofz_new_context
, but these MUST share the samefz_locks_context
(or at least depend upon the same underlying locks). The facility to create different independent contexts may be removed in future.
So, how does a multi-threaded example differ from a non-multithreaded one?
Firstly, when we create the first context, we call fz_new_context
as before, but the second argument should be a pointer to a set of locking functions.
The calling code should provide FZ_LOCK_MAX
mutexes, which will be locked/unlocked by MuPDF calling the lock/unlock function pointers in the supplied structure with the user pointer from the structure and the lock number, i
(0 <= i < FZ_LOCK_MAX
). These mutexes can safely be recursive or non-recursive as MuPDF only calls in a non-recursive style.
To make subsequent contexts, the user should not call fz_new_context
again (as this will fail to share important resources such as the store and glyph cache), but should rather call fz_clone_context
. Each of these cloned contexts can be freed by fz_free_context
as usual. They will share the important data structures (like store, glyph cache etc.) with the original context, but will have their own exception stacks.
To open a document, call fz_open_document
as usual, passing a context and a filename. It is important to realise that only one thread at a time can be accessing the documents itself.
This means that only one thread at a time can perform operations such as fetching a page, or rendering that page to a display list. Once a display list has been obtained however, it can be rendered from any other thread (or even from several threads simultaneously, giving banded rendering).
This means that an implementer has 2 basic choices when constructing an application to use MuPDF in multi-threaded mode. Either they can construct it so that a single nominated thread opens the document and then acts as a ‘server’ creating display lists for other threads to render, or they can add their own mutex around calls to MuPDF that use the document. The former is likely to be far more efficient in the long run.
For an example of how to do multi-threading see below which has a main thread and one rendering thread per page.
/*
Multi-threaded rendering of all pages in a document to PNG images.
First look at docs/example.c and make sure you understand it.
Then, before coming back here to see an example of multi-threading,
please read the multi-threading section in:
https://mupdf.readthedocs.io/en/latest/using-mupdf.html#multi-threading
This example will create one main thread for reading pages from the
document, and one thread per page for rendering. After rendering
the main thread will wait for each rendering thread to complete before
writing that thread's rendered image to a PNG image. There is
nothing in MuPDF requiring a rendering thread to only render a
single page, this is just a design decision taken for this example.
To build this example in a source tree and render every page as a
separate PNG, run:
make examples
./build/debug/multi-threaded document.pdf
To build from installed sources, and render the same document, run:
gcc -I/usr/local/include -o multi-threaded \
/usr/local/share/doc/mupdf/examples/multi-threaded.c \
/usr/local/lib/libmupdf.a \
/usr/local/lib/libmupdfthird.a \
-lpthread -lm
./multi-threaded document.pdf
Caution! As all pages are rendered simultaneously, please choose a
file with just a few pages to avoid stressing your machine too
much. Also you may run in to a limitation on the number of threads
depending on your environment.
*/
//Include the MuPDF header file, and pthread's header file.
#include <mupdf/fitz.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// A convenience function for dying abruptly on pthread errors.
void
fail(const char *msg)
{
fprintf(stderr, "%s\n", msg);
abort();
}
// The data structure passed between the requesting main thread and
// each rendering thread.
struct thread_data {
// A pointer to the original context in the main thread sent
// from main to rendering thread. It will be used to create
// each rendering thread's context clone.
fz_context *ctx;
// Page number sent from main to rendering thread for printing
int pagenumber;
// The display list as obtained by the main thread and sent
// from main to rendering thread. This contains the drawing
// commands (text, images, etc.) for the page that should be
// rendered.
fz_display_list *list;
// The area of the page to render as obtained by the main
// thread and sent from main to rendering thread.
fz_rect bbox;
// This is the result, a pixmap containing the rendered page.
// It is passed first from main thread to the rendering
// thread, then its samples are changed by the rendering
// thread, and then back from the rendering thread to the main
// thread.
fz_pixmap *pix;
// This is a note of whether a given thread failed or not.
int failed;
};
// This is the function run by each rendering function. It takes
// pointer to an instance of the data structure described above and
// renders the display list into the pixmap before exiting.
void *
renderer(void *data_)
{
struct thread_data *data = (struct thread_data *)data_;
int pagenumber = data->pagenumber;
fz_context *ctx = data->ctx;
fz_display_list *list = data->list;
fz_rect bbox = data->bbox;
fz_device *dev = NULL;
fprintf(stderr, "thread at page %d loading!\n", pagenumber);
// The context pointer is pointing to the main thread's
// context, so here we create a new context based on it for
// use in this thread.
ctx = fz_clone_context(ctx);
// Next we run the display list through the draw device which
// will render the request area of the page to the pixmap.
fz_var(dev);
fprintf(stderr, "thread at page %d rendering!\n", pagenumber);
fz_try(ctx)
{
// Create a white pixmap using the correct dimensions.
data->pix = fz_new_pixmap_with_bbox(ctx, fz_device_rgb(ctx), fz_round_rect(bbox), NULL, 0);
fz_clear_pixmap_with_value(ctx, data->pix, 0xff);
// Do the actual rendering.
dev = fz_new_draw_device(ctx, fz_identity, data->pix);
fz_run_display_list(ctx, list, dev, fz_identity, bbox, NULL);
fz_close_device(ctx, dev);
}
fz_always(ctx)
fz_drop_device(ctx, dev);
fz_catch(ctx)
data->failed = 1;
// Free this thread's context.
fz_drop_context(ctx);
fprintf(stderr, "thread at page %d done!\n", pagenumber);
return data;
}
// These are the two locking functions required by MuPDF when
// operating in a multi-threaded environment. They each take a user
// argument that can be used to transfer some state, in this case a
// pointer to the array of mutexes.
void lock_mutex(void *user, int lock)
{
pthread_mutex_t *mutex = (pthread_mutex_t *) user;
if (pthread_mutex_lock(&mutex[lock]) != 0)
fail("pthread_mutex_lock()");
}
void unlock_mutex(void *user, int lock)
{
pthread_mutex_t *mutex = (pthread_mutex_t *) user;
if (pthread_mutex_unlock(&mutex[lock]) != 0)
fail("pthread_mutex_unlock()");
}
int main(int argc, char **argv)
{
char *filename = argc >= 2 ? argv[1] : "";
pthread_t *thread = NULL;
fz_locks_context locks;
pthread_mutex_t mutex[FZ_LOCK_MAX];
fz_context *ctx;
fz_document *doc = NULL;
int threads;
int i;
// Initialize FZ_LOCK_MAX number of non-recursive mutexes.
for (i = 0; i < FZ_LOCK_MAX; i++)
{
if (pthread_mutex_init(&mutex[i], NULL) != 0)
fail("pthread_mutex_init()");
}
// Initialize the locking structure with function pointers to
// the locking functions and to the user data. In this case
// the user data is a pointer to the array of mutexes so the
// locking functions can find the relevant lock to change when
// they are called. This way we avoid global variables.
locks.user = mutex;
locks.lock = lock_mutex;
locks.unlock = unlock_mutex;
// This is the main thread's context function, so supply the
// locking structure. This context will be used to parse all
// the pages from the document.
ctx = fz_new_context(NULL, &locks, FZ_STORE_UNLIMITED);
fz_var(thread);
fz_var(doc);
fz_try(ctx)
{
// Register default file types.
fz_register_document_handlers(ctx);
// Open the PDF, XPS or CBZ document.
doc = fz_open_document(ctx, filename);
// Retrieve the number of pages, which translates to the
// number of threads used for rendering pages.
threads = fz_count_pages(ctx, doc);
fprintf(stderr, "spawning %d threads, one per page...\n", threads);
thread = malloc(threads * sizeof (*thread));
for (i = 0; i < threads; i++)
{
fz_page *page;
fz_rect bbox;
fz_display_list *list;
fz_device *dev = NULL;
fz_pixmap *pix;
struct thread_data *data;
fz_var(dev);
fz_try(ctx)
{
// Load the relevant page for each thread. Note, that this
// cannot be done on the worker threads, as only one thread
// at a time can ever be accessing the document.
page = fz_load_page(ctx, doc, i);
// Compute the bounding box for each page.
bbox = fz_bound_page(ctx, page);
// Create a display list that will hold the drawing
// commands for the page. Once we have the display list
// this can safely be used on any other thread.
list = fz_new_display_list(ctx, bbox);
// Create a display list device to populate the page's display list.
dev = fz_new_list_device(ctx, list);
// Run the page to that device.
fz_run_page(ctx, page, dev, fz_identity, NULL);
// Close the device neatly, so everything is flushed to the list.
fz_close_device(ctx, dev);
}
fz_always(ctx)
{
// Throw away the device.
fz_drop_device(ctx, dev);
// The page is no longer needed, all drawing commands
// are now in the display list.
fz_drop_page(ctx, page);
}
fz_catch(ctx)
fz_rethrow(ctx);
// Populate the data structure to be sent to the
// rendering thread for this page.
data = malloc(sizeof (*data));
data->pagenumber = i + 1;
data->ctx = ctx;
data->list = list;
data->bbox = bbox;
data->pix = NULL;
data->failed = 0;
// Create the thread and pass it the data structure.
if (pthread_create(&thread[i], NULL, renderer, data) != 0)
fail("pthread_create()");
}
// Now each thread is rendering pages, so wait for each thread
// to complete its rendering.
fprintf(stderr, "joining %d threads...\n", threads);
for (i = 0; i < threads; i++)
{
char filename[42];
struct thread_data *data;
if (pthread_join(thread[i], (void **) &data) != 0)
fail("pthread_join");
if (data->failed)
{
fprintf(stderr, "\tRendering for page %d failed\n", i + 1);
}
else
{
sprintf(filename, "out%04d.png", i);
fprintf(stderr, "\tSaving %s...\n", filename);
// Write the rendered image to a PNG file
fz_save_pixmap_as_png(ctx, data->pix, filename);
}
// Free the thread's pixmap and display list.
fz_drop_pixmap(ctx, data->pix);
fz_drop_display_list(ctx, data->list);
// Free the data structure passed back and forth
// between the main thread and rendering thread.
free(data);
}
}
fz_always(ctx)
{
// Free the thread structure
free(thread);
// Drop the document
fz_drop_document(ctx, doc);
}
fz_catch(ctx)
{
fz_report_error(ctx);
fail("error");
}
// Finally the main thread's context is freed.
fz_drop_context(ctx);
fprintf(stderr, "finally!\n");
fflush(NULL);
return 0;
}
Cloning the context#
As described above, every context contains an exception stack which is manipulated during the course of nested fz_try
/ fz_catches
. For obvious reasons the same exception stack cannot be used from more than one thread at a time.
If, however, we simply created a new context (using fz_new_context
) for every thread, we would end up with separate stores/glyph caches etc., which is not (generally) what is desired. MuPDF therefore provides a mechanism for “cloning” a context. This creates a new context that shares everything with the given context, except for the exception stack.
A commonly used general scheme is therefore to create a ‘base’ context at program start up, and to clone this repeatedly to get new contexts that can be used on new threads.
Coding Style#
Names#
Functions should be named according to one of the following schemes:
verb_noun.
verb_noun_with_noun.
noun_attribute.
set_noun_attribute.
noun_from_noun - convert from one type to another (avoid noun_to_noun).
Prefixes are mandatory for exported functions, macros, enums, globals and types:
fz
for common code.pdf
,xps
, etc., for interpreter specific code.
Prefixes are optional (but encouraged) for private functions and types.
Avoid using ‘get’ as this is a meaningless and redundant filler word.
These words are reserved for reference counting schemes:
new, create, add, find, load, open, keep, read, parse, graft, copy, deep_copy - return objects that you are responsible for freeing.
drop - relinquish ownership of the object passed in.
When searching for an object or value, the name used depends on whether returning the value is passing ownership:
lookup - return a value or borrowed pointer.
find - return an object that the caller is responsible for freeing.
Types#
Various different integer types are used throughout MuPDF.
In general:
int
is assumed to be 32bit at least.short
is assumed to be exactly 16 bits.char
is assumed to be exactly 8 bits.Array sizes, string lengths, and allocations are measured using
size_t
.size_t
is 32bit in 32bit builds, and 64bit on all 64bit builds.Buffers of data use unsigned chars (or
uint8_t
).Offsets within files/streams are represented using
int64_t
.
In addition, we use floats (and avoid doubles when possible), assumed to be IEEE compliant.
Reference counting#
Reference counting uses special words in functions to make it easy to remember and follow the rules.
Words that take ownership: new
, find
, load
, open
, keep
.
Words that release ownership: drop
.
If an object is returned by a function with one of the special words that take ownership, you are responsible for freeing it by calling drop
or free
, or close
before you return. You may pass ownership of an owned object by return it only if you name the function using one of the special words.
Any objects returned by functions that do not have any of these special words, are borrowed and have a limited life time. Do not hold on to them past the duration of the current function, or stow them away inside structs. If you need to keep the object for longer than that, you have to either keep
it or make your own copy.
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.