pydocmaker.core
===============
.. py:module:: pydocmaker.core
Attributes
----------
.. autoapisummary::
pydocmaker.core.np
pydocmaker.core.gImage
pydocmaker.core.chapter_level
pydocmaker.core._pdf_engine
pydocmaker.core._renderer_default
pydocmaker.core.log
pydocmaker.core.buildingblocks
Classes
-------
.. autoapisummary::
pydocmaker.core.constr
pydocmaker.core.Doc
Functions
---------
.. autoapisummary::
pydocmaker.core.config_renderer_default_set
pydocmaker.core.config_renderer_default_get
pydocmaker.core.config_pdf_engine_set
pydocmaker.core.config_pdf_engine_get
pydocmaker.core.config_pdf_engine_test
pydocmaker.core.config_pdf_engine_scan
pydocmaker.core.config_pdf_engine_testset
pydocmaker.core.is_notebook
pydocmaker.core.show_pdf
pydocmaker.core._is_chapter
pydocmaker.core.make_png_imageblob
pydocmaker.core._construct
pydocmaker.core.construct
pydocmaker.core.load
pydocmaker.core.print_to_pdf
Module Contents
---------------
.. py:data:: np
:value: None
.. py:data:: gImage
:value: None
.. py:data:: chapter_level
:value: 1
.. py:data:: _pdf_engine
:value: None
.. py:data:: _renderer_default
:value: 'auto'
.. py:data:: log
.. 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:: config_renderer_default_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_get()
.. 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_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_testset()
.. py:function:: is_notebook() -> bool
.. 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_chapter(dc)
.. py:function:: make_png_imageblob(im_bytes: str)
.. 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: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(v)
internal function
.. py:function:: construct(typ: str, **kwargs)
construct a document-part dict from the given typ and some kwargs
.. py:function:: load(doc: List[dict])
Loads a document from a list of dictionaries, a file path, or a stream-like object.
:param doc: The document data, file path, or stream-like object.
:type doc: List[dict] | str | BinaryIO | TextIO]
:returns: A Doc object representing the loaded document.
:rtype: Doc
:raises ValueError: If the document is not a list, file path, or stream-like object, or if the file or stream cannot be loaded.
.. 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.