pydocmaker

Submodules

Attributes

__version__

buildingblocks

colors_dc

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

A class used to manage templates, parameters, and attachments from a specified directory.

options

A class to hold configuration options for pydocmaker.

Functions

construct(typ, **kwargs)

construct a document-part dict from the given typ and some kwargs

print_to_pdf(file_path, output_pdf_path)

Prints a file to a PDF file using the appropriate platform-specific command using subprocess

make_pdf_from_tex(→ bytes)

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

show_pdf(pdf_bytes[, width, height])

Display a PDF file within an IPython environment.

is_notebook(→ bool)

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

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

txtcolor(s, color)

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.

get_registered_template_dirs([include_default])

Returns a list of registered template directories.

get_available_template_ids([template_dir])

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

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.

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()

config_pdf_engine_set([choice])

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

config_pdf_engine_scan([force_reload, firstonly])

Configures the PDF engine and tests its availability.

config_pdf_engine_test([raise_on_error, force_reload])

tests the availability of the currently configured PDF engine.

config_renderer_default_get()

config_renderer_default_set([choice])

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

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.7'
class pydocmaker.Doc(initial_data=None)

Bases: collections.UserList

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

DEFAULT_ADD_STRING_TYPE = 'markdown'
EXPORT_ENGINES = ['md', 'html', 'typst', 'json', 'docx', 'textile', 'ipynb', 'tex', 'redmine', 'pdf']
EXPORT_ENGINES_EXTENSIONS
static load_json(path)

Load a JSON file and return a Doc object.

Parameters:

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

__add__(b)

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.

__iadd__(b)

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

Parameters: b (str, tuple, list, or object with a dump method): The content to add.

  • 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.

flatten()

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

Returns:

A new document with all elements flattened.

Return type:

Doc

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

Adds a new chapter to the document.

Parameters:
  • chapter_name (str) – The name of the new chapter.

  • chapter_index (int, optional) – The index after which chapter to insert the new chapter. If None, appends to the end.

Raises:

AssertionError – If chapter_name is not a string or is empty.

get_chapter(chapter) List[dict]

Retrieves a specific chapter from the document.

Parameters:

chapter (str) – The name of the chapter to retrieve.

Returns:

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

Return type:

List[dict]

get_chapters(as_ranges=False) dict

Extracts chapters from the internal data and returns them as either dictionaries or ranges.

This method iterates through the internal data structure (represented by self.data) and identifies chapters based on a custom logic implemented in the _is_chapter function.

Parameters:

as_ranges (bool, optional) – If True, returns chapters as dictionaries with keys as chapter names (obtained from the previous chapter) and values as ranges of indices (inclusive-exclusive) within the data list representing the chapter content. Defaults to False.

Returns:

If as_ranges is False, returns a dictionary where keys are chapter names and values are corresponding chapter content extracted from the data list using the identified ranges. If as_ranges is True, returns a dictionary where keys are chapter names and values are ranges of indices (inclusive-exclusive) within the data list representing the chapter content.

Return type:

dict or dict[str, range]

get_template_from_meta(tformat='', template_dir=None, raise_on_error=False) pydocmaker.templating.DocTemplate

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

Parameters:
  • tformat (str, optional) – The format of the template either ‘tex’ or ‘html’. Defaults to ‘’.

  • template_dir (str, optional) – If this is given only this specific template dir is mounted to load templates from. Otherwise all registered templates are loaded

  • raise_on_error – (bool, optional): If this is False None will be returned in case of an error. Defaults to False.

Returns:

The template object if a template_id is found in the metadata, otherwise None.

Return type:

DocTemplate

set_template_to_meta(template_id: str, with_params=True, with_assets=True, test_found=True, on_exist='fail', template_params: dict = None) dict

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

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

  • with_params (bool, optional) – Whether to include the (default) parameters from the template in the metadata. Defaults to True.

  • with_assets (bool, optional) – Whether to include the assets (files) from the template in the metadata. Defaults to True.

  • test_found (bool, optional) – Whether to test if the template exists before adding anything. Defaults to True.

  • on_exist (str, optional) – What to do if the parameters or assets from a template already exist in the metadata. Can be ‘fail’, ‘overwrite’, or ‘skip’. Defaults to ‘fail’.

  • template_params (dict, optional) – Additional parameters to add to the template. Defaults to None.

Raises:
  • FileNotFoundError – If the template with the given ID does not exist.

  • AssertionError – If overwrite protection is enabled and the template would overwrite existing data.

  • ValueError – If an unknown value is passed for the on_exist parameter.

