pydocmaker

Submodules

Attributes

__version__

buildingblocks

colors_dc

log

config_pandoc_allowed_set

config_pandoc_allowed_get

tex_escape

Classes

Doc

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

constr

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

bcolors

Create a collection of name/value pairs.

_raise_missing

DocxFile

A class to handle operations on DOCX files such as appending multiple documents,

DocxFileW32

A context manager for working with DOCX files using Win32COM automation.

DocTemplate

A class used to represent a document template.

TemplateDirSource

Manage templates, parameters, and attachments from specified directories.

options

A class to hold configuration options for pydocmaker.

Functions

construct(→ Dict[str, Any])

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

print_to_pdf(→ None)

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

make_pdf_from_tex(→ bytes)

Converts a LaTeX document to a PDF or a ZIP file containing the PDF and all attachments.

show_pdf(→ None)

Display a PDF file within an IPython environment.

is_notebook(→ bool)

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

upload_report_to_redmine(doc, redmine, project_id[, ...])

Uploads a report generated from a Doc object to a Redmine wiki page.

txtcolor(s, color)

remove_undefined(params)

can_use_libreoffice([force_reload])

test if libreoffice is available

can_use_w32_word([verb, force_reload])

test if Microsoft Word is available and win32com library is available

pandoc_convert_file(inp_file, out_file_or_format)

Convert a file using pandoc.

pandoc_set_allowed(is_allowed)

Set whether or not pandoc is allowed to be used as a valid conversion option

pandoc_convert(input_string, input_format, output_format)

Convert text between different formats using Pandoc.

register_new_template_dir(→ bool)

Register a new template directory if its not already registered.

get_registered_template_dirs([include_default])

Returns a list of registered template directories.

get_available_template_ids(→ list)

Retrieve the template IDs from the registered template directories.

test_template_exists(template_id[, tformat, template_dir])

tests if a template with a given id and optional in a given format exists

remove_from_template_dir(→ bool)

Removes an existing template directory if it exists.

get_template_params(→ dict)

Retrieve the parameters for one or more templates.

resolve_template_id(template_id[, template_dir, ...])

Resolve a template ID to its full file name.

config_libreoffice_path_get()

gets the currently set path for the libreoffice executeable or None, if it has not been resolved yet.

config_libreoffice_path_set(path)

sets a new path for the libreoffice executeable (use None to force the backend to try to resolve it anew)

config_libreoffice_path_find()

config_libreoffice_path_testset()

config_pdf_engine_get(→ str)

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

config_pdf_engine_set(→ str)

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

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

Scans the system for available PDF engines and returns them.

config_pdf_engine_test(→ bool)

Tests the availability of the currently configured PDF engine.

config_renderer_default_get(→ str)

Returns the currently configured default renderer.

config_renderer_default_set([choice])

Sets the default renderer for displaying reports within Python.

test_typst_installed()

compile_with_typst(typst_code[, output, verb, ...])

config_latex_compiler_scan()

config_latex_compiler_get([verb])

config_latex_compiler_set(new_latex_compiler_str)

config_latex_compiler_testset([verb])

info_optionals([force_retest])

Test the availability of optional dependencies for pydocmaker.

pandoc_set_enabled()

short for pandoc_set_allowed(True), which will allow pandoc to be used as a valid conversion option

pandoc_set_disabled()

short for pandoc_set_allowed(False), which will disallow pandoc to be used as a valid conversion option

get_schema()

get_example()

load(path)

Load a JSON file and return a Doc object.

md2tex([children])

convenience function to quickly convert markdown to tex

mk_chapter(title, description[, parent, order])

Creates a new chapter.

mk_meta(project_name, version, description, author, ...)

Generate metadata for the documentation.

mk_tex([children, index, chapter, color, end])

Creates a new LaTeX document part.

mk_md([children, index, chapter, color, end])

Creates a new markdown document part.

mk_pre([children, index, chapter, color, end])

Creates a preformatted document part.

