...master 2026-11-12 (1037e2069+unstaged)

C++, Python, and C

Overview

Auto-generated abstracted C++, Python and C# versions of the MuPDF C API are available.

The C++ MuPDF API

Basics

Low-level C++ API

The MuPDF C API is provided as low-level C++ functions with ll_ prefixes.

Class-aware C++ API

C++ wrapper classes wrap most fz_* and pdf_* C structs:

Class-aware functions and methods take and return wrapper class instances instead of MuPDF C structs:

Usually it is more convenient to use the class-aware C++ API rather than the low-level C++ API.

C++ Exceptions

C++ exceptions use classes for each FZ_ERROR_* enum, all derived from a class mupdf::FzErrorBase which in turn derives from std::exception.

For example if MuPDF C code does fz_throw(ctx, FZ_ERROR_GENERIC, "something failed"), this will appear as a C++ exception with type mupdf::FzErrorGeneric. Its what() method will return code=2: something failed, and it will have a public member m_code set to FZ_ERROR_GENERIC.

Example wrappers

The MuPDF C API function fz_new_buffer_from_page() is available as these C++ functions/methods:

// MuPDF C function.
fz_buffer *fz_new_buffer_from_page(fz_context *ctx, fz_page *page, const fz_stext_options *options);

// MuPDF C++ wrappers.
namespace mupdf
{
    // Low-level wrapper:
    ::fz_buffer *ll_fz_new_buffer_from_page(::fz_page *page, const ::fz_stext_options *options);

    // Class-aware wrapper:
    FzBuffer fz_new_buffer_from_page(const FzPage& page, FzStextOptions& options);

    // Method in wrapper class FzPage:
    struct FzPage
    {
        ...
        FzBuffer fz_new_buffer_from_page(FzStextOptions& options);
        ...
    };
}

Extensions beyond the basic C API

Runtime environmental variables

All builds

Debug builds only

Debug builds contain diagnostics/checking code that is activated via these environmental variables:

Limitations

The Python and C# MuPDF APIs

Installing the Python mupdf module using pip

The Python mupdf module is available on the Python Package Index (PyPI) website.

Doxygen/Pydoc API documentation

Auto-generated documentation for the C, C++ and Python APIs is available at: https://ghostscript.com/~julian/mupdf-bindings/

Example client code

Using the Python API

Minimal Python code that uses the mupdf module:

import mupdf
document = mupdf.FzDocument('foo.pdf')

A simple example Python test script (run by scripts/mupdfwrap.py -t) is:

More detailed usage of the Python API can be found in:

Example Python code that shows all available information about a document’s Stext blocks, lines and characters:

#!/usr/bin/env python3

import mupdf

def show_stext(document):
    '''
    Shows all available information about Stext blocks, lines and characters.
    '''
    for p in range(document.fz_count_pages()):
        page = document.fz_load_page(p)
        stextpage = mupdf.FzStextPage(page, mupdf.FzStextOptions())
        for block in stextpage:
            block_ = block.m_internal
            log(f'block: type={block_.type} bbox={block_.bbox}')
            for line in block:
                line_ = line.m_internal
                log(f'    line: wmode={line_.wmode}'
                        + f' dir={line_.dir}'
                        + f' bbox={line_.bbox}'
                        )
                for char in line:
                    char_ = char.m_internal
                    log(f'        char: {chr(char_.c)!r} c={char_.c:4} color={char_.color}'
                            + f' origin={char_.origin}'
                            + f' quad={char_.quad}'
                            + f' size={char_.size:6.2f}'
                            + f' font=('
                                +  f'is_mono={char_.font.flags.is_mono}'
                                + f' is_bold={char_.font.flags.is_bold}'
                                + f' is_italic={char_.font.flags.is_italic}'
                                + f' ft_substitute={char_.font.flags.ft_substitute}'
                                + f' ft_stretch={char_.font.flags.ft_stretch}'
                                + f' fake_bold={char_.font.flags.fake_bold}'
                                + f' fake_italic={char_.font.flags.fake_italic}'
                                + f' has_opentype={char_.font.flags.has_opentype}'
                                + f' invalid_bbox={char_.font.flags.invalid_bbox}'
                                + f' name={char_.font.name}'
                                + f')'
                            )