Returns:

the meta elements data (content)

Return type:

dict

parse_filename_meta(doc_name, regex_pattern: str, fancy_title_analysis=True) dict

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

Parameters:
  • doc_name (str) – The name of the document.

  • regex_pattern (str) – The regular expression pattern to use for parsing (can also give multiple as list or tuple).

  • fancy_title_analysis (bool, optional) – Will Analyse the title for “signed” in it and also resolve CamelCasing from it

Returns:

A dictionary containing the parsed metadata.

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, **kwargs) dict

Sets the metadata for this document. 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 updates the 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 updated metadata.

Return type:

dict

get_meta(default=None) Dict | None

gets the (first) meta element in this document if it exists. If not returns None

get_metadata() Dict | None

Equivalent to self.get_meta(default={}).get(‘data’, {}) Gets the data of the (first) meta element in this document if it exists. If not exists an new empty dict is returned

has_meta() bool

tests if this document has one or more metadata objects

update_meta(*args, **kwargs) Dict | None

Updates the metadata element in this document if it exists. If not, it will be added with the content provided. The content can be provided either as a dictionary or as keyword arguments.

Examples

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

Returns:

The updated metadata content.

Return type:

dict

add_meta(*args, **kwargs) dict

Adds a metadata element to this document. If the metadata already exists, it will be updated. The content can be provided either as a dictionary or as keyword arguments.

Examples

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

Returns:

The metadata element’s data (content).

Return type:

dict

add(part: dict = None, index=None, chapter=None, color='', end=None)

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

Parameters:
  • part (dict) – The part to add. See the constr class for all possible 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 (ONLY VALID FOR string INPUTS!). 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.

Raises:
  • ValueError – If the part is invalid, or if both index and chapter are specified.

  • AssertionError – If index is not an integer or is out of bounds.

add_kw(typ, children=None, index=None, chapter=None, color='', end=None, **kwargs)

add a document part to this document with a given typ

Parameters:
  • typ (str, optional) – one of the allowed document part types. Either ‘markdown’, ‘verbatim’, ‘text’, ‘iter’ or ‘image’.

  • children (str or list) – 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 – the kwargs for such a document part

add_text(children=None, index=None, chapter=None, color='', **kwargs)

add a raw text part to this document

Parameters:
  • children (str or list) – 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.

  • kwargs – the kwargs for such a document part

add_tex(children=None, index=None, chapter=None, color='', end=None, **kwargs)

add a latex part to this document

Parameters:
  • children (str or list) – 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.

  • kwargs – the kwargs for such a document part

add_md(children=None, index=None, chapter=None, color='', end=None, **kwargs)

add a markdown document part to this document

Parameters:
  • children (str or list) – 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 – the kwargs for such a document part

add_table(children=None, index=None, chapter=None, color='', end=None, header=None, caption='', n_rows=None, n_cols=None, borders=True, **kwargs)

add a table element to this document

Parameters:
  • children (list of lists) – the “children” for this element. Must be a matrix (list of lists) with formatable elements in it.

  • 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.

  • header (list, optional) – The header row for the table. If given it must be a list with formatable elements in it.

  • caption (str, optional) – The caption to place at/under the table. Empty for no caption.

  • n_rows (int, optional) – The number of rows to give this table. If not given it will be determined from the number of rows in children.

  • n_cols (int, optional) – The number of columns to give this table. If not given it will be determined from the max number of columns in all rows in children.

  • borders (bool, optional) – Whether or not the table should have lines between its cells.

add_pre(children=None, index=None, chapter=None, color='', end=None, **kwargs)

add a verbaim (pre formatted) document part to this document

Parameters:
  • children (str or list) – 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 – the kwargs for such a document part

add_fig(fig=None, caption='', width=None, bbox_inches='tight', children=None, index=None, chapter=None, color='', end=None, **kwargs)

add 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.

add_image(image, caption='', width=None, children=None, index=None, chapter=None, color='', end=None, **kwargs)

add an image type dict from given image input. image can be of type:

  • pyplot figure

  • link to download an image from

  • filelike

  • numpy NxMx1 or NxMx3 matrix

  • PIL image

Parameters:
  • im (np.array) – the image as NxMx

  • 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.

  • 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.

dump() List[Dict]

dump this document to a basic list of dicts for document parts

Returns:

the individual parts of the document

Return type:

list

_ret(m, path_or_stream)

internal method to return or write data

