pydocmaker.core

Attributes

ALLOWED_ENGINES_PDF

np

gImage

chapter_level

_pdf_engine

_renderer_default

buildingblocks

Classes

constr

This is the basic schema for the main building blocks for a document.

Doc

A collection of document parts to make a document (can be used like a list).

Functions

config_renderer_default_set([choice])

Sets the default renderer for displaying reports within Python.

config_renderer_default_get(→ str)

Returns the currently configured default renderer.

config_pdf_engine_set(→ str)

Sets the PDF engine to be used for generating PDF documents.

config_pdf_engine_get(→ str)

Returns the currently configured PDF engine, testing and setting one if none is configured.

config_pdf_engine_test(→ bool)

Tests the availability of the currently configured PDF engine.

config_pdf_engine_scan(→ Union[str, List[str]])

Scans the system for available PDF engines and returns them.

config_pdf_engine_testset(→ Optional[str])

Scans for available PDF engines, sets the first one found, and returns it.

is_notebook(→ bool)

Checks whether the current code is running inside a notebook environment (Jupyter, Colab, etc.).

show_pdf(→ None)

Display a PDF file within an IPython environment.

_is_chapter(→ str)

Extracts the chapter name from a markdown element if it is a chapter heading.

_construct(→ Any)

Recursively construct document part dicts from nested structures.

construct(→ Dict[str, Any])

Construct a document-part dict from the given type name and keyword arguments.

load(→ Doc)

Loads a document from a list of dictionaries, JSON string, file path, or stream.

print_to_pdf(→ None)

Prints a file to a PDF file using platform-specific subprocess commands.

Module Contents

pydocmaker.core.ALLOWED_ENGINES_PDF
pydocmaker.core.np = None
pydocmaker.core.gImage = None
pydocmaker.core.chapter_level = 1
pydocmaker.core._pdf_engine = None
pydocmaker.core._renderer_default = 'auto'
pydocmaker.core.config_renderer_default_set(choice: str = 'auto')

Sets the default renderer for displaying reports within Python.

Parameters: choice (str): The desired renderer for showing reports within python. Must be any of ‘auto’, ‘rich’, ‘md’, ‘html’, ‘pdf’.

Default is ‘auto’.

Returns:

The selected renderer_default.

Return type:

str

Raises:

ValueError – If the provided choice is not one of the allowed options.

pydocmaker.core.config_renderer_default_get() str

Returns the currently configured default renderer.

pydocmaker.core.config_pdf_engine_set(choice: str = 'typst') str

Sets the PDF engine to be used for generating PDF documents.

Parameters: choice (str): The desired PDF engine. Must be one of ‘tex’, ‘word’, ‘libreoffice’, ‘typst’, or ‘pandoc’.

Default is ‘typst’.

Returns: str: The selected PDF engine.

Raises: ValueError: If the provided choice is not one of the allowed options.

pydocmaker.core.config_pdf_engine_get() str

Returns the currently configured PDF engine, testing and setting one if none is configured.

pydocmaker.core.config_pdf_engine_test(raise_on_error: bool = True, force_reload: bool = False) bool

Tests the availability of the currently configured PDF engine.

Parameters:
  • raise_on_error (bool) – If True, raises a ValueError if no valid compiler is found.

  • force_reload (bool) – If True, forces a reload of the PDF engine configuration.

Returns:

True if a valid compiler is found, False otherwise.

Return type:

bool

pydocmaker.core.config_pdf_engine_scan(force_reload: bool = False, firstonly: bool = False) str | List[str]

Scans the system for available PDF engines and returns them.

Parameters:
  • force_reload (bool) – If True, forces a reload of the PDF engine configuration cache.

  • firstonly (bool) – If True, returns only the first available engine as a string.

Returns:

A list of available engine names, or the first engine name if firstonly=True.

Return type:

str | list[str]

pydocmaker.core.config_pdf_engine_testset() str | None

Scans for available PDF engines, sets the first one found, and returns it.

pydocmaker.core.is_notebook() bool

Checks whether the current code is running inside a notebook environment (Jupyter, Colab, etc.).

Returns:

True if running in a notebook environment, False otherwise.

Return type:

bool

pydocmaker.core.show_pdf(pdf_bytes: bytes, width: int = 1000, height: int = 1200) None

Display a PDF file within an IPython environment.

This function takes a PDF file in bytes or base64 encoded string format and displays it within an IPython notebook.

Parameters:
  • pdf_bytes (bytes or str) – The PDF file in bytes or base64 encoded string format.

  • width (int, optional) – The width of the IFrame in which the PDF is displayed. Default is 1000.

  • height (int, optional) – The height of the IFrame in which the PDF is displayed. Default is 1200.

Raises:

AssertionError – If the function is not called within an IPython environment.

Example

>>> with open('example.pdf', 'rb') as file:
...     pdf_bytes = file.read()
>>> show_pdf(pdf_bytes)
pydocmaker.core._is_chapter(dc: Dict[str, Any]) str

Extracts the chapter name from a markdown element if it is a chapter heading.

Parameters:

dc – A document part dictionary.

Returns:

The chapter name if dc is a chapter heading, empty string otherwise.

Return type:

str

class pydocmaker.core.constr

This is the basic schema for the main building blocks for a document.

Provides static factory methods that create document part dictionaries with a ‘typ’ key identifying the element type (meta, markdown, text, latex, verbatim, line, image, table, iter, etc.).

typalias
static meta(children: str = '', data: Dict[str, Any] | None = None, **kwargs: Any) Dict[str, Any]

Create a metadata document part dict.

Parameters:
  • children – Unused string content placeholder.

  • data – Dictionary of metadata key-value pairs.

  • **kwargs – Additional metadata fields.

Returns:

Document part dict with typ=’meta’, children, and data.

Return type:

dict

static markdown(children: str = '', color: str = '', end: str | None = None) Dict[str, Any]

Create a markdown document part dict.

Parameters:
  • children – The markdown text content.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’markdown’.

Return type:

dict