mk_fig([fig, caption, width, bbox_inches, children, ...])

make an image document part from a pyplot figure type dict from given image input.

mk_image(image[, caption, width, children, color, end])

Make an image type dict from given image input.

Package Contents

pydocmaker.__version__ = '2.6.11'
class pydocmaker.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.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.

class pydocmaker.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.buildingblocks
pydocmaker.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.

pydocmaker.make_pdf_from_tex(input_latex_text, attachments_dc=None, docname='', out_format='pdf', base_dir=None, latex_compiler=None, n_times_make=None, verb=0, ignore_error=False) bytes

Converts a LaTeX document to a PDF or a ZIP file containing the PDF and all attachments.

Parameters:
  • input_latex_text (str or bytes) – The LaTeX document as a string or bytes.

  • attachments_dc (dict, optional) – A dictionary of attachments to include in the ZIP file. The keys are the filenames and the values are the file contents as bytes or strings. Defaults to an empty dictionary.

  • docname (str, optional) – The name of the output document. Defaults to a timestamp.

  • out_format (str, optional) – The format of the output. Either ‘pdf’ or ‘zip’. Defaults to ‘pdf’.

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

  • latex_compiler (str, optional) – 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) – The number of times to run the LaTeX compiler. Defaults to 1 for pandoc and 3 for al others.

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

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

Returns:

The PDF document as bytes, or a ZIP file containing the PDF and all attachments as bytes.

Return type:

bytes

Raises:
  • ValueError – If the input_latex_text is not a string or bytes, or if the docname is not a string.

  • ValueError – If the latex_compiler is not ‘pdflatex’, ‘lualatex’, ‘xelatex’, or ‘pandoc’.

  • ValueError – If the out_format is not ‘pdf’ or ‘zip’.

  • AssertionError – If the attachments_dc contains invalid keys or values.

pydocmaker.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.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.upload_report_to_redmine(doc, redmine, project_id, report_name=None, page_title=None, force_overwrite=False, verb=True)

Uploads a report generated from a Doc object to a Redmine wiki page.

Parameters:
  • doc (Doc) – The Doc object containing the report data.

  • redmine (redminelib.Redmine) – A Redmine connection object.

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

  • report_name (str, optional) – The name of the report. If not provided, the follwoing schema %Y%m%d_%H%M_exported_report will be used.

  • page_title (str, optional) – The title of the Redmine wiki page. If not provided, it will be derived from the report name.

  • force_overwrite (bool, optional) – Whether to overwrite an existing page with the same title. Defaults to False.

  • verb (bool, optional) – Whether to print verbose output during upload. Defaults to True.

Returns:

The uploaded Redmine wiki page object.

Return type:

redminelib.WikiPage

Raises:

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

class pydocmaker.bcolors(*args, **kwds)

Bases: enum.Enum

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

    >>> Color.RED
    <Color.RED: 1>
    
  • value lookup:

    >>> Color(1)
    <Color.RED: 1>
    
  • name lookup:

    >>> Color['RED']
    <Color.RED: 1>
    

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

HEADER = '\x1b[95m'
OKBLUE = '\x1b[94m'
OKCYAN = '\x1b[96m'
OKGREEN = '\x1b[92m'
WARNING = '\x1b[93m'
FAIL = '\x1b[91m'
ENDC = '\x1b[0m'
BOLD = '\x1b[1m'
UNDERLINE = '\x1b[4m'
pydocmaker.txtcolor(s: str, color: str)
pydocmaker.colors_dc
class pydocmaker._raise_missing(*args, **kwargs)
classmethod __getattr__(name)
pydocmaker.log
pydocmaker.remove_undefined(params)
class pydocmaker.DocxFile(file_path_or_buffer)

A class to handle operations on DOCX files such as appending multiple documents, replacing fields, and saving the modified document.

file_path_or_buffer
docx_data
inp_data
_get_bytes_file_or_buffer(file_path_or_buffer)

Retrieve bytes from a file path or buffer.

Parameters:

file_path_or_buffer – Path to the DOCX file or a buffer containing DOCX data.

Returns:

Bytes of the DOCX file.

append(*files, verb=0) bytes

Append multiple Word (.docx) documents into a single document.

Parameters:
  • files – Variable length argument list of either (bytes, or file paths, or buffers) to be appended.

  • verb – Verbosity level (0 for silent, 1 for verbose).

Returns:

The current instance of DocxFile with the appended DOCX data.

replace_fields(replace_dict)

Replace all MergeFields of a DOCX file with given text in form of a dict.

Parameters:

replace_dict – Dictionary where keys are field names and values are replacement texts.

Returns:

The current instance of DocxFile with the replaced fields.

get_fields()

Retrieve the merge fields from the DOCX document.

Returns:

A list of merge fields present in the DOCX document.

Return type:

list

replace_keywords(replace_dict)

Edit raw XML content of a DOCX file by replacing specified strings using python-docx.

Parameters:

replace_dict – Dictionary where keys are strings to be replaced and values are replacement strings.

Returns:

The current instance of DocxFile with the replaced keywords.

replace_keywords_raw(replace_dict)

Edit raw XML content of a DOCX file by replacing specified strings in all XML files within the document.

Parameters:

replace_dict – Dictionary where keys are strings to be replaced and values are replacement strings.

Returns:

The current instance of DocxFile with the replaced keywords in raw XML.

save(output_path_or_buffer=None)

Save the modified DOCX data to a file or buffer.

Parameters:

output_path_or_buffer – File path or buffer to save the DOCX data.

Returns:

The current instance of DocxFile.

class pydocmaker.DocxFileW32(docx_path, outpath=None)

A context manager for working with DOCX files using Win32COM automation.

This class provides methods to manipulate DOCX documents via Microsoft Word’s COM interface, including image compression, field updates, and exporting to PDF format. It ensures proper cleanup by closing the Word application and document upon exiting the context manager.

WARNING! This class needs the win32com library and word installed to work properly!

static is_installed(verb=0, force_reload=False, ret_int=False)
docx_path = b'.'
outpath = None
word = None
worddoc = None
_created_word_app = False
__enter__()

Enter the runtime context for the DocxFileW32 instance. if “win32com.client” is not available it will be imported.

Returns:

The instance itself for use in a ‘with’ statement.

Return type:

DocxFileW32

compress_images(compressionQuality=msoPictureCompress.Screen)

Compress all images within the document based on specified quality settings.

Parameters:

compressionQuality (msoPictureCompress or int) – The compression level to apply to images. Defaults to msoPictureCompress.Screen (quality 4).

Returns:

The instance itself to allow method chaining.

Return type:

DocxFileW32

update_fields()

Update all fields in the document, including those in headers and footers.

Returns:

The instance itself to allow method chaining.

Return type:

DocxFileW32

export(pdf_path=None, optimize_for_screen=True)

Export the document to PDF format with specified options.

Parameters:
  • pdf_path (str, optional) – The path where the PDF will be saved. If None, uses outpath.

  • optimize_for_screen (bool) – True for wdExportOptimizeForOnScreen (=1) else wdExportOptimizeForPrint (=0).

Returns:

The instance itself to allow method chaining.

Return type:

DocxFileW32

Raises:

AssertionError – If pdf_path is None and outpath is also None.

save()
close()
__exit__(exc_type, exc_value, traceback)

Exit the runtime context for the DocxFileW32 instance, saving and closing resources.

Parameters:
  • exc_type – Exception type (if any) that occurred during execution.

  • exc_value – Exception value (if any) that occurred during execution.

  • traceback – Traceback object (if any) that occurred during execution.

pydocmaker.can_use_libreoffice(force_reload=False)

test if libreoffice is available

Parameters:

force_reload (bool, optional) – whether or not to force to re-test, if it has been tested before. Defaults to False.

Returns:

True if available, False if not

Return type:

bool

pydocmaker.can_use_w32_word(verb=0, force_reload=False)