to_json(path_or_stream=None) str

Converts the current object to a JSON file.

Parameters:

path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.

Returns:

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

Return type:

str

to_markdown(path_or_stream=None, embed_images=True) str

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

Parameters:
  • path_or_stream (str or io.IOBase, optional) – The path to save the Markdown file to, or a file-like object to write the data to. If not provided, the Markdown string will be returned.

  • embed_images (bool, optional) – Whether to embed images as base64 strings within the Markdown. Defaults to True.

Returns:

The Markdown string if path_or_stream is not provided, or True if the Markdown was successfully written to the file or stream.

Return type:

str or bool

to_docx(path_or_stream=None, template: str = None, template_params=None, use_w32=False, as_pdf=False, compress_images=False, allow_pandoc=True) bytes

Converts the current object to a DOCX file, or a PDF file via DOCX (WARNING some options need win32com and word installed if selected).

Parameters:
  • template (str, optional) – Path to a DOCX template file. Defaults to None.

  • template_params (dict, optional) – Parameters to replace fields in the template. Defaults to None.

  • use_w32 (bool, optional) – 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 (bool, optional) – Whether to output the document as a PDF (via docx and win32com). Defaults to False.

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

  • allow_pandoc (bool, optional) – 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=None) str

Converts the current object to an ipynb (iPython notebook) file.

Parameters:

path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.

Returns:

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

Return type:

str

to_html(path_or_stream=None, template=None, template_params=None) str

Converts the current object to a HTML file.

Parameters:
  • path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.

  • template (str, optional) – A string containing the LaTeX code for the document template. Either a Jinja2 Latex template, or a string If not provided, a default template will be used.

  • template_params (dict, optional) – A dictionary containing the parameters for the document template which will be parsed to the “render” method of Jinja2

Returns:

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

Return type:

str

to_typst(path_or_stream=None, template=None, template_params=None) str

Converts the current object to a Typst file.

Parameters:
  • path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.

  • template (str, optional) – A string containing the LaTeX code for the document template. Either a Jinja2 Latex template, or a string If not provided, a default template will be used.

  • template_params (dict, optional) – A dictionary containing the parameters for the document template which will be parsed to the “render” method of Jinja2

Returns:

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

Return type:

str

