pydocmaker
==========
.. py:module:: pydocmaker
Submodules
----------
.. toctree::
:maxdepth: 1
/autoapi/pydocmaker/b64_data/index
/autoapi/pydocmaker/backend/index
/autoapi/pydocmaker/core/index
/autoapi/pydocmaker/templating/index
/autoapi/pydocmaker/util/index
Attributes
----------
.. autoapisummary::
pydocmaker.__version__
pydocmaker.buildingblocks
pydocmaker.colors_dc
pydocmaker.config_pandoc_allowed_set
pydocmaker.config_pandoc_allowed_get
pydocmaker.tex_escape
Classes
-------
.. autoapisummary::
pydocmaker.Doc
pydocmaker.constr
pydocmaker.bcolors
pydocmaker._raise_missing
pydocmaker.DocxFile
pydocmaker.DocxFileW32
pydocmaker.DocTemplate
pydocmaker.TemplateDirSource
pydocmaker.options
Functions
---------
.. autoapisummary::
pydocmaker.construct
pydocmaker.print_to_pdf
pydocmaker.make_pdf_from_tex
pydocmaker.show_pdf
pydocmaker.is_notebook
pydocmaker.upload_report_to_redmine
pydocmaker.txtcolor
pydocmaker.can_use_libreoffice
pydocmaker.can_use_w32_word
pydocmaker.pandoc_convert_file
pydocmaker.pandoc_set_allowed
pydocmaker.pandoc_convert
pydocmaker.register_new_template_dir
pydocmaker.get_registered_template_dirs
pydocmaker.get_available_template_ids
pydocmaker.test_template_exists
pydocmaker.remove_from_template_dir
pydocmaker.config_libreoffice_path_get
pydocmaker.config_libreoffice_path_set
pydocmaker.config_libreoffice_path_find
pydocmaker.config_libreoffice_path_testset
pydocmaker.config_pdf_engine_get
pydocmaker.config_pdf_engine_set
pydocmaker.config_pdf_engine_scan
pydocmaker.config_pdf_engine_test
pydocmaker.config_renderer_default_get
pydocmaker.config_renderer_default_set
pydocmaker.test_typst_installed
pydocmaker.compile_with_typst
pydocmaker.config_latex_compiler_scan
pydocmaker.config_latex_compiler_get
pydocmaker.config_latex_compiler_set
pydocmaker.config_latex_compiler_testset
pydocmaker.info_optionals
pydocmaker.pandoc_set_enabled
pydocmaker.pandoc_set_disabled
pydocmaker.get_schema
pydocmaker.get_example
pydocmaker.load
pydocmaker.md2tex
pydocmaker.mk_chapter
pydocmaker.mk_meta
pydocmaker.mk_tex
pydocmaker.mk_md
pydocmaker.mk_pre
pydocmaker.mk_fig
pydocmaker.mk_image
Package Contents
----------------
.. py:data:: __version__
:value: '2.6.7'
.. py:class:: Doc(initial_data=None)
Bases: :py:obj:`collections.UserList`
a collection of document parts to make a document (can be used like a list)
.. py:attribute:: DEFAULT_ADD_STRING_TYPE
:value: 'markdown'
.. py:attribute:: EXPORT_ENGINES
:value: ['md', 'html', 'typst', 'json', 'docx', 'textile', 'ipynb', 'tex', 'redmine', 'pdf']
.. py:attribute:: EXPORT_ENGINES_EXTENSIONS
.. py:method:: load_json(path)
:staticmethod:
Load a JSON file and return a Doc object.
:param path: The path to the JSON file or a file-like object.
:type path: str or file-like object
:returns: A Doc object initialized with the loaded JSON data.
:rtype: Doc
:raises json.JSONDecodeError: If the JSON file is not valid.
:raises TypeError: If the loaded JSON object is not of type list.
.. py:method:: __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.
.. py:method:: __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.
.. py:method:: flatten()
Unpacks all iterator elements within this document and returns a new flat document.
:returns: A new document with all elements flattened.
:rtype: Doc
.. py:method:: add_chapter(chapter_name: str, chapter_index=None, color='')
Adds a new chapter to the document.
:param chapter_name: The name of the new chapter.
:type chapter_name: str
:param chapter_index: The index after which chapter to insert the new chapter. If None, appends to the end.
:type chapter_index: int, optional
:raises AssertionError: If `chapter_name` is not a string or is empty.
.. py:method:: get_chapter(chapter) -> List[dict]
Retrieves a specific chapter from the document.
:param chapter: The name of the chapter to retrieve.
:type chapter: str
:returns: A list of dictionaries representing the content of the specified chapter.
:rtype: List[dict]
.. py:method:: 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.
:param as_ranges: 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.
:type as_ranges: bool, optional
: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.
:rtype: dict or dict[str, range]
.. py:method:: 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.
:param tformat: The format of the template either 'tex' or 'html'. Defaults to ''.
:type tformat: str, optional
:param template_dir: If this is given only this specific template dir is mounted to load templates from. Otherwise all registered templates are loaded
:type template_dir: str, optional
:param 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.
:rtype: DocTemplate
.. py:method:: 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.
:param template_id: The ID of the template to set.
:type template_id: str
:param with_params: Whether to include the (default) parameters from the template in the metadata. Defaults to True.
:type with_params: bool, optional
:param with_assets: Whether to include the assets (files) from the template in the metadata. Defaults to True.
:type with_assets: bool, optional
:param test_found: Whether to test if the template exists before adding anything. Defaults to True.
:type test_found: bool, optional
:param on_exist: 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'.
:type on_exist: str, optional
:param template_params: Additional parameters to add to the template. Defaults to None.
:type template_params: dict, optional
:raises FileNotFoundError: If the template with the given ID does not exist.
:raises AssertionError: If overwrite protection is enabled and the template would overwrite existing data.
:raises ValueError: If an unknown value is passed for the on_exist parameter.
:returns: the meta elements data (content)
:rtype: dict
.. py:method:: 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.
:param doc_name: The name of the document.
:type doc_name: str
:param regex_pattern: The regular expression pattern to use for parsing (can also give multiple as list or tuple).
:type regex_pattern: str
:param fancy_title_analysis: Will Analyse the title for "signed" in it and also resolve CamelCasing from it
:type fancy_title_analysis: bool, optional
:returns: A dictionary containing the parsed metadata.
:rtype: dict
.. rubric:: Example
>>> import pydocmaker as pyd
>>> doc = pyd.Doc()
>>> regex_pattern = r'(?P
\w+)-(?P[a-zA-Z0-9]+)-(?P\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'}
.. py:method:: 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.
:param \*args: A single dictionary containing metadata.
:param \*\*kwargs: Key-value pairs representing metadata.
:returns: The updated metadata.
:rtype: dict
.. py:method:: get_meta(default=None) -> Union[Dict, None]
gets the (first) meta element in this document if it exists. If not returns None
.. py:method:: get_metadata() -> Union[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
.. py:method:: has_meta() -> bool
tests if this document has one or more metadata objects
.. py:method:: update_meta(*args, **kwargs) -> Union[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.
.. rubric:: Examples
.update_meta({'doc_name': 'test'})
.update_meta(doc_name='test')
:returns: The updated metadata content.
:rtype: dict
.. py:method:: 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.
.. rubric:: Examples
.add_meta({'doc_name': 'test'})
.add_meta(doc_name='test')
:returns: The metadata element's data (content).
:rtype: dict
.. py:method:: 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.
:param part: The part to add. See the `constr` class for all possible parts.
:type part: dict
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex (ONLY VALID FOR string INPUTS!). Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:raises ValueError: If the `part` is invalid, or if both `index` and `chapter` are specified.
:raises AssertionError: If `index` is not an integer or is out of bounds.
.. py:method:: add_kw(typ, children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a document part to this document with a given typ
:param typ: one of the allowed document part types. Either 'markdown', 'verbatim', 'text', 'iter' or 'image'.
:type typ: str, optional
:param children: the "children" for this element. Either text directly (as string) or a list of other parts
:type children: str or list
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:param kwargs: the kwargs for such a document part
.. py:method:: add_text(children=None, index=None, chapter=None, color='', **kwargs)
add a raw text part to this document
:param children: the "children" for this element. Either text directly (as string) or a list of other parts
:type children: str or list
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param kwargs: the kwargs for such a document part
.. py:method:: add_tex(children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a latex part to this document
:param children: the "children" for this element. Either text directly (as string) or a list of other parts
:type children: str or list
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param kwargs: the kwargs for such a document part
.. py:method:: add_md(children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a markdown document part to this document
:param children: the "children" for this element. Either text directly (as string) or a list of other parts
:type children: str or list
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:param kwargs: the kwargs for such a document part
.. py:method:: 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
:param children: the "children" for this element. Must be a matrix (list of lists) with formatable elements in it.
:type children: list of lists
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:param header: The header row for the table. If given it must be a list with formatable elements in it.
:type header: list, optional
:param caption: The caption to place at/under the table. Empty for no caption.
:type caption: str, optional
:param n_rows: The number of rows to give this table. If not given it will be determined from the number of rows in children.
:type n_rows: int, optional
:param n_cols: 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.
:type n_cols: int, optional
:param borders: Whether or not the table should have lines between its cells.
:type borders: bool, optional
.. py:method:: add_pre(children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a verbaim (pre formatted) document part to this document
:param children: the "children" for this element. Either text directly (as string) or a list of other parts
:type children: str or list
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:param kwargs: the kwargs for such a document part
.. py:method:: 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.
:param fig: the figure which to upload (or the current figure if None). Defaults to None.
:type fig: matplotlib figure, optional
:param caption: the caption to give to the image. Defaults to ''.
:type caption: str, optional
:param width: The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
:type width: float, optional
:param bbox_inches: will give better spacing for matplotlib figures.
:type bbox_inches: str, optional
:param children: A specific name/id to give to the image (will be auto generated if None). Defaults to None.
:type children: str, optional
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
.. py:method:: 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
:param im: the image as NxMx
:type im: np.array
:param caption: the caption to give to the image. Defaults to ''.
:type caption: str, optional
:param width: The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
:type width: float, optional
:param children: A specific name/id to give to the image (will be auto generated if None). Defaults to None.
:type children: str, optional
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
.. py:method:: dump() -> List[Dict]
dump this document to a basic list of dicts for document parts
:returns: the individual parts of the document
:rtype: list
.. py:method:: _ret(m, path_or_stream)
internal method to return or write data
.. py:method:: to_json(path_or_stream=None) -> str
Converts the current object to a JSON file.
:param path_or_stream: 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.
:type path_or_stream: str or io.IOBase, optional
:returns: The JSON data as string, or True if the data was saved successfully to a file or stream.
:rtype: str
.. py:method:: to_markdown(path_or_stream=None, embed_images=True) -> str
Converts the current object to a Markdown string or writes it to a file.
:param path_or_stream: 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.
:type path_or_stream: str or io.IOBase, optional
:param embed_images: Whether to embed images as base64 strings within the Markdown. Defaults to True.
:type embed_images: bool, optional
:returns: The Markdown string if `path_or_stream` is not provided, or True if the Markdown was successfully written to the file or stream.
:rtype: str or bool
.. py:method:: 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).
:param template: Path to a DOCX template file. Defaults to None.
:type template: str, optional
:param template_params: Parameters to replace fields in the template. Defaults to None.
:type template_params: dict, optional
:param 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.
:type use_w32: bool, optional
:param as_pdf: Whether to output the document as a PDF (via docx and win32com). Defaults to False.
:type as_pdf: bool, optional
:param compress_images: Whether to compress images in the document using win32com. Defaults to False.
:type compress_images: bool, optional
:param allow_pandoc: whether or not to allow the usage of pandoc instead of python-docx (usually pandoc creates nicer documents!)
:type allow_pandoc: bool, optional
:returns: The data as bytes, or True if the data was saved successfully to a file or stream.
:rtype: bytes
:raises ValueError: If attempting to export to PDF without win32com and Word.Application installed and use_w32 set to True.
.. py:method:: to_ipynb(path_or_stream=None) -> str
Converts the current object to an ipynb (iPython notebook) file.
:param path_or_stream: 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.
:type path_or_stream: str or io.IOBase, optional
:returns: The data as string, or True if the data was saved successfully to a file or stream.
:rtype: str
.. py:method:: to_html(path_or_stream=None, template=None, template_params=None) -> str
Converts the current object to a HTML file.
:param path_or_stream: 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.
:type path_or_stream: str or io.IOBase, optional
:param template: 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.
:type template: str, optional
:param template_params: A dictionary containing the parameters for the document template which will be parsed to the "render" method of Jinja2
:type template_params: dict, optional
:returns: The data as string, or True if the data was saved successfully to a file or stream.
:rtype: str
.. py:method:: to_typst(path_or_stream=None, template=None, template_params=None) -> str
Converts the current object to a Typst file.
:param path_or_stream: 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.
:type path_or_stream: str or io.IOBase, optional
:param template: 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.
:type template: str, optional
:param template_params: A dictionary containing the parameters for the document template which will be parsed to the "render" method of Jinja2
:type template_params: dict, optional
:returns: The data as string, or True if the data was saved successfully to a file or stream.
:rtype: str
.. py:method:: 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) -> Union[str, bytes, bool]
Converts the current object to a PDF file or zipped latex project folder.
:param path_or_stream: 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.
:type path_or_stream: str or file-like object, optional
:param docname: The name of the output document. Defaults to a unix timestamp followed by '_mydocument'.
:type docname: str, optional
:param files_to_upload: A list of files to be uploaded with the document.
:type files_to_upload: optional
:param base_dir: The directory to use as the base directory for the temporary directory.
Defaults to the system's default temporary directory.
:type base_dir: str, optional
:param engine: 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().
:type engine: str, optional
:param latex_compiler: 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.
:type latex_compiler: str, optional
:param n_times_make: 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.
:type n_times_make: int, optional
:param verb: The verbosity level (0, 1, 2). If greater than 0, the function will print more and more debug information. Defaults to 0.
:type verb: int, optional
:param ignore_error: Whether to ignore errors during the LaTeX compilation. Defaults to True.
:type ignore_error: bool, optional
:param template: 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.
:type template: str, optional
:param template_params: A dictionary containing the parameters for the document template which will be parsed to the "render" method of Jinja2
:type template_params: dict, optional
:param do_escape_template_params: 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'.
:type do_escape_template_params: bool, optional
: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.
:rtype: 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.
.. py:method:: 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).
:param path_or_stream: 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.
:type path_or_stream: str or io.IOBase, optional
:param additional_files (dict[str: bytes], optional): Any additional files you want to upload to the tex document, such as an image as a logo in the header.
:param template: The LaTeX template to use.
:type template: str, optional
:param do_escape_template_params: 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'.
:type do_escape_template_params: bool, optional
:param template_params: Additional parameters to pass to the LaTeX template.
:type template_params: dict, optional
:param text_only: Only valid if path_or_stream is None. Whether or not to return attachments as well. Defaults to False
:type text_only: bool, optional
: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.
:rtype: If saving to a file or stream
.. py:method:: 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])
:param path_or_stream: 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.
:type path_or_stream: str or io.IOBase, optional
:param text_only: Only valid if path_or_stream is None. Whether or not to return attachments as well. Defaults to False
:type text_only: bool, optional
: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.
:rtype: If saving to a file or stream
.. py:method:: to_redmine() -> Tuple[str, list]
Converts the current object to a Redmine Textile like text (and attachments) and returns them as tuple.
.. py:method:: 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.
:param redmine: A Redmine connection object.
:type redmine: redminelib.Redmine
:param project_id: The ID of the Redmine project where the report should be uploaded.
:type project_id: str
:param report_name: The name of the report. If not provided, the follwoing schema `%Y%m%d_%H%M_exported_report` will be used.
:type report_name: str, optional
:param page_title: The title of the Redmine wiki page. If not provided, it will be derived from the report name.
:type page_title: str, optional
:param force_overwrite: Whether to overwrite an existing page with the same title. Defaults to False.
:type force_overwrite: bool, optional
:param verb: Whether to print verbose output during upload. Defaults to True.
:type verb: bool, optional
:returns: The uploaded Redmine wiki page object.
:rtype: redminelib.WikiPage
:raises AssertionError: If any of the `doc`, `project_id` or `redmine` arguments is None or empty.
.. py:method:: 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.
:param 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
:param 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.
:param 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
:rtype: bool
.. rubric:: Example
>>> doc.print_rich("output.rich")
>>> doc.print_rich(sys.stdout)
>>> doc.print_rich()
.. py:method:: 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.
:param output_pdf_path: The path to save the PDF file to. If not provided, a temporary file will be used.
:type output_pdf_path: str, optional
:returns: True if the data was saved successfully to a file or stream.
If returning:
str: The PDF file as bytes.
:rtype: If saving to a file or stream
.. py:method:: export_all(dir_path=None, report_name='exported_report', **kwargs)
Exports the document to all possible formats.
:param dir_path: 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.
:type dir_path: str, optional
:param report: The base name for the exported files. Defaults to "exported_report".
:type report: str, optional
:param \*\*kwargs: Additional keyword arguments specific to the chosen export formats.
:returns: A dictionary containing the exported data or paths for each engine.
:rtype: dict
.. py:method:: export_many(engines: List[str] = None, dir_path=None, report_name='exported_report', **kwargs)
Exports the document to multiple formats.
:param engines: A list of export engines to use. If not provided, all supported engines will be used.
:type engines: list[str], optional
:param dir_path: 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.
:type dir_path: str, optional
:param report: The base name for the exported files. Defaults to "exported_report".
:type report: str, optional
:param \*\*kwargs: Additional keyword arguments specific to the chosen export formats.
:returns: A dictionary containing the exported data or paths for each engine.
:rtype: dict
.. py:method:: export(engine: str, path_or_stream=None, **kwargs)
Exports the document to a specified format.
:param engine: The format to export to. Valid options are: 'md', 'markdown', 'json', 'html', 'tex', 'latex', 'textile', 'word', 'docx', and 'redmine'.
:type engine: str
:param path_or_stream: The path to save the exported file to, or a file-like object to write the data to.
:type path_or_stream: str or io.IOBase, optional
:param \*\*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.
:rtype: str or bool
:raises KeyError: If the specified `engine` is not supported.
.. py:method:: 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
}
:param url: The URL of the endpoint that accepts the document data.
:type url: str
:param doc_name: The name of the uploaded document. Defaults to ''.
:type doc_name: str, optional
:param force_overwrite: Whether to overwrite an existing document. Defaults to False.
:type force_overwrite: bool, optional
:param page_title: The title of the uploaded document (if applicable). Defaults to ''.
:type page_title: str, optional
:param requests_kwargs: (dict, optional) with kwargs for requests.post(). Defaults to None.
:param raise_on_fail: (bool, optional): set True to raise an exception on failed upload. Defaults to True.
:param 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.
:rtype: dict
:raises requests.exceptions.RequestException: If the upload request fails.
.. py:method:: 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
:param engine: 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!)
:type engine: str, optional
:param index: The index of the part to display.
:type index: int, optional
:param chapter: The name of the chapter to display.
:type chapter: str, optional
:param files_to_upload: ONLY VALID WHEN engine='pdf'. See to_pdf method for details. Defaults to None.
:type files_to_upload: dict, optional
:param template: ONLY VALID WHEN engine='pdf'. See to_pdf method for details. Defaults to None.
:type template: jinja2 template or string, optional
:param template_params: ONLY VALID WHEN engine='pdf'. See to_pdf method for details. Defaults to None.
:type template_params: dict, optional
:param do_escape_template_params: ONLY VALID WHEN engine='pdf'. See to_pdf method for details. Defaults to False.
:type do_escape_template_params: bool, optional
:param embed_images: ONLY VALID WHEN engine='md' or 'rich'. Whether to embed (show) images within the document, or placeholders. Defaults to True.
:type embed_images: bool, optional
:raises KeyError: if the specified engine is not found or not valid
:raises AssertionError: If both `index` and `chapter` are specified.
.. py:method:: __repr__(*args, **kwargs)
.. py:method:: __str__(*args, **kwargs)
.. py:method:: get_example()
:classmethod:
.. py:function:: construct(typ: str, **kwargs)
construct a document-part dict from the given typ and some kwargs
.. py:class:: constr
This is the basic schema for the main building blocks for a document
.. py:attribute:: typalias
.. py:method:: meta(children='', data=None, **kwargs)
:staticmethod:
.. py:method:: markdown(children='', color='', end=None)
:staticmethod:
.. py:method:: text(children='', color='', end=None)
:staticmethod:
.. py:method:: line(children='', color='', end=None)
:staticmethod:
.. py:method:: latex(children='', color='', end=None)
:staticmethod:
.. py:method:: verbatim(children='', color='', end=None)
:staticmethod:
.. py:method:: iter(children: list = None, color='', end=None)
:staticmethod:
.. py:method:: table(children: list = None, color='', end=None, header=None, caption=None, n_cols=None, n_rows=None, borders=True)
:staticmethod:
.. py:method:: image(imageblob='', caption='', children='', width=None, color='', end=None)
:staticmethod:
.. py:method:: image_from_link(url, caption='', children='', width=None, color='', end=None)
:staticmethod:
.. py:method:: image_from_file(path, children='', caption='', width=None, color='', end=None)
:staticmethod:
.. py:method:: 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
:param caption: the caption to give to the image. Defaults to ''.
:type caption: str, optional
:param width: The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
:type width: float, optional
:param children: A specific name/id to give to the image (will be auto generated if None). Defaults to None.
:type children: str, optional
:param fig: the figure which to upload (or the current figure if None). Defaults to None.
:type fig: matplotlib figure, optional
:returns: dict
.. py:method:: image_from_obj(img, caption='', width=None, children=None, color='', end=None)
:staticmethod:
make a image type dict from given image of type matrix, filelike or PIL image
:param im: the image as NxMx
:type im: np.array
:param caption: the caption to give to the image. Defaults to ''.
:type caption: str, optional
:param width: The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
:type width: float, optional
:param children: A specific name/id to give to the image (will be auto generated if None). Defaults to None.
:type children: str, optional
:returns: dict with the results
.. py:data:: buildingblocks
.. py:function:: 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.
:param file_path: The path to the file to print.
:type file_path: str
:param output_pdf_path: The path to the output PDF file.
:type output_pdf_path: str
:raises ValueError: If the platform is not supported.
.. py:function:: 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.
:param input_latex_text: The LaTeX document as a string or bytes.
:type input_latex_text: str or bytes
:param attachments_dc: 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.
:type attachments_dc: dict, optional
:param docname: The name of the output document. Defaults to a timestamp.
:type docname: str, optional
:param out_format: The format of the output. Either 'pdf' or 'zip'. Defaults to 'pdf'.
:type out_format: str, optional
:param base_dir: The directory to use as the base directory for the temporary directory.
Defaults to the system's default temporary directory.
:type base_dir: str, optional
:param latex_compiler: 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.
:type latex_compiler: str, optional
:param n_times_make: The number of times to run the LaTeX compiler. Defaults to 1 for pandoc and 3 for al others.
:type n_times_make: int, optional
:param verb: The verbosity level. If greater than 0, the function will print debug information. Defaults to 0.
:type verb: int, optional
:param ignore_error: Whether to ignore errors during the LaTeX compilation. Defaults to False.
:type ignore_error: bool, optional
:returns: The PDF document as bytes, or a ZIP file containing the PDF and all attachments as bytes.
:rtype: bytes
:raises ValueError: If the input_latex_text is not a string or bytes, or if the docname is not a string.
:raises ValueError: If the latex_compiler is not 'pdflatex', 'lualatex', 'xelatex', or 'pandoc'.
:raises ValueError: If the out_format is not 'pdf' or 'zip'.
:raises AssertionError: If the attachments_dc contains invalid keys or values.
.. py:function:: 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)
.. py:function:: is_notebook() -> bool
.. py:function:: 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.
:param doc: The Doc object containing the report data.
:type doc: Doc
:param redmine: A Redmine connection object.
:type redmine: redminelib.Redmine
:param project_id: The ID of the Redmine project where the report should be uploaded.
:type project_id: str
:param report_name: The name of the report. If not provided, the follwoing schema `%Y%m%d_%H%M_exported_report` will be used.
:type report_name: str, optional
:param page_title: The title of the Redmine wiki page. If not provided, it will be derived from the report name.
:type page_title: str, optional
:param force_overwrite: Whether to overwrite an existing page with the same title. Defaults to False.
:type force_overwrite: bool, optional
:param verb: Whether to print verbose output during upload. Defaults to True.
:type verb: bool, optional
:returns: The uploaded Redmine wiki page object.
:rtype: redminelib.WikiPage
:raises AssertionError: If any of the `doc`, `project_id` or `redmine` arguments is None or empty.
.. py:class:: bcolors(*args, **kwds)
Bases: :py:obj:`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
- value lookup:
>>> Color(1)
- name lookup:
>>> Color['RED']
Enumerations can be iterated over, and know how many members they have:
>>> len(Color)
3
>>> list(Color)
[, , ]
Methods can be added to enumerations, and members can have their own
attributes -- see the documentation for details.
.. py:attribute:: HEADER
:value: '\x1b[95m'
.. py:attribute:: OKBLUE
:value: '\x1b[94m'
.. py:attribute:: OKCYAN
:value: '\x1b[96m'
.. py:attribute:: OKGREEN
:value: '\x1b[92m'
.. py:attribute:: WARNING
:value: '\x1b[93m'
.. py:attribute:: FAIL
:value: '\x1b[91m'
.. py:attribute:: ENDC
:value: '\x1b[0m'
.. py:attribute:: BOLD
:value: '\x1b[1m'
.. py:attribute:: UNDERLINE
:value: '\x1b[4m'
.. py:function:: txtcolor(s: str, color: str)
.. py:data:: colors_dc
.. py:class:: _raise_missing(*args, **kwargs)
.. py:method:: __getattr__(name)
:classmethod:
.. py:class:: 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.
.. py:attribute:: file_path_or_buffer
.. py:attribute:: docx_data
.. py:attribute:: inp_data
.. py:method:: _get_bytes_file_or_buffer(file_path_or_buffer)
Retrieve bytes from a file path or buffer.
:param file_path_or_buffer: Path to the DOCX file or a buffer containing DOCX data.
:return: Bytes of the DOCX file.
.. py:method:: append(*files, verb=0) -> bytes
Append multiple Word (.docx) documents into a single document.
:param files: Variable length argument list of either (bytes, or file paths, or buffers) to be appended.
:param verb: Verbosity level (0 for silent, 1 for verbose).
:return: The current instance of DocxFile with the appended DOCX data.
.. py:method:: replace_fields(replace_dict)
Replace all MergeFields of a DOCX file with given text in form of a dict.
:param replace_dict: Dictionary where keys are field names and values are replacement texts.
:return: The current instance of DocxFile with the replaced fields.
.. py:method:: get_fields()
Retrieve the merge fields from the DOCX document.
:returns: A list of merge fields present in the DOCX document.
:rtype: list
.. py:method:: replace_keywords(replace_dict)
Edit raw XML content of a DOCX file by replacing specified strings using python-docx.
:param replace_dict: Dictionary where keys are strings to be replaced and values are replacement strings.
:return: The current instance of DocxFile with the replaced keywords.
.. py:method:: replace_keywords_raw(replace_dict)
Edit raw XML content of a DOCX file by replacing specified strings in all XML files within the document.
:param replace_dict: Dictionary where keys are strings to be replaced and values are replacement strings.
:return: The current instance of DocxFile with the replaced keywords in raw XML.
.. py:method:: save(output_path_or_buffer=None)
Save the modified DOCX data to a file or buffer.
:param output_path_or_buffer: File path or buffer to save the DOCX data.
:return: The current instance of DocxFile.
.. py:class:: 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!
.. py:method:: is_installed(verb=0, force_reload=False, ret_int=False)
:staticmethod:
.. py:attribute:: docx_path
:value: b'.'
.. py:attribute:: outpath
:value: None
.. py:attribute:: word
:value: None
.. py:attribute:: worddoc
:value: None
.. py:attribute:: _created_word_app
:value: False
.. py:method:: __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.
:rtype: DocxFileW32
.. py:method:: compress_images(compressionQuality=msoPictureCompress.Screen)
Compress all images within the document based on specified quality settings.
:param compressionQuality: The compression level to apply to images.
Defaults to msoPictureCompress.Screen (quality 4).
:type compressionQuality: msoPictureCompress or int
:returns: The instance itself to allow method chaining.
:rtype: DocxFileW32
.. py:method:: update_fields()
Update all fields in the document, including those in headers and footers.
:returns: The instance itself to allow method chaining.
:rtype: DocxFileW32
.. py:method:: export(pdf_path=None, optimize_for_screen=True)
Export the document to PDF format with specified options.
:param pdf_path: The path where the PDF will be saved. If None, uses outpath.
:type pdf_path: str, optional
:param optimize_for_screen: True for wdExportOptimizeForOnScreen (=1) else wdExportOptimizeForPrint (=0).
:type optimize_for_screen: bool
:returns: The instance itself to allow method chaining.
:rtype: DocxFileW32
:raises AssertionError: If pdf_path is None and outpath is also None.
.. py:method:: save()
.. py:method:: close()
.. py:method:: __exit__(exc_type, exc_value, traceback)
Exit the runtime context for the DocxFileW32 instance, saving and closing resources.
:param exc_type: Exception type (if any) that occurred during execution.
:param exc_value: Exception value (if any) that occurred during execution.
:param traceback: Traceback object (if any) that occurred during execution.
.. py:function:: can_use_libreoffice(force_reload=False)
test if libreoffice is available
:param force_reload: whether or not to force to re-test, if it has been tested before. Defaults to False.
:type force_reload: bool, optional
:returns: True if available, False if not
:rtype: bool
.. py:function:: can_use_w32_word(verb=0, force_reload=False)
test if Microsoft Word is available and win32com library is available
:param verb: whether or not to give verbose info. Defaults to 0.
:type verb: int, optional
:param force_reload: whether or not to force to re-test, if it has been tested before. Defaults to False.
:type force_reload: bool, optional
:returns: True if both are available, False if not
:rtype: bool
.. py:function:: 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.
.. py:function:: pandoc_set_allowed(is_allowed)
Set whether or not pandoc is allowed to be used as a valid conversion option
.. py:function:: 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.
:param input_string: The text to be converted
:type input_string: str
:param input_format: The source format (e.g., 'markdown', 'rst')
:type input_format: str
:param output_format: The target format (e.g., 'html', 'latex')
:type output_format: str
:param is_binary: If True, treat input/output as binary data
:type is_binary: bool
:param \*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
:rtype: 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.
.. py:data:: config_pandoc_allowed_set
.. py:data:: config_pandoc_allowed_get
.. py:class:: 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.
.. attribute:: template
A string representation of the template.
:type: str
.. attribute:: params
A dictionary of parameters to be used in the template.
:type: dict
.. attribute:: attachments
A dictionary of attachments to be used in the template.
:type: dict
.. attribute:: env
An instance of the jinja2 Environment class.
:type: Environment
.. py:method:: from_tid(template_id: str, tformat='', template_dir=None)
:staticmethod:
Load a template by supplying a template_id and possibly a template format
:param template_id: The ID of the template to load e.G. "base"
:type template_id: str
:param tformat: optinal the template format to get e.G. ".tex" or ".html". Defaults to '' which means first of any format being found.
:type tformat: str, optional
:param template_dir: The directory containing the templates.
If not provided, the default template directory is used.
:type template_dir: str, optional
:returns: An instance of the DocTemplate class.
:rtype: DocTemplate
.. py:method:: test_tid_exists(template_id: str, tformat='', template_dir=None)
:staticmethod:
.. py:method:: get_available_tids(template_dir=None)
:staticmethod:
.. py:attribute:: template
.. py:attribute:: params
:value: None
.. py:attribute:: attachments
:value: None
.. py:attribute:: env
.. py:attribute:: template_id
:value: None
.. py:property:: tformat
.. py:method:: __str__()
.. py:method:: __repr__()
.. py:method:: find_undeclared_variables()
Find undeclared variables in the template.
:returns: A set of undeclared variable names used in the template.
:rtype: set
.. py:method:: render(**kwargs)
Render the Jinja2 template with given parameters.
:param \*\*kwargs: Additional parameters to be used in the template.
:returns: The rendered template as a string.
:rtype: str
.. py:class:: TemplateDirSource(template_dirs: List[str] = None)
A class used to manage templates, parameters, and attachments from a specified directory.
...
.. attribute:: template_dir
a string representing the directory path where the templates are located
:type: str
.. attribute:: env
an Environment object from the jinja2 library used to load templates
:type: Environment
.. method:: get_params(templates=None)
Returns a dictionary of parameters for the specified templates.
.. method:: get_templates()
Returns a dictionary of templates in the directory.
.. method:: get_template_ids()
Returns a list of template IDs.
.. method:: get_attachments(templates=None)
Returns a dictionary of attachments for the specified templates.
.. method:: get_all(load_params=True, load_attachments=True)
Returns a tuple containing dictionaries of templates, parameters, and attachments.
.. method:: resolve_template_id(my_template_id)
Returns the full template name corresponding to the given template ID.
.. py:attribute:: template_dirs
:value: None
.. py:attribute:: env
.. py:method:: find_undeclared_variables(template)
Find undeclared variables in a template.
:param template: The template to analyze.
:type template: str
:returns: A set of undeclared variable names used in the template.
:rtype: set
.. py:method:: get_params(templates=None) -> dict
Returns a dictionary of (default) parameters for the specified templates.
:param templates: A dictionary of template params. If None, all templates are loaded.
:type templates: iterable str
:returns: A dictionary of parameters for the specified templates with dict[template_id, dict[param_name,param_value]].
:rtype: dict
.. py:method:: 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.
:rtype: dict
.. py:method:: 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.
:rtype: list
.. py:method:: get_attachments(templates=None)
Get attachments from the template directory.
:param templates: A list or dictionary of templates.
If None, all templates will be used. Defaults to None.
:type templates: list or dict, optional
:returns:
A dictionary of attachments, where the keys are the template names
and the values are dictionaries of attachments for that template.
:rtype: dict
.. py:method:: get_all_filenames()
Get all filenames in all template directories.
.. py:method:: get_all(load_params=True, load_attachments=True)
Get all templates, parameters, and attachments.
:param load_params: Whether to load parameters. Defaults to True.
:type load_params: bool, optional
:param load_attachments: Whether to load attachments. Defaults to True.
:type load_attachments: bool, optional
:returns: A tuple containing templates, parameters, and attachments.
:rtype: tuple
.. py:method:: resolve_template_id(my_template_id)
Resolve the template ID to the actual template file name.
:param my_template_id: The template ID to resolve.
:type my_template_id: str
:returns: The actual template file name.
:rtype: str
:raises KeyError: If the template ID is not found in the available templates.
.. py:method:: __contains__(template_id)
Check if a template_id is in any of the template directories.
.. py:function:: register_new_template_dir(new_template_dir: str, check_exists=True) -> bool
Register a new template directory.
:param new_template_dir: The path to the new template directory.
:type new_template_dir: str
:param check_exists: Whether to check if the directory exists. Defaults to True.
:type check_exists: bool, optional
:raises FileNotFoundError: If the directory does not exist and check_exists is True.
:returns: True if the directory was successfully registered, False otherwise.
:rtype: bool
.. py:function:: get_registered_template_dirs(include_default=True)
Returns a list of registered template directories.
:param include_default: Whether to include the default template directory.
Defaults to True.
:type include_default: bool, optional
:returns:
A list of registered template directories. If include_default is True, the default
template directory is the first element in the list.
:rtype: list
.. py:function:: 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.
:rtype: list
.. py:function:: test_template_exists(template_id, tformat='', template_dir=None)
tests if a template with a given id and optional in a given format exists
:param template_id: the template id to search for e.G. 'base'
:type template_id: str
:param tformat: 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 ''.
:type tformat: str, optional
:param template_dir: if this is given only the given template directory is mounted to load jinja templates. Defaults to ''.
:type template_dir: str, optional
:returns: True if found False otherwise
:rtype: bool
.. py:function:: remove_from_template_dir(to_remove: str) -> bool
Removes an existing template directory if it exists.
:param to_remove: The path to remove from the template dirs.
:type to_remove: str
:returns: Always True
:rtype: bool
.. py:data:: tex_escape
.. py:function:: 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.
:rtype: str|None
.. py:function:: 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.
:rtype: str|None
.. py:function:: config_libreoffice_path_find()
.. py:function:: config_libreoffice_path_testset()
.. py:function:: config_pdf_engine_get()
.. py:function:: 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.
.. py:function:: config_pdf_engine_scan(force_reload=False, firstonly=False)
Configures the PDF engine and tests its availability.
:param raise_on_error: If True, raises a ValueError if no valid compiler is found.
:type raise_on_error: bool
:param force_reload: If True, forces a reload of the PDF engine configuration.
:type force_reload: bool
:returns: True if a valid compiler is found, False otherwise.
:rtype: bool
.. py:function:: config_pdf_engine_test(raise_on_error=True, force_reload=False)
tests the availability of the currently configured PDF engine.
:param raise_on_error: If True, raises a ValueError if no valid compiler is found.
:type raise_on_error: bool
:param force_reload: If True, forces a reload of the PDF engine configuration.
:type force_reload: bool
:returns: True if a valid compiler is found, False otherwise.
:rtype: bool
.. py:function:: config_renderer_default_get()
.. py:function:: 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.
.. py:function:: test_typst_installed()
.. py:function:: compile_with_typst(typst_code: Union[str, List[dict]], output: str = None, verb=1, on_warning='warn', format=None, attachments=None, **kwargs)
.. py:function:: config_latex_compiler_scan()
.. py:function:: config_latex_compiler_get(verb=0)
.. py:function:: config_latex_compiler_set(new_latex_compiler_str)
.. py:function:: config_latex_compiler_testset(verb=1)
.. py:function:: 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.
.. py:class:: 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.
.. py:attribute:: latex_compiler_scan
.. py:attribute:: latex_compiler_get
.. py:attribute:: latex_compiler_set
.. py:attribute:: latex_compiler_test
.. py:attribute:: libreoffice_path_find
.. py:attribute:: libreoffice_path_get
.. py:attribute:: libreoffice_path_set
.. py:attribute:: pdf_engine_get
.. py:attribute:: pdf_engine_set
.. py:attribute:: pdf_engine_scan
.. py:attribute:: pdf_engine_test
.. py:attribute:: renderer_default_get
.. py:attribute:: renderer_default_set
.. py:attribute:: pandoc_allowed_set
.. py:attribute:: pandoc_allowed_get
.. py:attribute:: typst_installed
.. py:attribute:: get_info_on_optional_components
.. py:function:: pandoc_set_enabled()
short for pandoc_set_allowed(True), which will allow pandoc to be used as a valid conversion option
.. py:function:: pandoc_set_disabled()
short for pandoc_set_allowed(False), which will disallow pandoc to be used as a valid conversion option
.. py:function:: get_schema()
.. py:function:: get_example()
.. py:function:: load(path)
Load a JSON file and return a Doc object.
:param path: The path to the JSON file, a http(s) link, or a file-like object.
:type path: str or file-like object
:returns: A Doc object initialized with the loaded JSON data.
:rtype: Doc
:raises json.JSONDecodeError: If the JSON file is not valid.
:raises TypeError: If the loaded JSON object is not of type list.
.. py:function:: md2tex(children='', **kwargs)
convenience function to quickly convert markdown to tex
:param children: the markdown string to convert. Defaults to ''.
:type children: str, optional
:returns: the corresponding tex string
:rtype: str
.. py:function:: mk_chapter(title, description, parent=None, order=None)
Creates a new chapter.
:param title: The title of the chapter.
:type title: str
:param description: A brief description of the chapter.
:type description: str
:param parent: The parent chapter. Defaults to None.
:type parent: Chapter, optional
:param order: The order of the chapter. Defaults to None.
:type order: int, optional
:returns: The newly created chapter.
:rtype: Chapter
.. py:function:: mk_meta(project_name, version, description, author, author_email, url, license)
Generate metadata for the documentation.
:param project_name: The name of the project.
:type project_name: str
:param version: The version of the project.
:type version: str
:param description: A brief description of the project.
:type description: str
:param author: The author's name.
:type author: str
:param author_email: The author's email address.
:type author_email: str
:param url: The URL of the project.
:type url: str
:param license: The license of the project.
:type license: str
:returns: A dictionary containing the metadata.
:rtype: dict
.. py:function:: mk_tex(children=None, index=None, chapter=None, color='', end=None, **kwargs)
Creates a new LaTeX document part.
:param children: The "children" for this element. Either text directly (as string) or a list of other parts.
:type children: str or list, optional
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: Any color which can be rendered by HTML or LaTeX. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:param \*\*kwargs: Additional keyword arguments for the document part.
:returns: The newly created LaTeX document part.
:rtype: dict
.. py:function:: mk_md(children=None, index=None, chapter=None, color='', end=None, **kwargs)
Creates a new markdown document part.
:param children: The "children" for this element. Either text directly (as string) or a list of other parts.
:type children: str or list, optional
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: Any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:param \*\*kwargs: Additional keyword arguments for the document part.
:returns: The newly created markdown document part.
:rtype: dict
.. py:function:: mk_pre(children=None, index=None, chapter=None, color='', end=None, **kwargs)
Creates a preformatted document part.
:param children: The "children" for this element. Either text directly (as string) or a list of other parts.
:type children: str or list, optional
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: Any color which can be rendered by HTML or LaTeX. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:param \*\*kwargs: Additional keyword arguments for the document part.
:returns: The created document part.
:rtype: dict
.. py:function:: 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.
:param fig: the figure which to upload (or the current figure if None). Defaults to None.
:type fig: matplotlib figure, optional
:param caption: the caption to give to the image. Defaults to ''.
:type caption: str, optional
:param width: The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
:type width: float, optional
:param bbox_inches: will give better spacing for matplotlib figures.
:type bbox_inches: str, optional
:param children: A specific name/id to give to the image (will be auto generated if None). Defaults to None.
:type children: str, optional
:param index: The index where to insert the part. If None, appends to the end.
:type index: int, optional
:param chapter: The chapter name or index where to insert the part. If None, appends to the end.
:type chapter: str | int, optional
:param color: any color which can be rendered by html or latex. Empty string for default.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
:type end: str, optional
:returns: The created document part.
:rtype: dict
.. py:function:: 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
:param image: The image input, which can be a pyplot figure, a link, a file-like object, a numpy array, or a PIL image.
:param caption: The caption to give to the image. Defaults to ''.
:type caption: str, optional
:param width: The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
:type width: float, optional
:param children: A specific name/id to give to the image (will be auto-generated if None). Defaults to None.
:type children: str, optional
:param color: Any color which can be rendered by HTML or LaTeX. Empty string for default. Defaults to ''.
:type color: str, optional
:param end: If you want to insert a different line ending (than the default) for this element, set this argument to any string. None for default.
:type end: str, optional
:param \*\*kwargs: Additional keyword arguments to pass to the underlying method.
:returns: A dictionary representing the image with the specified attributes.
:rtype: dict