test if Microsoft Word is available and win32com library is available

Parameters:
  • verb (int, optional) – whether or not to give verbose info. Defaults to 0.

  • force_reload (bool, optional) – whether or not to force to re-test, if it has been tested before. Defaults to False.

Returns:

True if both are available, False if not

Return type:

bool

pydocmaker.pandoc_convert_file(inp_file, out_file_or_format)

Convert a file using pandoc.

Parameters: inp_file (str): The path to the input file. out_file_or_format (str or Path): The path to the output file or the desired output format.

If it’s a string starting with a dot, it’s considered as a file extension and the output file will be the input file with the new extension.

Returns: subprocess.CompletedProcess: The result of the pandoc conversion command.

Raises: AssertionError: If the input file does not exist or if no output file or format is provided.

pydocmaker.pandoc_set_allowed(is_allowed)

Set whether or not pandoc is allowed to be used as a valid conversion option

pydocmaker.pandoc_convert(input_string, input_format, output_format, is_binary=False, *args)

Convert text between different formats using Pandoc.

This function wraps the pandoc command-line tool to convert text from one format to another. It handles both text and binary conversions, with proper encoding and error handling.

Parameters:
  • input_string (str) – The text to be converted

  • input_format (str) – The source format (e.g., ‘markdown’, ‘rst’)

  • output_format (str) – The target format (e.g., ‘html’, ‘latex’)

  • is_binary (bool) – If True, treat input/output as binary data

  • *args – Additional arguments to pass to pandoc

Returns:

The converted text. If is_binary is True, returns bytes;

otherwise returns a UTF-8 decoded string

Return type:

str or bytes

Raises:

RuntimeError – If pandoc returns an error message

Note

If input_format equals output_format, the original input_string is returned without invoking pandoc, as it would be redundant.

pydocmaker.config_pandoc_allowed_set
pydocmaker.config_pandoc_allowed_get
class pydocmaker.DocTemplate(template, params=None, attachments=None, env=None, template_id=None)

A class used to represent a document template.

This class provides methods to load a template from a template directory, render the template with given parameters, and manage attachments.

template

A string representation of the template.

Type:

str

params

A dictionary of parameters to be used in the template.

Type:

dict

attachments

A dictionary of attachments to be used in the template.

Type:

dict

env

An instance of the jinja2 Environment class.

Type:

Environment

static from_tid(template_id: str, tformat='', template_dir=None)

Load a template by supplying a template_id and possibly a template format

Parameters:
  • template_id (str) – The ID of the template to load e.G. “base”

  • tformat (str, optional) – optinal the template format to get e.G. “.tex” or “.html”. Defaults to ‘’ which means first of any format being found.

  • template_dir (str, optional) – The directory containing the templates. If not provided, the default template directory is used.

Returns:

An instance of the DocTemplate class.

Return type:

DocTemplate

static test_tid_exists(template_id: str, tformat='', template_dir=None)

Test if a template with the given ID and optional format exists.

Parameters:
  • template_id (str) – The template ID to search for (e.g. ‘base’).

  • tformat (str, optional) – The template format to look for (‘tex’, ‘html’, etc.). If empty, checks for any format. Defaults to ‘’.

  • template_dir (str, optional) – If given, only the specified template directory is searched. Defaults to None.

Returns:

True if a template with the given ID (and optional format) exists.

Return type:

bool

static get_available_tids(template_dir=None)

Get the list of available template IDs.

Parameters:

template_dir (str, optional) – A specific template directory to search. If None, all registered template directories are searched.

Returns:

A list of template IDs (names without file extensions).

Return type:

list

template
params = None
attachments = None
env
template_id = None
property tformat
__str__()
__repr__()
render(**kwargs)

Render the Jinja2 template with given parameters.

Parameters:

**kwargs – Additional parameters to be used in the template.

Returns:

The rendered template as a string.

Return type:

str

class pydocmaker.TemplateDirSource(template_dirs: List[str] = None, tformat=None)