static text(children: str = '', color: str = '', end: str | None = None) Dict[str, Any]

Create a plain text document part dict.

Parameters:
  • children – The plain text content.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’text’.

Return type:

dict

static line(children: str = '', color: str = '', end: str | None = None) Dict[str, Any]

Create a line document part dict.

Args:

children: The text content for this line. color: Color for rendering (for HTML/LaTeX backends). end: Custom line ending (default ‘

‘).

Returns:

dict: Document part dict with typ=’line’.

static latex(children: str = '', color: str = '', end: str | None = None) Dict[str, Any]

Create a LaTeX document part dict.

Parameters:
  • children – The LaTeX source code string.

  • color – Color for rendering (for HTML backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’latex’.

Return type:

dict

static verbatim(children: str = '', color: str = '', end: str | None = None) Dict[str, Any]

Create a verbatim (pre-formatted text) document part dict.

Parameters:
  • children – The verbatim text content.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’verbatim’.

Return type:

dict

static iter(children: List[Any] | None = None, color: str = '', end: str | None = None) Dict[str, Any]

Create an iter (iterator/loop) document part dict.

Used to wrap content that should be iterated over (flattened) during export.

Parameters:
  • children – List of document parts to iterate over.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’iter’.

Return type:

dict

static table(children: List[List[Any]] | None = None, color: str = '', end: str | None = None, header: List[Any] | None = None, caption: str = '', n_cols: int | None = None, n_rows: int | None = None, borders: bool = True) Dict[str, Any]

Create a table document part dict.

Parameters:
  • children – Matrix (list of lists) with formatable elements.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

  • header – Header row as a list of formatable elements.

  • caption – Caption text to place under/above the table.

  • n_cols – Number of columns (auto-detected from children if not given).

  • n_rows – Number of rows (auto-detected from children if not given).

  • borders – Whether the table should have lines between cells.

Returns:

Document part dict with typ=’table’.

Return type:

dict

static image(imageblob: str = '', caption: str = '', children: str = '', width: float | None = None, color: str = '', end: str | None = None) Dict[str, Any]

Create an image document part dict.

Parameters:
  • imageblob – Base64-encoded image data string.

  • caption – Caption text for the image.

  • children – Internal name/id for the image file. Auto-generated if empty.

  • width – Display width for the image in the document.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’image’.

Return type:

dict

Create an image document part by downloading an image from a URL.

Parameters:
  • url – The URL to download the image from.

  • caption – Caption text for the image. Derived from filename if empty.

  • children – Internal name/id for the image file. Derived from URL if empty.

  • width – Display width for the image in the document.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’image’ containing the downloaded image data.

Return type:

dict

Raises:

AssertionError – If url is empty or downloaded content is not an image MIME type.

static image_from_file(path: str | os.PathLike | BinaryIO, children: str = '', caption: str = '', width: float | None = None, color: str = '', end: str | None = None) Dict[str, Any]

Create an image document part from a file path or file-like object.

Parameters:
  • path – File path string, PathLike object, or a file-like object with a read() method.

  • children – Internal name/id for the image file. Derived from filename if empty.

  • caption – Caption text for the image. Derived from children if empty.

  • width – Display width for the image in the document.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’image’ containing the image data.

Return type:

dict

Raises:

AssertionError – If path is empty or read content is not bytes.

static image_from_fig(caption: str = '', width: float | None = None, children: str | None = None, fig: Any = None, color: str = '', end: str | None = None, bbox_inches: str = 'tight', **kwargs: Any) Dict[str, Any]

Convert a matplotlib figure (or the current figure) to a document image dict.

Parameters:
  • caption – The caption to give to the image.

  • width – The width for the image to have in the document. None lets the individual formatter determine the width.

  • children – A specific name/id to give to the image (will be auto generated if None).

  • fig – The matplotlib figure object (or the current figure if None).

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

  • bbox_inches – Bounding box for the figure save (passed to matplotlib.savefig).

  • **kwargs – Additional keyword arguments passed to matplotlib.savefig.

Returns:

Document part dict with typ=’image’ containing the rendered figure as base64.

Return type:

dict

static image_from_obj(img: Any, caption: str = '', width: float | None = None, children: str | None = None, color: str = '', end: str | None = None) Dict[str, Any]

Create an image document part from a matrix, file-like object, PIL Image, or numpy array.

Accepts various input types and converts them to a base64-encoded PNG image: - 2D lists of lists -> numpy array -> PIL Image - numpy arrays with shape -> PIL Image - PIL Images -> file-like -> bytes -> base64 - File path strings -> file-like -> bytes -> base64 - Bytes -> base64

Parameters:
  • img – Image input. Can be a list of lists, numpy array, PIL Image, file path (str), file-like object with a read() method, or bytes.

  • caption – The caption to give to the image.

  • width – The width for the image to have in the document. None lets the formatter determine width.

  • children – A specific name/id for the image (auto-generated if None).

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

Returns:

Document part dict with typ=’image’ containing the image data.

Return type:

dict

pydocmaker.core.buildingblocks
class pydocmaker.core.Doc(initial_data: List[Dict[str, Any]] | None = None)

Bases: collections.UserList

A collection of document parts to make a document (can be used like a list).

The Doc class extends UserList and stores document parts as a list of dictionaries. Each dictionary represents a document element with a ‘typ’ key identifying its type (e.g., ‘markdown’, ‘text’, ‘latex’, ‘image’, ‘table’, ‘iter’, ‘meta’).

DEFAULT_ADD_STRING_TYPE

Default type used when adding plain strings to the document.

EXPORT_ENGINES

List of supported export format identifiers.

EXPORT_ENGINES_EXTENSIONS

Mapping of export format identifiers to their file extensions.

DEFAULT_ADD_STRING_TYPE: str = 'markdown'
EXPORT_ENGINES: List[str] = ['md', 'html', 'typst', 'json', 'docx', 'textile', 'ipynb', 'tex', 'redmine', 'pdf']
EXPORT_ENGINES_EXTENSIONS: Dict[str, str]
static load_json(path: str | pathlib.Path | BinaryIO | TextIO) Doc

Load a JSON file and return a Doc object.

Parameters:

path – The path to the JSON file, a URL string, or a file-like object.

Returns:

A Doc object initialized with the loaded JSON data.

Return type:

Doc

Raises:
  • json.JSONDecodeError – If the JSON file is not valid.

  • ValueError – If the remote response is not valid JSON.

__add__(b: Any) Doc

Add (join) two Docs into a single one and return a new instance.

This method combines two Doc objects into one. If b is a tuple or list containing a string and a default type, it uses the provided default type. If b is a string, it wraps it in a Doc object using the default type.

Parameters:

b – Content to append. Can be a Doc, list, tuple, or string.

Returns:

A new Doc instance with combined content.

Return type:

Doc

__iadd__(b: Any) Doc

Add content to the current instance using the += operator.

Parameters:

b – The content to add. Can be a Doc, list, tuple, or string. - If b has a dump method, it will be called to get the content. - If b is a tuple or list of length 2 with both elements being strings, the first element is used as the key and the second as the value. - If b is a string, it will be added with the default key.

Returns:

self (the modified instance after adding the content).

Return type:

Doc

flatten() Doc

Unpacks all iterator elements within this document and returns a new flat document.

Returns:

A new document with all elements flattened (iterators expanded in-place).

Return type:

Doc

add_chapter(chapter_name: str, chapter_index: int | None = None, color: str = '') Doc

Adds a new chapter heading to the document.

The chapter is inserted after the chapter at the given index (if chapter_index is provided), or appended to the end of the document.

Parameters:
  • chapter_name – The name/title of the new chapter.

  • chapter_index – The zero-based index of an existing chapter after which to insert. If None, the new chapter is appended to the end.

  • color – Color for the chapter heading (for HTML/LaTeX backends).

Returns:

self (for method chaining).

Return type:

Doc

Raises:

AssertionError – If chapter_name is not a string, is empty, or already exists.

get_chapter(chapter: str) List[Dict[str, Any]]

Retrieves a specific chapter from the document.

Parameters:

chapter – The name of the chapter to retrieve.

Returns:

A list of dictionaries representing the content items in the specified chapter.

Return type:

List[Dict[str, Any]]

get_chapters(as_ranges: bool = False) Dict[str, List[Dict[str, Any]]] | Dict[str, slice]

Extracts chapter names and their content (or index ranges) from the document.

Iterates through the internal data and identifies chapters based on markdown heading elements matched by the _is_chapter function.

Parameters:

as_ranges – If False, returns chapter names mapped to their content lists. If True, returns chapter names mapped to slice objects with start/stop indices.

Returns:

Dict[str, List[Dict[str, Any]]] if as_ranges=False, or Dict[str, slice] if as_ranges=True.

Keys are chapter names. Values are either content lists or slice objects.

get_template_from_meta(tformat: str = '', template_dir: str | None = None, raise_on_error: bool = False) pydocmaker.templating.DocTemplate | None

Gets the template from the metadata in this document if one is defined.

Loads template parameters and attachments stored in the document’s metadata element. If a template_id is defined, resolves it from the template directory. If a raw template string is stored instead, returns a DocTemplate wrapping it.

Parameters:
  • tformat – The format of the template (‘tex’, ‘html’, ‘typ’, etc.). Used to resolve template_id.

  • template_dir – If given, only this specific template directory is mounted for loading.

  • raise_on_error – If False, a template_id that cannot be resolved results in a warning and returns None.

Returns:

DocTemplate if a template is found in metadata, None otherwise or on unresolved error.

set_template_to_meta(template_id: str, with_params: bool = True, with_assets: bool = True, test_found: bool = True, on_exist: str = 'fail', template_params: Dict[str, Any] | None = None, tformat: str | None = None) Dict[str, Any]

Sets a template by a given template_id to the document metadata.

Copies template parameters and attachment files into the document’s metadata element. Controls behavior when the metadata already contains corresponding data via the on_exist parameter.

Parameters:
  • template_id – The ID of the template to set.

  • with_params – Whether to include the default parameters from the template in the metadata.

  • with_assets – Whether to include the asset files from the template in the metadata.

  • test_found – Whether to verify the template exists before modifying metadata.

  • on_exist – What to do if parameters/assets from the template already exist in metadata. ‘fail’ raises an assertion, ‘overwrite’ replaces existing data, ‘skip’ preserves existing data.

  • template_params – Additional parameters to merge into the template parameters.

  • tformat – Template format override (‘tex’, ‘html’, ‘typ’, etc.).

Returns:

The merged data content of the updated metadata element.

Return type:

dict

Raises:
  • FileNotFoundError – If test_found is True and the template_id does not exist.

  • AssertionError – If on_exist=’fail’ and template params/assets would overwrite existing metadata.

  • ValueError – If on_exist is not ‘fail’, ‘overwrite’, or ‘skip’.

parse_filename_meta(doc_name: str, regex_pattern: str | Sequence[str], fancy_title_analysis: bool = True) Dict[str, Any]

Parses metadata from a document name using a regular expression pattern.

Extracts named groups from a regex match against doc_name and stores them in the document’s metadata. Optionally performs fancy title analysis: resolves camelCasing and detects “signed” status.

Parameters:
  • doc_name – The document name to parse.

  • regex_pattern – A regex pattern string or sequence of pattern strings with named groups.

  • fancy_title_analysis – If True, attempts to detect “signed” status, resolves camelCasing, and cleans up the title string.

Returns:

A dictionary containing the parsed metadata, including ‘doc_name’ key.

Return type:

dict

Example

>>> import pydocmaker as pyd
>>> doc = pyd.Doc()
>>> regex_pattern = r'(?P<title>\w+)-(?P<version>[a-zA-Z0-9]+)-(?P<state>\w+)'
>>> doc_name = 'myfile-01-draft'
>>> doc.parse_filename_meta(doc_name, regex_pattern)
{'doc_name': 'myfile-01-draft', 'title': 'myfile', 'version': '01', 'state': 'draft'}
set_meta(*args: Any, **kwargs: Any) Dict[str, Any]

Replaces the metadata for this document with the provided content. Can be used in two ways: - By passing a dictionary: .set_meta({‘doc_name’: ‘test’}) - By passing keyword arguments: .set_meta(doc_name=’test’)

This method replaces all existing metadata or creates new metadata if it doesn’t exist.

Parameters:
  • *args – A single dictionary containing metadata.

  • **kwargs – Key-value pairs representing metadata.

Returns:

The new metadata content (the merged data dict).

Return type:

dict

get_meta(default: Dict[str, Any] | None = None) Dict[str, Any] | None

Gets the first metadata element in this document if it exists.

Parameters:

default – Value to return if no metadata element is found.

Returns:

The metadata dict (with ‘typ’, ‘children’, ‘data’ keys) if found, or default.

get_metadata() Dict[str, Any]

Gets the data dict from the first metadata element.

Gets the ‘data’ key content from the first metadata element. If no metadata element exists, returns an empty dict.

Returns:

The metadata data dictionary, or empty dict if none exists.

Return type:

dict

has_meta() bool

Tests if this document has one or more metadata objects.

Returns:

True if a metadata element exists, False otherwise.

Return type:

bool

update_meta(*args: Any, **kwargs: Any) Dict[str, Any]

Updates the metadata element in this document if it exists. If no metadata element exists, it will be created with the provided content. The content can be provided either as a dictionary (positional arg) or as keyword arguments.

Examples

.update_meta({‘doc_name’: ‘test’}) .update_meta(doc_name=’test’)

Parameters:
  • *args – A single dictionary containing metadata fields to update.

  • **kwargs – Key-value pairs representing metadata fields to update.

Returns:

The updated metadata data content.

Return type:

dict

add_meta(*args: Any, **kwargs: Any) Dict[str, Any]

Adds a metadata element to this document. If metadata already exists, it will be updated via update_meta instead. The content can be provided either as a dictionary (positional arg) or as keyword arguments.

Examples

.add_meta({‘doc_name’: ‘test’}) .add_meta(doc_name=’test’)

Parameters:
  • *args – A single dictionary containing metadata fields.

  • **kwargs – Key-value pairs representing metadata fields.

Returns:

The metadata data content (from the added or updated element).

Return type:

dict

add(part: Dict[str, Any] | str | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', end: str | None = None) Doc

Appends a new document part to the given location or end of this document.

If part is a string, it is automatically converted to a ‘text’ type document part. If chapter is given, the part is inserted at the end of that chapter (or the chapter is created). If index is given, the part is inserted at that list position.

Parameters:
  • part – The document part dict (from constr methods) or string to add.

  • index – The list index where to insert the part. If None, appends to the end.

  • chapter – The chapter name or zero-based chapter index where to insert. If None, appends to the end.

  • color – Color for rendering (only valid for string inputs).

  • end – Custom line ending (only valid for string inputs).

Returns:

self (for method chaining).

Return type:

Doc

Raises:

AssertionError – If part is empty, both index and chapter are specified, or index is out of bounds.

add_kw(typ: str, children: str | List[Any] | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', end: str | None = None, **kwargs: Any) Doc

Add a document part to this document with a given type.

Internally creates a document part dict via the construct function and calls add().

Parameters:
  • typ – One of the allowed document part types (‘markdown’, ‘verbatim’, ‘text’, ‘iter’, ‘image’, ‘table’, ‘latex’, ‘meta’, ‘line’).

  • children – The content for this element. Either a string directly or a list of other document parts.

  • index – The list index where to insert the part. If None, appends to the end.

  • chapter – The chapter name or zero-based chapter index. If None, appends to the end.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

  • **kwargs – Additional keyword arguments passed to the document part constructor.

Returns:

self (for method chaining).

Return type:

Doc

add_text(children: str | List[Any] | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', **kwargs: Any) Doc

Add a raw text part to this document.

Parameters:
  • children – The text content or list of items.

  • index – The list index where to insert. If None, appends to end.

  • chapter – Chapter name or index for insertion. If None, appends to end.

  • color – Color for rendering (for HTML/LaTeX backends).

  • **kwargs – Additional keyword arguments for the text element.

Returns:

self (for method chaining).

Return type:

Doc

add_tex(children: str | List[Any] | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', end: str | None = None, **kwargs: Any) Doc

Add a LaTeX part to this document.

Parameters:
  • children – The LaTeX source content or list of items.

  • index – The list index where to insert. If None, appends to end.

  • chapter – Chapter name or index for insertion. If None, appends to end.

  • color – Color for rendering (for HTML backends).

  • end – Custom line ending.

  • **kwargs – Additional keyword arguments for the LaTeX element.

Returns:

self (for method chaining).

Return type:

Doc

add_md(children: str | List[Any] | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', end: str | None = None, **kwargs: Any) Doc

Add a markdown document part to this document.

Parameters:
  • children – The markdown content or list of items.

  • index – The list index where to insert. If None, appends to end.

  • chapter – Chapter name or index for insertion. If None, appends to end.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

  • **kwargs – Additional keyword arguments for the markdown element.

Returns:

self (for method chaining).

Return type:

Doc

add_table(children: List[List[Any]] | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', end: str | None = None, header: List[Any] | None = None, caption: str = '', n_rows: int | None = None, n_cols: int | None = None, borders: bool = True, **kwargs: Any) Doc

Add a table element to this document.

Parameters:
  • children – Matrix (list of lists) with formatable elements.

  • index – The list index where to insert. If None, appends to end.

  • chapter – Chapter name or index for insertion. If None, appends to end.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

  • header – Header row as a list of formatable elements.

  • caption – Caption text to place at/under the table.

  • n_rows – Number of rows (auto-detected from children if not given).

  • n_cols – Number of columns (auto-detected from children if not given).

  • borders – Whether the table should have lines between its cells.

  • **kwargs – Additional keyword arguments.

Returns:

self (for method chaining).

Return type:

Doc

add_pre(children: str | List[Any] | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', end: str | None = None, **kwargs: Any) Doc

Add a verbatim (pre-formatted) document part to this document.

Parameters:
  • children – The verbatim text content or list of items.

  • index – The list index where to insert. If None, appends to end.

  • chapter – Chapter name or index for insertion. If None, appends to end.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

  • **kwargs – Additional keyword arguments for the verbatim element.

Returns:

self (for method chaining).

Return type:

Doc

add_fig(fig: Any = None, caption: str = '', width: float | None = None, bbox_inches: str = 'tight', children: str | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', end: str | None = None, **kwargs: Any) Doc

Add a matplotlib figure to this document as an image element.

Parameters:
  • fig – Matplotlib figure object (or None to use current figure).

  • caption – The caption to give to the image.

  • width – The width for the image in the document. None lets the formatter decide.

  • bbox_inches – Bounding box for figure save (passed to matplotlib.savefig).

  • children – Specific name/id for the image (auto-generated if None).

  • index – The list index where to insert. If None, appends to end.

  • chapter – Chapter name or index for insertion. If None, appends to end.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

  • **kwargs – Additional keyword arguments passed to matplotlib.savefig.

Returns:

self (for method chaining).

Return type:

Doc

add_image(image: Any, caption: str = '', width: float | None = None, children: str | None = None, index: int | None = None, chapter: str | int | None = None, color: str = '', end: str | None = None, **kwargs: Any) Doc

Add an image element to this document from various input types.

Image input can be:
  • HTTP URL string (downloaded automatically)

  • File path string (local file)

  • Base64-encoded image data string

  • Matplotlib Figure object

  • NumPy array (NxM, NxMx1, or NxMx3)

  • PIL Image object

  • File-like object with read() method

Parameters:
  • image – The image source. See supported types above.

  • caption – The caption to give to the image.

  • width – The width for the image in the document. None lets the formatter decide.

  • children – Specific name/id for the image (auto-generated if None).

  • index – The list index where to insert. If None, appends to end.

  • chapter – Chapter name or index for insertion. If None, appends to end.

  • color – Color for rendering (for HTML/LaTeX backends).

  • end – Custom line ending.

  • **kwargs – Additional keyword arguments.

Returns:

self (for method chaining).

Return type:

Doc

dump() List[Dict[str, Any]]

Dump this document to a basic list of dicts (deep copy).

Returns:

The individual parts of the document as a list of deep-copied dictionaries.

Return type:

List[Dict[str, Any]]

_ret(m: str | bytes, path_or_stream: str | pathlib.Path | IO[Any] | None) str | bytes | bool | None

Internal method to return or write data to a path, stream, or return the value.

Parameters:
  • m – The data to write (string or bytes).

  • path_or_stream – Path string, Path object, or file-like object to write to. If None, returns the data directly.

Returns:

The written data (str or bytes) if path_or_stream is None. True if written to a path/stream.

dumps(path_or_stream: str | pathlib.Path | IO[str] | None = None) str

Alias for self.to_json.

Parameters:

path_or_stream – Path to save to, or file-like object. If None, returns string.

Returns:

The JSON data as string if path_or_stream is None, or True if written to a file/stream.

Return type:

str

to_json(path_or_stream: str | pathlib.Path | IO[str] | None = None) str

Converts the current document to a JSON file or string.

Parameters:

path_or_stream – Path string, Path object, or file-like object to write the data to. If None, the JSON string is returned.

Returns:

The JSON data as a string if path_or_stream is None.

True if the data was saved successfully to a file or stream.

Return type:

str

to_markdown(path_or_stream: str | pathlib.Path | IO[str] | None = None, embed_images: bool = True) str | bool

Converts the current document to a Markdown string or writes it to a file.

Parameters:
  • path_or_stream – Path string, Path object, or file-like object to write to. If None, the Markdown string is returned.

  • embed_images – Whether to embed images as base64 strings within the Markdown.

Returns:

The Markdown string if path_or_stream is None. True if the Markdown was successfully written to a file or stream.

to_docx(path_or_stream: str | pathlib.Path | IO[bytes] | None = None, template: str | None = None, template_params: Dict[str, Any] | None = None, use_w32: bool = False, as_pdf: bool = False, compress_images: bool = False, allow_pandoc: bool = True) bytes | bool

Converts the current document to a DOCX file, or a PDF file via DOCX. WARNING: Some PDF options require win32com and Microsoft Word installed.

Parameters:
  • path_or_stream – Path string, Path object, or file-like object to write to. If None, the DOCX bytes are returned.

  • template – Path to a DOCX template file. Defaults to None (default template).

  • template_params – Dictionary of parameters to replace fields in the template.

  • use_w32 (bool, optional) – Whether to use win32com for document field updating (needs win32com + Word installed).

  • as_pdf (bool, optional) – Whether to output the document as a PDF (via docx + win32com).

  • compress_images (bool, optional) – Whether to compress images in the document using win32com.

  • allow_pandoc (bool, optional) – Whether to allow pandoc to be used instead of python-docx (usually produces nicer documents).

  • use_w32 – Whether to use win32com for document field updating and any of the following arguments, THIS OPTION NEEDS win32com and word installed. Defaults to False.

  • as_pdf – Whether to output the document as a PDF (via docx and win32com). Defaults to False.

  • compress_images – Whether to compress images in the document using win32com. Defaults to False.

  • allow_pandoc – whether or not to allow the usage of pandoc instead of python-docx (usually pandoc creates nicer documents!)

Returns:

The data as bytes, or True if the data was saved successfully to a file or stream.

Return type:

bytes

Raises:

ValueError – If attempting to export to PDF without win32com and Word.Application installed and use_w32 set to True.

to_ipynb(path_or_stream: str | pathlib.Path | IO[str] | None = None) str | bool

Converts the current document to an ipynb (IPython notebook) file.

Parameters:

path_or_stream – Path string, Path object, or file-like object to write to. If None, the JSON string is returned.

Returns:

The JSON string if path_or_stream is None. True if successfully written to a file or stream.

to_html(path_or_stream: str | pathlib.Path | IO[str] | None = None, template: Any | None = None, template_params: Dict[str, Any] | None = None) str

Converts the current document to a HTML file/string.

Uses template parameters from document metadata if no explicit template is provided.

Parameters:
  • path_or_stream – Path string, Path object, or file-like object to write to.

  • template – A Jinja2 Template object or string for the HTML template. If None, a default template or one from document metadata is used.

  • template_params – Dictionary of parameters for the HTML template, passed to Jinja2’s render method. Merged with template parameters from document metadata.

Returns:

The HTML content if path_or_stream is None.

True if the data was saved successfully to a file or stream.

Return type:

str

to_typst(path_or_stream: str | pathlib.Path | IO[str] | None = None, template: str | jinja2.Template | None = None, template_params: Dict[str, Any] | None = None) str

Converts the current document to a Typst file/string.

Uses template parameters from document metadata if no explicit template is provided.

Parameters:
  • path_or_stream – Path string, Path object, or file-like object to write to.

  • template – A Jinja2 Template object or string for the Typst template. If None, a default template or one from document metadata is used.

  • template_params – Dictionary of parameters for the Typst template, passed to Jinja2’s render method. Merged with template parameters from document metadata.

Returns:

The Typst source if path_or_stream is None.

True if the data was saved successfully to a file or stream.

Return type:

str

to_pdf(path_or_stream: str | pathlib.Path | IO[bytes] = None, docname: str = '', files_to_upload: Dict[str, bytes] | None = None, base_dir: str | None = None, engine: str | None = None, latex_compiler: str | None = None, n_times_make: int | None = None, verb: int = 0, ignore_error: bool = True, template: str | jinja2.Template | None = None, template_params: Dict[str, Any] | None = None, do_escape_template_params: str = 'auto', **kwargs) str | bytes | bool

Converts the current object to a PDF file or zipped LaTeX project folder.

Parameters:
  • path_or_stream (str or file-like object, optional) – The output destination. If it’s a string ending with ‘.pdf’, it will be written in PDF format to the given path. If it’s a string ending with ‘.zip’, the whole project folder used for making the PDF file will be zipped and saved under the given path. If it’s ‘zip’ or ‘pdf’, the data will be returned in the given format. If it’s None, the PDF data will be returned as a bytes object.

  • docname (str, optional) – The name of the output document. Defaults to a unix timestamp followed by ‘_mydocument’.

  • files_to_upload (dict, optional) – A dictionary of files to be included with the document.

  • base_dir (str, optional) – The directory to use as the base directory for the temporary directory. Defaults to the system’s default temporary directory.

  • engine (str, optional) – The PDF engine to use (one of “typst”, “tex”, “latextex”, “word”, “libreoffice”, or “pandoc”). If None, the engine is first inferred from the template via determine_engine_from_template(), then from any default template in meta via get_template_from_meta(), and finally from the config via config_pdf_engine_get().

  • latex_compiler (str, optional) – Only used if engine resolves to “tex”. The LaTeX compiler to use. Either ‘pdflatex’, ‘lualatex’, ‘xelatex’, or ‘pandoc’. If not specified, the function will try to use ‘pandoc’, ‘pdflatex’, ‘lualatex’, or ‘xelatex’ in that order.

  • n_times_make (int, optional) – Only used if engine resolves to “tex”. The number of times to run the LaTeX compiler. Defaults to 1 for pandoc and 3 for all others.

  • verb (int, optional) – The verbosity level (0, 1, 2). If greater than 0, the function will print more and more debug information. Defaults to 0.

  • ignore_error (bool, optional) – Whether to ignore errors during compilation. Defaults to True.

  • template (str, optional) – A string containing the document template code (either a Jinja2 template or plain LaTeX/Typst). If not provided, a default template will be used based on the detected format or configured engine.

  • template_params (dict, optional) – A dictionary containing parameters for the document template, passed to the “render” method of Jinja2.

  • do_escape_template_params (str | bool, optional) – Only valid for LaTeX templates. Whether to escape the template parameters. “auto” will scan for %%latex at the start of a string to determine if it’s a LaTeX string. Defaults to ‘auto’.

Returns:

If path_or_stream is a file path, returns True on success or False on failure.

If path_or_stream is ‘pdf’, ‘zip’, or None, returns the output as a bytes object (or str for certain engines).

Return type:

Union[str, bytes, bool]

Raises:

Warning – If the provided file path does not end with ‘.zip’ or ‘.pdf’, a warning is issued and the file is assumed to be in PDF format.

See also

additional_files (dict, optional): Passed via **kwargs; merged into files_to_upload. attachments (dict, optional): Passed via **kwargs; merged into files_to_upload.

to_tex(path_or_stream: str | pathlib.Path | BinaryIO | None = None, additional_files: Dict[str, bytes] | None = None, template: str | None = None, do_escape_template_params: str | bool = 'auto', template_params: Dict[str, Any] | None = None, text_only: bool = False) bool | str | Tuple[str, Dict[str, bytes]] | Tuple[bytes, Dict[str, bytes]]

Converts the current document to a TEX file (and attachments) as a ZIP archive.

The output is always a ZIP file containing doc.json, main.tex, and any attachment files. If saving to a file or stream, returns True on success. If not saving, returns a tuple of (tex_as_bytes, files_dict) by default, or just the tex string if text_only=True.

Parameters:
  • path_or_stream – Path string, Path object, or file-like object to write the ZIP to.

  • additional_files – Extra files to include in the ZIP (e.g., images, logos).

  • template – The LaTeX template (Jinja2) to use. If None, uses one from document metadata.

  • do_escape_template_params – Whether to escape LaTeX special chars in template params. ‘auto’ detects LaTeX templates automatically.

  • template_params – Additional parameters to pass to the LaTeX template.

  • text_only – If True and path_or_stream is None, returns the raw tex string instead of ZIP bytes.

Returns:

True if saved to a file/stream. Tuple[str, Dict[str, bytes]]: The tex string and file dict if returning and not text_only. str: The tex string if text_only=True. Tuple[bytes, Dict[str, bytes]]: The ZIP bytes and file dict if path_or_stream is None.

Return type:

bool

to_textile(path_or_stream: str | pathlib.Path | BinaryIO | None = None, text_only: bool = False) bool | str | Tuple[str, Dict[str, bytes]]

Converts the current document to a TEXTILE file (and attachments) as a ZIP archive.

If path_or_stream is given, the ZIP is written to the stream or file path. Otherwise returns a tuple of (textile_str, files_dict), or just the textile string if text_only=True.

Parameters:
  • path_or_stream – Path string, Path object, or file-like object to write the ZIP to.

  • text_only – If True and path_or_stream is None, returns just the textile string.

Returns:

True if saved to a file or stream. str: The textile source string if text_only=True. Tuple[str, Dict[str, bytes]]: The textile string and file dict if returning and not text_only.

Return type:

bool

to_redmine() Tuple[str, List[Dict[str, Any]]]

Converts the current document to Redmine-compatible Textile formatted text and attachments.

Returns:

A tuple of (textile_text, attachment_dicts).

Each attachment dict has keys: path, filename, content_type, description.

Return type:

Tuple[str, List[Dict[str, Any]]]

to_redmine_upload(redmine: Any, project_id: str | int, report_name: str | None = None, page_title: str | None = None, force_overwrite: bool = False, verb: bool = True) str

Converts the current document to Redmine Textile format and uploads it to a Redmine wiki page.

This will also export the document to all possible formats and attach them to the wiki page. This will also export the document to all possible formats and attach them to the wiki page.

Parameters:
  • redmine – A Redmine connection object (redminelib.Redmine instance).

  • project_id – The ID of the Redmine project where the report should be uploaded.

  • report_name – The name of the report. If None, uses a timestamp-based default.

  • page_title – The title of the Redmine wiki page. If None, derived from the report name.

  • force_overwrite – Whether to overwrite an existing page with the same title.

  • verb – Whether to print verbose output during upload.

Returns:

The URL of the uploaded Redmine wiki page.

Return type:

str

Raises:

AssertionError – If any of the project_id or redmine arguments is None.

print_rich(path_or_stream: str | IO[str] | None = None, title: str | None = None, embed_images: bool = True) bool | None

Renders the current document using the Python Rich library and outputs it to the console or a file.

Attempts to extract a title from document metadata if not provided.

Parameters:
  • path_or_stream – File path string, file-like object with a write method, or None for stdout.

  • title – Optional title for the documentation. If None, attempts to extract from metadata using common title keys (title, TITLE, filename, name, docname, etc.).

  • embed_images – If True, images appear as simplified pixelized pictures on the console. If False, a placeholder is inserted instead.

Returns:

True if path_or_stream is not None and writing was successful.

None if output went to stdout.

Return type:

bool

Example

>>> doc.print_rich("output.rich")
>>> doc.print_rich(sys.stdout)
>>> doc.print_rich()
to_pdf_print(path_or_stream: str | IO[bytes] | None = None) bytes | bool | None

Exports the document to a PDF file using the system’s “print to PDF” function (HTML to PDF).

WARNING: This function only works on POSIX-like operating systems and requires a PDF printer to be installed and set as default printer. It will not work on Windows or macOS. The resulting PDF quality is lower than proper PDF engines like pdflatex, typst, or word.

WARNING II: The resulting PDF file will not be of the same quality as a PDF file generated by a proper PDF engine like pdflatex, typst, or word. It is recommended to use this function only as a last resort if no other PDF engine is available and you need a quick and dirty PDF file.

Parameters:

path_or_stream – Path string for output PDF, file-like object to write to, or None to return bytes.

Returns:

bytes if path_or_stream is None. bool (True/False) if path_or_stream is a file or stream. None if a file/path was given as string but could not determine the return.

Raises:
  • AssertionError – If the OS is not POSIX.

  • IOError – If the PDF file could not be written.

export_all(dir_path: str | None = None, report_name: str = 'exported_report', **kwargs: Any) Dict[str | bytes, Any]

Exports the document to all supported formats.

Calls export_many with all engines from Doc.EXPORT_ENGINES.

Parameters:
  • dir_path – Directory path where exported files should be saved. If None, returns a dict mapping keys to exported data.

  • report_name – Base name for the exported files.

  • **kwargs – Additional keyword arguments specific to each export format.

Returns:

Dict mapping keys (file paths if dir_path given, or report_name+extension if not) to the exported data (bytes, str, or True).

export_many(engines: List[str] | None = None, dir_path: str | None = None, report_name: str = 'exported_report', **kwargs: Any) Dict[str | bytes, Any]

Exports the document to multiple specified formats.

Parameters:
  • engines – List of export engine names (e.g., ‘md’, ‘html’, ‘pdf’, ‘docx’). If None or empty, exports to all engines in Doc.EXPORT_ENGINES.

  • dir_path – Directory path where exported files should be saved. If None, returns a dict mapping keys to exported data.

  • report_name – Base name for the exported files.

  • **kwargs – Additional keyword arguments, potentially keyed by engine name.

Returns:

Dict mapping keys to exported data.

If dir_path is given: keys are full file paths, values are bools. If dir_path is None: keys are report_name+extension strings, values are raw data.

export(engine: str, path_or_stream: str | pathlib.Path | BinaryIO | TextIO | None = None, **kwargs: Any) Any

Exports the document to a specified format.

Dispatches to the appropriate to_* method based on the engine name.

Parameters:
  • engine – The format to export to. Valid options: ‘md’, ‘markdown’, ‘json’, ‘html’, ‘typst’, ‘typ’, ‘pdf’, ‘tex’, ‘latex’, ‘textile’, ‘ipynb’, ‘jupyter’, ‘notebook’, ‘word’, ‘docx’, ‘redmine’.

  • path_or_stream – Path string, Path object, or file-like object to write to.

  • **kwargs – Additional keyword arguments specific to the chosen export format.

Returns:

The exported data (str, bytes, bool, tuple, or dict) depending on the engine and whether path_or_stream was provided.

Raises:

KeyError – If the specified engine is not supported.

upload(url: str, doc_name: str = '', force_overwrite: bool = False, page_title: str = '', requests_kwargs: Dict[str, Any] | None = None, raise_on_fail: bool = True, warn_on_fail: bool = True) Dict[str, Any]

Uploads the document data to a specified URL via HTTP POST.

The JSON body sent is:

{“doc_name”: doc_name, “doc”: self.dump(), “force_overwrite”: force_overwrite, “page_title”: page_title}

Parameters:
  • url – The URL endpoint that accepts the document data.

  • doc_name – The name of the uploaded document.

  • force_overwrite – Whether to overwrite an existing document at the destination.

  • page_title – Title of the uploaded document (if applicable).

  • requests_kwargs – Dictionary of keyword arguments passed to requests.post().

  • raise_on_fail – If True, raises requests.exceptions.RequestException on non-2xx status.

  • warn_on_fail – If True, emits a warning with server response text on failure.

Returns:

The JSON response from the server after uploading.

Return type:

dict

Raises:

requests.exceptions.RequestException – If raise_on_fail is True and the upload fails.

show(engine: str | None = None, index: int | None = None, chapter: str | None = None, files_to_upload: Dict[str, bytes] | None = None, template: Any | None = None, template_params: Dict[str, Any] | None = None, do_escape_template_params: bool = False, embed_images: bool = True, **kwargs: Any) None

Displays the document or a specific part of it via IPython display or print to console.

For IPython/Jupyter environments, uses HTML, Markdown, PDF, or Code display widgets. For non-notebook environments, prints to stdout in the chosen format.

Parameters:
  • engine – Display engine to use. None decides based on environment (html in notebooks, rich in console). Options: ‘html’, ‘markdown’, ‘md’, ‘tex’, ‘latex’, ‘pdf’ (notebook only), ‘typst’, ‘auto’, ‘rich’, ‘console’, ‘terminal’, ‘plain’.

  • index – Display only the document part at this list index.

  • chapter – Display only the content of this named chapter.

  • files_to_upload – EXTRA ONLY WHEN engine=’pdf’. Additional files for PDF generation (see to_pdf).

  • template – ONLY WHEN engine=’pdf’ or ‘html’. Template string or Jinja2 Template object.

  • template_params – ONLY WHEN engine=’pdf’ or ‘html’. Template parameters dict.

  • do_escape_template_params – ONLY WHEN engine=’pdf’. Whether to escape template params for LaTeX.

  • embed_images – ONLY WHEN engine=’md’ or ‘rich’. Whether to embed images or show placeholders.

  • **kwargs – Additional arguments passed to the export method.

Raises:
  • KeyError – If the specified engine is not valid for the current environment.

  • AssertionError – If both index and chapter are specified.

__repr__(*args: Any, **kwargs: Any) str

Return a summary string with number of chapters and element count.

__str__(*args: Any, **kwargs: Any) str

Alias for __repr__.

classmethod get_example() Doc

Create and return a sample document with various element types.

Returns a Doc containing markdown text, verbatim code blocks, LaTeX, a table, and an embedded base64 image. Useful for testing and documentation examples.

Returns:

A sample document instance.

Return type:

Doc

pydocmaker.core._construct(v: Any) Any

Recursively construct document part dicts from nested structures.

Converts lists of dicts by recursively calling construct on each dict element. List elements not containing dicts are recursively processed. String elements are returned as-is.

Parameters:

v – A value that may be a string, list, or dict representing a document part.

Returns:

The constructed value (string, list, or dict).

pydocmaker.core.construct(typ: str, **kwargs: Any) Dict[str, Any]

Construct a document-part dict from the given type name and keyword arguments.

Looks up the constructor in the constr class (using typalias for name resolution). Recursively constructs nested ‘children’ content before calling the constructor.

Parameters:
  • typ – The document part type (e.g., ‘markdown’, ‘text’, ‘verbatim’, ‘latex’, ‘image’, ‘table’, ‘iter’).

  • **kwargs – Arguments passed to the constructor function.

Returns:

A dict representing the document part, or the typ string directly if no constructor and no kwargs.

Raises:
  • AssertionError – If typ is not a string.

  • TypeError – If the type is unknown.

pydocmaker.core.load(doc: List[Dict[str, Any]] | str | bytes | BinaryIO | TextIO) Doc

Loads a document from a list of dictionaries, JSON string, file path, or stream.

Accepts:
  • A list of doc-part dicts

  • A JSON string starting with ‘[’

  • A file path string

  • A binary or text file-like object with read() and seek() methods

Parameters:

doc – Document data as a list of dicts, JSON string, file path, or stream.

Returns:

A Doc object representing the loaded document.

Return type:

Doc

Raises:
  • AssertionError – If doc is not a list after parsing.

  • ValueError – If the file or stream cannot be loaded.

pydocmaker.core.print_to_pdf(file_path: str, output_pdf_path: str) None

Prints a file to a PDF file using platform-specific subprocess commands.

WARNING: This function only works on POSIX-like operating systems and requires a PDF printer to be installed and set as default printer. It will not work on Windows or macOS. The resulting PDF quality may be lower than proper PDF engines.

WARNING II: The resulting PDF file will not be of the same quality as a PDF file generated by a proper PDF engine like pdflatex, typst, or word. It is recommended to use this function only as a last resort if no other PDF engine is available and you need a quick and dirty PDF file.

Parameters:
  • file_path – Path to the input file (typically an HTML file).

  • output_pdf_path – Path for the output PDF file.

Raises:
  • ValueError – If the platform is not POSIX, or paths don’t exist.

  • subprocess.CalledProcessError – If the print command fails.