to_pdf(path_or_stream=None, docname='', files_to_upload=None, base_dir=None, engine=None, latex_compiler=None, n_times_make=None, verb=0, ignore_error=True, template=None, template_params=None, do_escape_template_params='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 (optional) – A list of files to be uploaded 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 (either “typst”, “tex”, “word”, or “libreoffice”). If None, the currently configured engine will be queried 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 the LaTeX compilation. Defaults to True.

  • template (str, optional) – A string containing the LaTeX code for the document template. Either a Jinja2 Latex template, or a string If not provided, a default template will be used.

  • template_params (dict, optional) – A dictionary containing the parameters for the document template which will be parsed to the “render” method of Jinja2

  • do_escape_template_params (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 its a latex string. Defaults to ‘auto’.

Returns:

Either the data as string, or bytes depending on if its binary. Or True|False to indicate if the data was saved successfully to a file or stream.

Return type:

str

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.

to_tex(path_or_stream=None, additional_files=None, template=None, do_escape_template_params='auto', template_params=None, text_only=False)

Converts the current object to a TEX file (and attachments).

Parameters:
  • path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as a string.

  • (dict[str (additional_files) – bytes], optional): Any additional files you want to upload to the tex document, such as an image as a logo in the header.

  • template (str, optional) – The LaTeX template to use.

  • do_escape_template_params (bool, optional) – Whether to escape the template parameters. “auto” will scan for %%latex at the start of a string to determine if its a latex string. Defaults to ‘auto’.

  • template_params (dict, optional) – Additional parameters to pass to the LaTeX template.

  • text_only (bool, optional) – Only valid if path_or_stream is None. Whether or not to return attachments as well. Defaults to False

Returns:

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

str: The tex file as a string. dict: The additional input files needed for LaTeX (bytes) as values and their relative paths (str) as keys.

Return type:

If saving to a file or stream

to_textile(path_or_stream=None, text_only=False)

Converts the current object to a TEXTILE file (and attachments). If path_or_stream is given it will zip all contents and write it to the stream or file path given. If not it will return a tuple with textile (str), files (dict[str, bytes])

Parameters:
  • path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.

  • text_only (bool, optional) – Only valid if path_or_stream is None. Whether or not to return attachments as well. Defaults to False

Returns:

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

str: The tex file as a string. dict: The additional input files needed for LaTeX (bytes) as values and their relative paths (str) as keys.

Return type:

If saving to a file or stream

to_redmine() Tuple[str, list]

Converts the current object to a Redmine Textile like text (and attachments) and returns them as tuple.

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

Converts the current object to a Redmine Textile like text (and attachments) 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.

Parameters:
  • 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.

print_rich(path_or_stream=None, title=None, embed_images=True)

Parses the current object using python rich library and output it either on console or to any file / stream.

Parameters:
  • path_or_stream – Either a file path (str) to write to, a file-like object with a write method, or None to output to stdout

  • title – Optional title for the documentation. If not provided, will attempt to extract from metadata using common title keys. If still None a default title will be used.

  • embed_images – if True this will make the images appear as simplified pixelized pictures on the console, if False it will insert a placeholder instead.

Returns:

Only in path_or_stream is not None. True if successful, False otherwise

Return type:

bool

Example

>>> doc.print_rich("output.rich")
>>> doc.print_rich(sys.stdout)
>>> doc.print_rich()
to_pdf_print(path_or_stream=None)

Exports the document to a PDF file by using the systems “print to pdf” function to export from 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 since they do not have a command line interface for printing to PDF. Use with caution and make sure to test it on your system before using it in production!

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:

output_pdf_path (str, optional) – The path to save the PDF file to. If not provided, a temporary file will be used.

Returns:

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

str: The PDF file as bytes.

Return type:

If saving to a file or stream

export_all(dir_path=None, report_name='exported_report', **kwargs)

Exports the document to all possible formats.

Parameters:
  • dir_path (str, optional) – The path to the directory where the exported files should be saved. If not provided, a dict with the returned data from the exporters will be returned.

  • report (str, optional) – The base name for the exported files. Defaults to “exported_report”.

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

Returns:

A dictionary containing the exported data or paths for each engine.

Return type:

dict

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

Exports the document to multiple formats.

Parameters:
  • engines (list[str], optional) – A list of export engines to use. If not provided, all supported engines will be used.

  • dir_path (str, optional) – The path to the directory where the exported files should be saved. If not provided, a dict with the returned data from the exporters will be returned.

  • report (str, optional) – The base name for the exported files. Defaults to “exported_report”.

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

Returns:

A dictionary containing the exported data or paths for each engine.

Return type:

dict

export(engine: str, path_or_stream=None, **kwargs)

Exports the document to a specified format.

Parameters:
  • engine (str) – The format to export to. Valid options are: ‘md’, ‘markdown’, ‘json’, ‘html’, ‘tex’, ‘latex’, ‘textile’, ‘word’, ‘docx’, and ‘redmine’.

  • path_or_stream (str or io.IOBase, optional) – The path to save the exported file to, or a file-like object to write the data to.

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

Returns:

The exported data or True if the data was successfully written to a file or stream.

Return type:

str or bool

Raises:

KeyError – If the specified engine is not supported.

upload(url, doc_name='', force_overwrite=False, page_title='', requests_kwargs=None, raise_on_fail=True, warn_on_fail=True)
Uploads the document data to a specified URL using HTTP(s) and requests.

The json body is constructed as:

upload = {

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

}

Parameters:
  • url (str) – The URL of the endpoint that accepts the document data.

  • doc_name (str, optional) – The name of the uploaded document. Defaults to ‘’.

  • force_overwrite (bool, optional) – Whether to overwrite an existing document. Defaults to False.

  • page_title (str, optional) – The title of the uploaded document (if applicable). Defaults to ‘’.

  • requests_kwargs – (dict, optional) with kwargs for requests.post(). Defaults to None.

  • raise_on_fail – (bool, optional): set True to raise an exception on failed upload. Defaults to True.

  • warn_on_fail – (bool, optional): set True to prompt some warning text with the feedback from server on a fail. Defaults to True.

Returns:

The JSON response from the server after uploading the document.

Return type:

dict

Raises:

requests.exceptions.RequestException – If the upload request fails.

show(engine=None, index=None, chapter=None, files_to_upload=None, template=None, template_params=None, do_escape_template_params=False, embed_images=True, **kwargs)

Displays the document or a specific part of it in ipython display or via print

Parameters:
  • engine (str, optional) – The engine to use for displaying. None to decide based on the currently available console. Else either “html”, “markdown”, “md”, “tex”, “latex”, or “pdf” (pdf only works in Ipython!)

  • index (int, optional) – The index of the part to display.

  • chapter (str, optional) – The name of the chapter to display.

  • files_to_upload (dict, optional) – ONLY VALID WHEN engine=’pdf’. See to_pdf method for details. Defaults to None.

  • template (jinja2 template or string, optional) – ONLY VALID WHEN engine=’pdf’. See to_pdf method for details. Defaults to None.

  • template_params (dict, optional) – ONLY VALID WHEN engine=’pdf’. See to_pdf method for details. Defaults to None.

  • do_escape_template_params (bool, optional) – ONLY VALID WHEN engine=’pdf’. See to_pdf method for details. Defaults to False.

  • embed_images (bool, optional) – ONLY VALID WHEN engine=’md’ or ‘rich’. Whether to embed (show) images within the document, or placeholders. Defaults to True.

Raises:
  • KeyError – if the specified engine is not found or not valid

  • AssertionError – If both index and chapter are specified.

__repr__(*args, **kwargs)
__str__(*args, **kwargs)
classmethod get_example()
pydocmaker.construct(typ: str, **kwargs)

construct a document-part dict from the given typ and some kwargs

class pydocmaker.constr

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

typalias
static meta(children='', data=None, **kwargs)
static markdown(children='', color='', end=None)
static text(children='', color='', end=None)
static line(children='', color='', end=None)
static latex(children='', color='', end=None)
static verbatim(children='', color='', end=None)
static iter(children: list = None, color='', end=None)
static table(children: list = None, color='', end=None, header=None, caption=None, n_cols=None, n_rows=None, borders=True)
static image(imageblob='', caption='', children='', width=None, color='', end=None)
static image_from_file(path, children='', caption='', width=None, color='', end=None)
image_from_fig(width=None, children=None, fig=None, color='', end=None, bbox_inches='tight', **kwargs)

convert a matplotlib figure (or the current figure) to a document image dict to later add to a document

Parameters:
  • 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.

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

Returns:

dict

static image_from_obj(img, caption='', width=None, children=None, color='', end=None)

make a image type dict from given image of type matrix, filelike or PIL image

Parameters:
  • im (np.array) – the image as NxMx

  • 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.

Returns:

dict with the results

pydocmaker.buildingblocks
pydocmaker.print_to_pdf(file_path, output_pdf_path)

Prints a file to a PDF file using the appropriate platform-specific command using subprocess

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 since they do not have a command line interface for printing to PDF. Use with caution and make sure to test it on your system before using it in production!

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 (str) – The path to the file to print.

  • output_pdf_path (str) – The path to the output PDF file.

Raises:

ValueError – If the platform is not supported.

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=1000, height=1200)

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
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)
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)
static get_available_tids(template_dir=None)
template
params = None
attachments = None
env
template_id = None
property tformat
__str__()
__repr__()
find_undeclared_variables()