Manage templates, parameters, and attachments from specified directories.

template_dirs

a list of directory paths where templates are located

Type:

list

env

an Environment object from the jinja2 library used to load templates

Type:

Environment

engine

The template engine type filter. When set, only templates matching the engine type are loaded (“html”, “typ” for templates starting with “typ”, or “tex” for templates ending with “tex”).

Type:

str or None

get_params(templates=None, allow_fallback_jinja=True)

Returns a dictionary of parameters for the specified templates.

get_templates()

Returns a dictionary of Jinja2 Template objects keyed by template name.

get_template_ids()

Returns a list of template IDs (names without file extensions).

get_attachments(templates=None)

Returns a dictionary of attachments for the specified templates.

get_all(load_params=True, load_attachments=True)

Returns a tuple of (templates dict, params dict, attachments dict).

resolve_template_id(my_template_id)

Returns the full template file name corresponding to the given template ID.

find_undeclared_variables(template)

Returns a set of variable names used in the template but not declared.

VALID_ENGINES = ('html', 'typ', 'tex')
template_dirs = None
tformat = None
env
find_undeclared_variables(template: jinja2.Template | str)

Find undeclared variables in a Jinja2 template.

Accepts the template argument as any of the following:

  • a pathlib.Path or str template ID (e.g. "base.tex", "base.html.j2") — the ID is resolved via resolve_template_id so that {% extends %}, {% include %}, etc. are followed through by jinja2’s loader.

  • a str containing raw Jinja2 template source code

  • a Jinja2 Template object loaded from a file (has a filename attribute pointing to an on-disk file)

Jinja2’s env.parse() is used for all paths that go through the loader, which automatically traces {% extends %} / {% include %} and collects variables from all included/extended templates.

Note: Jinja2 does not expose the original source of templates created via Environment.from_string() (name is None and there is no filename). Passing such templates raises ValueError. Use a raw source string instead.

Parameters:

template – The template to analyze. See above for accepted types.

Returns:

A set of undeclared variable names used in the template.

Return type:

set

get_params(templates: Iterable[str] = None, allow_fallback_jinja=True) dict

Returns a dictionary of (default) parameters for the specified templates.

When a .params.json file is found for a template, its contents are used as-is. When no .params.json file exists and allow_fallback_jinja is True, parameters are inferred from the template source via find_undeclared_variables, in which case all parameter values are set to jinja2.Undefined which will be ignored on render.

Parameters:
  • templates (iterable str) – An iterable of template ids/names. If None, all templates are loaded.

  • allow_fallback_jinja (bool, optional) – If True and no .params.json file is found for a template, infer parameters from undeclared variables in the template source with None values. Defaults to True.

Returns:

A dictionary keyed by template_id, where each value is a dict of

param_name to param_value. When parameters come from a .params.json file, values are as defined in that file. When inferred via the Jinja2 fallback, all values are None.

Return type:

dict

get(template_id: str, default=None)
_template_matches_engine(template_name)

Check if a template name matches the configured engine filter.

get_templates() dict

Retrieves all the templates from the directory.

Returns:

A dictionary of templates where the keys are the template names

and the values are the corresponding Jinja2 Template objects.

Return type:

dict

get_template_ids()

This function retrieves the template IDs from the list of templates.

Returns:

A list of template IDs, which are the names of the templates without the file extension.

Return type:

list

get_attachments(templates=None)

Get attachments from the template directory.

Parameters:

templates (list or dict, optional) – A list or dictionary of templates. If None, all templates will be used. Defaults to None.

Returns:

A dictionary of attachments, where the keys are the template names

and the values are dictionaries of attachments for that template.

Return type:

dict

get_all_filenames()

Get all filenames in all template directories.

get_all(load_params=True, load_attachments=True)

Get all templates, parameters, and attachments.

Parameters:
  • load_params (bool, optional) – Whether to load parameters. Defaults to True.

  • load_attachments (bool, optional) – Whether to load attachments. Defaults to True.