document = mupdf.FzDocument('foo.pdf')
show_stext(document)

Basic PDF viewers written in Python and C

Building the C++, Python and C# MuPDF APIs from source

General requirements

Setting up

Windows only

All platforms

General build flags

In all of the commands below, one can set environmental variables to control the build of the underlying MuPDF C API, for example USE_SYSTEM_LIBJPEG=yes.

In addition, XCXXFLAGS can be used to set additional C++ compiler flags when building the C++ and Python bindings (the name is analogous to the XCFLAGS used by MuPDF’s makefile when compiling the core library).

Building and installing the Python bindings using pip

Building the Python bindings

Building the C++ bindings

Building the C# bindings

Using the bindings

To use the bindings, one has to tell the OS where to find the MuPDF runtime files.

Notes

How scripts/mupdfwrap.py builds the APIs

Building the MuPDF C API

Generation of the MuPDF C++ API

Generation of the MuPDF Python and C# APIs

Building auto-generated MuPDF API documentation

Build HTML documentation for the C, C++ and Python APIs (using Doxygen and pydoc):

python ./scripts/mupdfwrap.py --doc all

This will generate the following tree:

mupdf/docs/generated/
    index.html
    c/
    c++/
    python/

All content is ultimately generated from the MuPDF C header file comments.

As of 2022-2-5, it looks like swig -doxygen (swig-4.02) ignores single-line /** ... */ comments, so the generated Python code (and hence also Pydoc documentation) is missing information.

Generated files

All generated files are within the MuPDF checkout.