Find undeclared variables in the template.

Returns:

A set of undeclared variable names used in the template.

Return type:

set

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)

A class used to manage templates, parameters, and attachments from a specified directory.

template_dir

a string representing the directory path where the templates are located

Type:

str

env

an Environment object from the jinja2 library used to load templates

Type:

Environment

get_params(templates=None)

Returns a dictionary of parameters for the specified templates.

get_templates()

Returns a dictionary of templates in the directory.

get_template_ids()

Returns a list of template IDs.

get_attachments(templates=None)

Returns a dictionary of attachments for the specified templates.

get_all(load_params=True, load_attachments=True)

Returns a tuple containing dictionaries of templates, parameters, and attachments.

resolve_template_id(my_template_id)

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

template_dirs = None
env
find_undeclared_variables(template)

Find undeclared variables in a template.

Parameters:

template (str) – The template to analyze.

Returns:

A set of undeclared variable names used in the template.

Return type:

set

get_params(templates=None) dict

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

Parameters:

templates (iterable str) – A dictionary of template params. If None, all templates are loaded.

Returns:

A dictionary of parameters for the specified templates with dict[template_id, dict[param_name,param_value]].

Return type:

dict

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.

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)

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

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 (either ‘tex’, or ‘html’) 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.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()
pydocmaker.config_pdf_engine_set(choice: str = 'typst')

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=False, firstonly=False)

Configures the PDF engine and tests its availability.

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_pdf_engine_test(raise_on_error=True, force_reload=False)

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()
pydocmaker.config_renderer_default_set(choice: str = 'auto')

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

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

Default is ‘auto’.

Returns: str: The selected renderer_default.

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