Returns:

A tuple containing templates, parameters, and attachments.

Return type:

tuple

resolve_template_id(my_template_id)

Resolve the template ID to the actual template file name.

Parameters:

my_template_id (str) – The template ID to resolve.

Returns:

The actual template file name.

Return type:

str

Raises:

KeyError – If the template ID is not found in the available templates.

__contains__(template_id)

Check if a template_id is in any of the template directories.

pydocmaker.register_new_template_dir(new_template_dir: str, check_exists=True) bool

Register a new template directory if its not already registered. NOTE: If its already registered this function does nothing without much overhead.

Parameters:
  • new_template_dir (str) – The path to the new template directory.

  • check_exists (bool, optional) – Whether to check if the directory exists. Defaults to True.

Raises:

FileNotFoundError – If the directory does not exist and check_exists is True.

Returns:

True if the directory was successfully registered, False otherwise.

Return type:

bool

pydocmaker.get_registered_template_dirs(include_default=True)

Returns a list of registered template directories.

Parameters:

include_default (bool, optional) – Whether to include the default template directory. Defaults to True.

Returns:

A list of registered template directories. If include_default is True, the default

template directory is the first element in the list.

Return type:

list

pydocmaker.get_available_template_ids(template_dir=None, tformat=None) list

Retrieve the template IDs from the registered template directories.

Parameters:
  • template_dir (str, optional) – A specific template directory to search. If None, all registered template directories are searched.

  • tformat (str, optional) – Template format filter (e.g. ‘html’, ‘typ’, ‘tex’). If None, no format filtering is applied.

Returns:

A list of template IDs (names without file extensions).

Return type:

list

pydocmaker.test_template_exists(template_id, tformat='', template_dir=None)

tests if a template with a given id and optional in a given format exists

Parameters:
  • template_id (str) – the template id to search for e.G. ‘base’

  • tformat (str, optional) – optinal the template format to look for (e.g. ‘html’, ‘typ’, ‘tex’) if nothing is given the first found template with that name independent of the format is returned. Defaults to ‘’.

  • template_dir (str, optional) – if this is given only the given template directory is mounted to load jinja templates. Defaults to ‘’.

Returns:

True if found False otherwise

Return type:

bool

pydocmaker.remove_from_template_dir(to_remove: str) bool

Removes an existing template directory if it exists.

Parameters:

to_remove (str) – The path to remove from the template dirs.

Returns:

Always True

Return type:

bool

pydocmaker.get_template_params(template_id=None, template_dir=None, allow_fallback_jinja=True, tformat=None) dict

Retrieve the parameters for one or more templates.

When a .params.json file is found for a template, its contents are used as-is. When no .params.json file exists and allow_fallback_jinja is True, parameters are inferred from the template source via find_undeclared_variables, in which case all parameter values are set to jinja2.Undefined which will be ignored on render.

Parameters:
  • template_id (str, optional) – A specific template ID to get parameters for. If None, parameters for all templates are returned.

  • template_dir (str, optional) – A specific template directory to search. If None, all registered template directories are searched.

  • allow_fallback_jinja (bool, optional) – If True and no .params.json file is found, infer parameters from undeclared variables in the template source. Defaults to True.

  • tformat (str, optional) – Template format filter (e.g. ‘html’, ‘typ’, ‘tex’). If None, no format filtering is applied.

Returns:

A dictionary of template parameters. If template_id is provided, the parameter dicts

is returned directly for template_id. If template_id is None, keys are template IDs mapping to their parameter dicts (including all templates).

Return type:

dict

pydocmaker.resolve_template_id(template_id, template_dir=None, tformat=None, on_error='raise')

Resolve a template ID to its full file name.

Parameters:
  • template_id (str) – The template ID to resolve (e.g. ‘base’, ‘base.html’, ‘base.html.j2’).

  • template_dir (str, optional) – A specific template directory to search. If None, all registered template directories are searched.

  • tformat (str, optional) – Template format filter (e.g. ‘html’, ‘typ’, ‘tex’). If None, no format filtering is applied.

  • on_error (str|Any, optional) – if this is anything but “raise” the given value will be returned on a KeyError.