mupdf/
    build/
        shared-release/    [Unix runtime files.]
            libmupdf.so    [MuPDF C API, not MacOS.]
            libmupdf.dylib [MuPDF C API, MacOS.]
            libmupdfcpp.so [MuPDF C++ API.]
            mupdf.py       [MuPDF Python API.]
            _mupdf.so      [MuPDF Python API internals.]
            mupdf.cs       [MuPDF C# API.]
            mupdfcsharp.so [MuPDF C# API internals.]

        shared-debug/
            [as shared-release but debug build.]

        shared-release-x*-py*/      [Windows runtime files.]
            mupdfcpp.dll            [MuPDF C and C++ API, x32.]
            mupdfcpp64.dll          [MuPDF C and C++ API, x64.]
            mupdf.py                [MuPDF Python API.]
            _mupdf.pyd              [MuPDF Python API internals.]
            mupdf.cs                [MuPDF C# API.]
            mupdfcsharp.dll         [MuPDF C# API internals.]

    platform/
        c++/
            include/    [MuPDF C++ API header files.]
                mupdf/
                    classes.h
                    classes2.h
                    exceptions.h
                    functions.h
                    internal.h

            implementation/ [MuPDF C++ implementation source files.]
                classes.cpp
                classes2.cpp
                exceptions.cpp
                functions.cpp
                internal.cpp

            generated.pickle    [Information from clang parse step, used by later stages.]
            windows_mupdf.def   [List of MuPDF public global data, used when linking mupdfcpp.dll.]

        python/ [SWIG Python files.]
            mupdfcpp_swig.i     [SWIG input file.]
            mupdfcpp_swig.i.cpp [SWIG output file.]

        csharp/  [SWIG C# files.]
            mupdf.cs            [SWIG output file, no out-params helpers.]
            mupdfcpp_swig.i     [SWIG input file.]
            mupdfcpp_swig.i.cpp [SWIG output file.]

        win32/
            Release/    [Windows 32-bit .dll, .lib, .exp, .pdb etc.]
            x64/
                Release/    [Windows 64-bit .dll, .lib, .exp, .pdb etc.]
                    mupdfcpp64.dll  [Copied to build/shared-release*/mupdfcpp64.dll]
                    mupdfpyswig.dll [Copied to build/shared-release*/_mupdf.pyd]
                    mupdfcpp64.lib
                    mupdfpyswig.lib

        win32-vs-upgrade/   [used instead of win32/ if PYMUPDF_SETUP_MUPDF_VS_UPGRADE is '1'.]

Windows-specifics

Required predefined macros

Code that will use the MuPDF DLL must be built with FZ_DLL_CLIENT predefined.

The MuPDF DLL itself is built with FZ_DLL predefined.

DLLs

There is no separate C library, instead the C and C++ APIs are both in mupdfcpp.dll, which is built by running devenv on platform/win32/mupdf.sln.

The Python SWIG library is called _mupdf.pyd which, despite the name, is a standard Windows DLL, built from platform/python/mupdfcpp_swig.i.cpp.

DLL export of functions and data

On Windows, include/mupdf/fitz/export.h defines FZ_FUNCTION and FZ_DATA to __declspec(dllexport) and/or __declspec(dllimport) depending on whether FZ_DLL or FZ_DLL_CLIENT are defined.

All MuPDF C headers prefix declarations of public global data with FZ_DATA.

In generated C++ code:

When building mupdfcpp.dll on Windows we link with the auto-generated platform/c++/windows_mupdf.def file; this lists all C public global data.

For reasons that are not fully understood, we don’t seem to need to tag C functions with FZ_FUNCTION, but this is required for C++ functions otherwise we get unresolved symbols when building MuPDF client code.

Building the DLLs

We build Windows binaries by running devenv.com directly.

Building _mupdf.pyd is tricky because it needs to be built with a specific Python.h and linked with a specific python.lib. This is done by setting environmental variables MUPDF_PYTHON_INCLUDE_PATH and MUPDF_PYTHON_LIBRARY_PATH when running devenv.com, which are referenced by platform/win32/mupdfpyswig.vcxproj. Thus one cannot easily build _mupdf.pyd directly from the Visual Studio GUI.

[In the git history there is code that builds _mupdf.pyd by running the Windows compiler and linker cl.exe and link.exe directly, which avoids the complications of going via devenv, at the expense of needing to know where cl.exe and link.exe are.]

C++ bindings details

Wrapper functions

Wrappers for a MuPDF function fz_foo() are available in multiple forms:

Constructors using MuPDF functions

Wrapper class constructors are created for each MuPDF function that returns an instance of a MuPDF struct.

Sometimes two such functions do not have different arg types so C++ overloading cannot distinguish between them as constructors (because C++ constructors do not have names).

We cope with this in two ways:

Default constructors

All wrapper classes have a default constructor.

Raw constructors

Many wrapper classes have constructors that take a pointer to the underlying MuPDF C struct. These are usually for internal use only. They do not call fz_keep_*() - it is expected that any supplied MuPDF struct is already owned.

POD wrapper classes

Class wrappers for MuPDF structs default to having a m_internal member which points to an instance of the wrapped struct. This works well for MuPDF structs which support reference counting, because we can automatically create copy constructors, operator= functions and destructors that call the associated fz_keep_*() and fz_drop_*() functions.

However where a MuPDF struct does not support reference counting and contains simple data, it is not safe to copy a pointer to the struct, so the class wrapper will be a POD class. This is done in one of two ways:

Extra static methods

Where relevant, wrapper class can have static methods that wrap selected MuPDF functions. For example FzMatrix does this for fz_concat(), fz_scale() etc, because these return the result by value rather than modifying a fz_matrix instance.

Miscellaneous custom wrapper classes

The wrapper for fz_outline_item does not contain a fz_outline_item by value or pointer. Instead it defines C++-style member equivalents to fz_outline_item’s fields, to simplify usage from C++ and Python/C#.

The fields are initialised from a fz_outline_item when the wrapper class is constructed. In this particular case there is no need to hold on to a fz_outline_item, and the use of std::string ensures that value semantics can work.

Experimental thread-safety in C++ bindings

As of 2026-06-01 there is experimental support for automatic thread safety in the generated C++ bindings.

Caveats:

Details:

Extra functions in C++, Python and C

[These functions are available as low-level functions, class-aware functions and class methods.]

/**
C++ alternative to ``fz_lookup_metadata()`` that returns a ``std::string``
or calls ``fz_throw()`` if not found.
*/
FZ_FUNCTION std::string fz_lookup_metadata2(fz_context* ctx, fz_document* doc, const char* key);

/**
C++ alternative to ``pdf_lookup_metadata()`` that returns a ``std::string``
or calls ``fz_throw()`` if not found.
*/
FZ_FUNCTION std::string pdf_lookup_metadata2(fz_context* ctx, pdf_document* doc, const char* key);

/**
C++ alternative to ``fz_md5_pixmap()`` that returns the digest by value.
*/
FZ_FUNCTION std::vector<unsigned char> fz_md5_pixmap2(fz_context* ctx, fz_pixmap* pixmap);

/**
C++ alternative to fz_md5_final() that returns the digest by value.
*/
FZ_FUNCTION std::vector<unsigned char> fz_md5_final2(fz_md5* md5);

/** */
FZ_FUNCTION long long fz_pixmap_samples_int(fz_context* ctx, fz_pixmap* pixmap);

/**
Provides simple (but slow) access to pixmap data from Python and C#.
*/
FZ_FUNCTION int fz_samples_get(fz_pixmap* pixmap, int offset);

/**
Provides simple (but slow) write access to pixmap data from Python and
C#.
*/
FZ_FUNCTION void fz_samples_set(fz_pixmap* pixmap, int offset, int value);

/**
C++ alternative to fz_highlight_selection() that returns quads in a
std::vector.
*/
FZ_FUNCTION std::vector<fz_quad> fz_highlight_selection2(fz_context* ctx, fz_stext_page* page, fz_point a, fz_point b, int max_quads);

struct fz_search_page2_hit
{{
    fz_quad quad;
    int mark;
}};

/**
C++ alternative to fz_search_page() that returns information in a std::vector.
*/
FZ_FUNCTION std::vector<fz_search_page2_hit> fz_search_page2(fz_context* ctx, fz_document* doc, int number, const char* needle, int hit_max);

/**
C++ alternative to fz_string_from_text_language() that returns information in a std::string.
*/
FZ_FUNCTION std::string fz_string_from_text_language2(fz_text_language lang);

/**
C++ alternative to fz_get_glyph_name() that returns information in a std::string.
*/
FZ_FUNCTION std::string fz_get_glyph_name2(fz_context* ctx, fz_font* font, int glyph);

/**
Extra struct containing fz_install_load_system_font_funcs()'s args,
which we wrap with virtual_fnptrs set to allow use from Python/C# via
Swig Directors.
*/
typedef struct fz_install_load_system_font_funcs_args
{{
    fz_load_system_font_fn* f;
    fz_load_system_cjk_font_fn* f_cjk;
    fz_load_system_fallback_font_fn* f_fallback;
}} fz_install_load_system_font_funcs_args;

/**
Alternative to fz_install_load_system_font_funcs() that takes args in a
struct, to allow use from Python/C# via Swig Directors.
*/
FZ_FUNCTION void fz_install_load_system_font_funcs2(fz_context* ctx, fz_install_load_system_font_funcs_args* args);

/** Internal singleton state to allow Swig Director class to find
fz_install_load_system_font_funcs_args class wrapper instance. */
FZ_DATA extern void* fz_install_load_system_font_funcs2_state;

/** Helper for calling ``fz_document_handler::open`` function pointer via
Swig from Python/C#. */
FZ_FUNCTION fz_document* fz_document_handler_open(fz_context* ctx, const fz_document_handler *handler, fz_stream* stream, fz_stream* accel, fz_archive* dir, void* recognize_state);

/** Helper for calling a ``fz_document_handler::recognize`` function
pointer via Swig from Python/C#. */
FZ_FUNCTION int fz_document_handler_recognize(fz_context* ctx, const fz_document_handler *handler, const char *magic);

/** Swig-friendly wrapper for pdf_choice_widget_options(), returns the
options directly in a vector. */
FZ_FUNCTION std::vector<std::string> pdf_choice_widget_options2(fz_context* ctx, pdf_annot* tw, int exportval);

/** Swig-friendly wrapper for fz_new_image_from_compressed_buffer(),
uses specified ``decode`` and ``colorkey`` if they are not null (in which
case we assert that they have size ``2*fz_colorspace_n(colorspace)``). */
FZ_FUNCTION fz_image* fz_new_image_from_compressed_buffer2(
        fz_context* ctx,
        int w,
        int h,
        int bpc,
        fz_colorspace* colorspace,
        int xres,
        int yres,
        int interpolate,
        int imagemask,
        const std::vector<float>& decode,
        const std::vector<int>& colorkey,
        fz_compressed_buffer* buffer,
        fz_image* mask
        );

/** Swig-friendly wrapper for pdf_rearrange_pages(). */
void pdf_rearrange_pages2(
        fz_context* ctx,
        pdf_document* doc,
        const std::vector<int>& pages,
        pdf_clean_options_structure structure
        );

/** Swig-friendly wrapper for pdf_subset_fonts(). */
void pdf_subset_fonts2(fz_context *ctx, pdf_document *doc, const std::vector<int>& pages);

/** Swig-friendly and typesafe way to do fz_snprintf(fmt, value). ``fmt``
must end with one of 'efg' otherwise we throw an exception. */
std::string fz_format_double(fz_context* ctx, const char* fmt, double value);

struct fz_font_ucs_gid
{{
    unsigned long ucs;
    unsigned int gid;
}};

/** SWIG-friendly wrapper for fz_enumerate_font_cmap(). */
std::vector<fz_font_ucs_gid> fz_enumerate_font_cmap2(fz_context* ctx, fz_font* font);

/** SWIG-friendly wrapper for pdf_set_annot_callout_line(). */
void pdf_set_annot_callout_line2(fz_context *ctx, pdf_annot *annot, std::vector<fz_point>& callout);

/** SWIG-friendly wrapper for fz_decode_barcode_from_display_list(),
avoiding leak of the returned string. */
std::string fz_decode_barcode_from_display_list2(fz_context *ctx, fz_barcode_type *type, fz_display_list *list, fz_rect subarea, int rotate);

/** SWIG-friendly wrapper for fz_decode_barcode_from_pixmap(), avoiding
leak of the returned string. */
std::string fz_decode_barcode_from_pixmap2(fz_context *ctx, fz_barcode_type *type, fz_pixmap *pix, int rotate);

/** SWIG-friendly wrapper for fz_decode_barcode_from_page(), avoiding
leak of the returned string. */
std::string fz_decode_barcode_from_page2(fz_context *ctx, fz_barcode_type *type, fz_page *page, fz_rect subarea, int rotate);

Python/C# bindings details

Extra Python functions

Access to raw C arrays

The following functions can be used from Python to get access to raw data:

[These functions are implemented internally using SWIG’s carrays.i and pybuffer.i.

Python differences from C API

[The functions described below are also available as class methods.]

Custom methods

Python and C# code does not easily handle functions that return raw data, for example as an unsigned char* that is not a zero-terminated string. Sometimes we provide a C++ method that returns a std::vector by value, so that Python and C# code can wrap it in a systematic way.

For example Md5::fz_md5_final2().

For all functions described below, there is also a ll_* variant that takes/returns raw MuPDF structs instead of wrapper classes.

New functions

Implemented in Python

Non-standard API or implementation

Limitations

Making MuPDF function pointers call Python code

Overview

For MuPDF structs with function pointers, we provide a second C++ wrapper class for use by the Python bindings.

Callback args

Python callbacks have args that are more low-level than in the rest of the Python API:

Exceptions in callbacks

Python exceptions in Director callbacks are propagated back through the language layers (from Python to C++ to C, then back to C++ and finally to Python).

For convenience we add a text representation of the original Python backtrace to the exception text, but the C layer’s fz_try/catch exception handling only holds 256 characters of exception text, so this backtrace information may be truncated by the time the exception reaches the original Python code’s except ... block.

Example

Here is an example PDF filter written in Python that removes alternating items:

import mupdf

def test_filter(path):
    class MyFilter( mupdf.PdfFilterOptions2):
        def __init__( self):
            super().__init__()
            self.use_virtual_text_filter()
            self.recurse = 1
            self.sanitize = 1
            self.state = 1
            self.ascii = True
        def text_filter( self, ctx, ucsbuf, ucslen, trm, ctm, bbox):
            print( f'text_filter(): ctx={ctx} ucsbuf={ucsbuf} ucslen={ucslen} trm={trm} ctm={ctm} bbox={bbox}')
            # Remove every other item.
            self.state = 1 - self.state
            return self.state

    filter_ = MyFilter()

    document = mupdf.PdfDocument(path)
    for p in range(document.pdf_count_pages()):
        page = document.pdf_load_page(p)
        print( f'Running document.pdf_filter_page_contents on page {p}')
        document.pdf_begin_operation('test filter')
        document.pdf_filter_page_contents(page, filter_)
        document.pdf_end_operation()

    document.pdf_save_document('foo.pdf', mupdf.PdfWriteOptions())