Returns:

The actual template file name resolved from the available templates.

Return type:

str

pydocmaker.tex_escape
pydocmaker.config_libreoffice_path_get()

gets the currently set path for the libreoffice executeable or None, if it has not been resolved yet.

Returns:

the currently set path for the libreoffice executeable or None, if it has not been resolved yet.

Return type:

str|None

pydocmaker.config_libreoffice_path_set(path)

sets a new path for the libreoffice executeable (use None to force the backend to try to resolve it anew)

Returns:

the newly set path for the libreoffice executeable or None, if it has not been resolved yet.

Return type:

str|None

pydocmaker.config_libreoffice_path_find()
pydocmaker.config_libreoffice_path_testset()
pydocmaker.config_pdf_engine_get() str

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

pydocmaker.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.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.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.config_renderer_default_get() str

Returns the currently configured default renderer.

pydocmaker.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.test_typst_installed()
pydocmaker.compile_with_typst(typst_code: str | List[dict], output: str = None, verb=1, on_warning='warn', format=None, attachments=None, **kwargs)
pydocmaker.config_latex_compiler_scan()
pydocmaker.config_latex_compiler_get(verb=0)
pydocmaker.config_latex_compiler_set(new_latex_compiler_str)
pydocmaker.config_latex_compiler_testset(verb=1)
pydocmaker.info_optionals(force_retest=False)

Test the availability of optional dependencies for pydocmaker.

Parameters: force_retest (bool): If True, forces a retest of the dependencies.

Returns: dict: A dictionary containing the status of each dependency.

  • ‘can_run_pandoc’: Boolean indicating if pandoc can be run.

  • ‘can_use_w32_word’: Boolean indicating if w32com.client can be used with Word.

  • ‘can_use_libreoffice’: Boolean indicating if LibreOffice can be used.

  • ‘pdf_engines_available’: List of available PDF engines.

  • ‘pdf_engine’: currently selected (default) engine to create pdf documents from pydocs

  • ‘libreoffice_path’: Path to the LibreOffice executable or None if not found.

class pydocmaker.options

A class to hold configuration options for pydocmaker. This is just a convenient wrapper around the individual config functions in the backend modules. Each attribute is a callable that points to the corresponding config function in the backend modules. For example, options.latex_compiler_get() will call the config_latex_compiler_get() function in the pdf_maker_tex module.

latex_compiler_scan
latex_compiler_get
latex_compiler_set
latex_compiler_test
libreoffice_path_find
libreoffice_path_get
libreoffice_path_set
pdf_engine_get
pdf_engine_set
pdf_engine_scan
pdf_engine_test
renderer_default_get
renderer_default_set
pandoc_allowed_set
pandoc_allowed_get
typst_installed
get_info_on_optional_components
pydocmaker.pandoc_set_enabled()

short for pandoc_set_allowed(True), which will allow pandoc to be used as a valid conversion option

pydocmaker.pandoc_set_disabled()

short for pandoc_set_allowed(False), which will disallow pandoc to be used as a valid conversion option

pydocmaker.get_schema()
pydocmaker.get_example()
pydocmaker.load(path)

Load a JSON file and return a Doc object.

Parameters:

path (str or file-like object) – The path to the JSON file, a http(s) link, 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.

  • TypeError – If the loaded JSON object is not of type list.

pydocmaker.md2tex(children='', **kwargs)

convenience function to quickly convert markdown to tex

Parameters:

children (str, optional) – the markdown string to convert. Defaults to ‘’.

Returns:

the corresponding tex string

Return type:

str

pydocmaker.mk_chapter(title, description, parent=None, order=None)

Creates a new chapter.

Parameters:
  • title (str) – The title of the chapter.

  • description (str) – A brief description of the chapter.

  • parent (Chapter, optional) – The parent chapter. Defaults to None.

  • order (int, optional) – The order of the chapter. Defaults to None.

Returns:

The newly created chapter.

Return type:

Chapter

pydocmaker.mk_meta(project_name, version, description, author, author_email, url, license)

Generate metadata for the documentation.

Parameters:
  • project_name (str) – The name of the project.

  • version (str) – The version of the project.

  • description (str) – A brief description of the project.

  • author (str) – The author’s name.

  • author_email (str) – The author’s email address.

  • url (str) – The URL of the project.

  • license (str) – The license of the project.

Returns:

A dictionary containing the metadata.

Return type:

dict

pydocmaker.mk_tex(children=None, index=None, chapter=None, color='', end=None, **kwargs)

Creates a new LaTeX document part.

Parameters:
  • children (str or list, optional) – The “children” for this element. Either text directly (as string) or a list of other parts.

  • index (int, optional) – The index where to insert the part. If None, appends to the end.

  • chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.

  • color (str, optional) – Any color which can be rendered by HTML or LaTeX. Empty string for default.

  • end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.

  • **kwargs – Additional keyword arguments for the document part.

Returns:

The newly created LaTeX document part.

Return type:

dict

pydocmaker.mk_md(children=None, index=None, chapter=None, color='', end=None, **kwargs)

Creates a new markdown document part.

Parameters:
  • children (str or list, optional) – The “children” for this element. Either text directly (as string) or a list of other parts.

  • index (int, optional) – The index where to insert the part. If None, appends to the end.

  • chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.

  • color (str, optional) – Any color which can be rendered by html or latex. Empty string for default.

  • end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.

  • **kwargs – Additional keyword arguments for the document part.

Returns:

The newly created markdown document part.

Return type:

dict

pydocmaker.mk_pre(children=None, index=None, chapter=None, color='', end=None, **kwargs)

Creates a preformatted document part.

Parameters:
  • children (str or list, optional) – The “children” for this element. Either text directly (as string) or a list of other parts.

  • index (int, optional) – The index where to insert the part. If None, appends to the end.

  • chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.

  • color (str, optional) – Any color which can be rendered by HTML or LaTeX. Empty string for default.

  • end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.

  • **kwargs – Additional keyword arguments for the document part.

Returns:

The created document part.

Return type:

dict

pydocmaker.mk_fig(fig=None, caption='', width=None, bbox_inches='tight', children=None, color='', end=None, **kwargs)

make an image document part from a pyplot figure type dict from given image input.

Parameters:
  • fig (matplotlib figure, optional) – the figure which to upload (or the current figure if None). Defaults to None.

  • caption (str, optional) – the caption to give to the image. Defaults to ‘’.

  • width (float, optional) – The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.

  • bbox_inches (str, optional) – will give better spacing for matplotlib figures.

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

  • index (int, optional) – The index where to insert the part. If None, appends to the end.

  • chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.

  • color (str, optional) – any color which can be rendered by html or latex. Empty string for default.

  • end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.

Returns:

The created document part.

Return type:

dict

pydocmaker.mk_image(image, caption='', width=None, children=None, color='', end=None, **kwargs)

Make an image type dict from given image input.

The image can be of type:
  • pyplot figure

  • link to download an image from

  • file-like object

  • numpy NxMx1 or NxMx3 matrix

  • PIL image

Parameters:
  • image – The image input, which can be a pyplot figure, a link, a file-like object, a numpy array, or a PIL image.

  • caption (str, optional) – The caption to give to the image. Defaults to ‘’.

  • width (float, optional) – The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.

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

  • color (str, optional) – Any color which can be rendered by HTML or LaTeX. Empty string for default. Defaults to ‘’.

  • end (str, optional) – If you want to insert a different line ending (than the default) for this element, set this argument to any string. None for default.

  • **kwargs – Additional keyword arguments to pass to the underlying method.

Returns:

A dictionary representing the image with the specified attributes.

Return type:

dict