pydocmaker.core
Attributes
Classes
This is the basic schema for the main building blocks for a document |
|
a collection of document parts to make a document (can be used like a list) |
Functions
|
Sets the PDF engine to be used for generating PDF documents. |
|
Sets the PDF engine to be used for generating PDF documents. |
|
tests the availability of the currently configured PDF engine. |
|
Configures the PDF engine and tests its availability. |
|
|
|
Display a PDF file within an IPython environment. |
|
|
|
|
|
internal function |
|
construct a document-part dict from the given typ and some kwargs |
|
Loads a document from a list of dictionaries, a file path, or a stream-like object. |
|
Prints a file to a PDF file using the appropriate platform-specific command using subprocess |
Module Contents
- pydocmaker.core.np = None
- pydocmaker.core.gImage = None
- pydocmaker.core.chapter_level = 1
- pydocmaker.core._pdf_engine = None
- pydocmaker.core._renderer_default = 'auto'
- pydocmaker.core.log
- pydocmaker.core.config_renderer_default_set(choice: str = 'auto')
Sets the PDF engine to be used for generating PDF documents.
Parameters: choice (str): The desired renderer for showing reports within python. Must be any of ‘auto’, ‘rich’, ‘md’, ‘html’, ‘pdf’.
Default is ‘auto’.
Returns: str: The selected renderer_default.
Raises: ValueError: If the provided choice is not one of the allowed options.
- pydocmaker.core.config_renderer_default_get()
- pydocmaker.core.config_pdf_engine_set(choice: str = 'typst')
Sets the PDF engine to be used for generating PDF documents.
Parameters: choice (str): The desired PDF engine. Must be one of ‘tex’, ‘word’, ‘libreoffice’, ‘typst’, or ‘pandoc’.
Default is ‘typst’.
Returns: str: The selected PDF engine.
Raises: ValueError: If the provided choice is not one of the allowed options.
- pydocmaker.core.config_pdf_engine_get()
- pydocmaker.core.config_pdf_engine_test(raise_on_error=True, force_reload=False)
tests the availability of the currently configured PDF engine.
- Parameters:
raise_on_error (bool) – If True, raises a ValueError if no valid compiler is found.
force_reload (bool) – If True, forces a reload of the PDF engine configuration.
- Returns:
True if a valid compiler is found, False otherwise.
- Return type:
bool
- pydocmaker.core.config_pdf_engine_scan(force_reload=False, firstonly=False)
Configures the PDF engine and tests its availability.
- Parameters:
raise_on_error (bool) – If True, raises a ValueError if no valid compiler is found.
force_reload (bool) – If True, forces a reload of the PDF engine configuration.
- Returns:
True if a valid compiler is found, False otherwise.
- Return type:
bool
- pydocmaker.core.config_pdf_engine_testset()
- pydocmaker.core.is_notebook() bool
- pydocmaker.core.show_pdf(pdf_bytes: bytes, width=1000, height=1200)
Display a PDF file within an IPython environment.
This function takes a PDF file in bytes or base64 encoded string format and displays it within an IPython notebook.
Parameters: pdf_bytes (bytes or str): The PDF file in bytes or base64 encoded string format. width (int, optional): The width of the IFrame in which the PDF is displayed. Default is 1000. height (int, optional): The height of the IFrame in which the PDF is displayed. Default is 1200.
Raises: AssertionError: If the function is not called within an IPython environment.
Example: >>> with open(‘example.pdf’, ‘rb’) as file: … pdf_bytes = file.read() >>> show_pdf(pdf_bytes)
- pydocmaker.core._is_chapter(dc)
- pydocmaker.core.make_png_imageblob(im_bytes: str)
- class pydocmaker.core.constr
This is the basic schema for the main building blocks for a document
- typalias
- static meta(children='', data=None, **kwargs)
- static markdown(children='', color='', end=None)
- static text(children='', color='', end=None)
- static line(children='', color='', end=None)
- static latex(children='', color='', end=None)
- static verbatim(children='', color='', end=None)
- static iter(children: list = None, color='', end=None)
- static table(children: list = None, color='', end=None, header=None, caption=None, n_cols=None, n_rows=None, borders=True)
- static image(imageblob='', caption='', children='', width=None, color='', end=None)
- static image_from_link(url, caption='', children='', width=None, color='', end=None)
- static image_from_file(path, children='', caption='', width=None, color='', end=None)
- image_from_fig(width=None, children=None, fig=None, color='', end=None, bbox_inches='tight', **kwargs)
convert a matplotlib figure (or the current figure) to a document image dict to later add to a document
- Parameters:
caption (str, optional) – the caption to give to the image. Defaults to ‘’.
width (float, optional) – The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
children (str, optional) – A specific name/id to give to the image (will be auto generated if None). Defaults to None.
fig (matplotlib figure, optional) – the figure which to upload (or the current figure if None). Defaults to None.
- Returns:
dict
- static image_from_obj(img, caption='', width=None, children=None, color='', end=None)
make a image type dict from given image of type matrix, filelike or PIL image
- Parameters:
im (np.array) – the image as NxMx
caption (str, optional) – the caption to give to the image. Defaults to ‘’.
width (float, optional) – The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
children (str, optional) – A specific name/id to give to the image (will be auto generated if None). Defaults to None.
- Returns:
dict with the results
- pydocmaker.core.buildingblocks
- class pydocmaker.core.Doc(initial_data=None)
Bases:
collections.UserLista collection of document parts to make a document (can be used like a list)
- DEFAULT_ADD_STRING_TYPE = 'markdown'
- EXPORT_ENGINES = ['md', 'html', 'typst', 'json', 'docx', 'textile', 'ipynb', 'tex', 'redmine', 'pdf']
- EXPORT_ENGINES_EXTENSIONS
- static load_json(path)
Load a JSON file and return a Doc object.
- Parameters:
path (str or file-like object) – The path to the JSON file or a file-like object.
- Returns:
A Doc object initialized with the loaded JSON data.
- Return type:
- Raises:
json.JSONDecodeError – If the JSON file is not valid.
TypeError – If the loaded JSON object is not of type list.
- __add__(b)
Add (join) two Docs into a single one and return a new instance.
This method combines two Doc objects into one. If b is a tuple or list containing a string and a default type, it uses the provided default type. If b is a string, it wraps it in a Doc object using the default type.
- __iadd__(b)
Add content to the current instance using the += operator.
Parameters: b (str, tuple, list, or object with a dump method): The content to add.
If b has a dump method, it will be called to get the content.
If b is a tuple or list of length 2 with both elements being strings,
the first element is used as the key and the second as the value. - If b is a string, it will be added with the default key.
Returns: self: The modified instance after adding the content.
- flatten()
Unpacks all iterator elements within this document and returns a new flat document.
- Returns:
A new document with all elements flattened.
- Return type:
- add_chapter(chapter_name: str, chapter_index=None, color='')
Adds a new chapter to the document.
- Parameters:
chapter_name (str) – The name of the new chapter.
chapter_index (int, optional) – The index after which chapter to insert the new chapter. If None, appends to the end.
- Raises:
AssertionError – If chapter_name is not a string or is empty.
- get_chapter(chapter) List[dict]
Retrieves a specific chapter from the document.
- Parameters:
chapter (str) – The name of the chapter to retrieve.
- Returns:
A list of dictionaries representing the content of the specified chapter.
- Return type:
List[dict]
- get_chapters(as_ranges=False) dict
Extracts chapters from the internal data and returns them as either dictionaries or ranges.
This method iterates through the internal data structure (represented by self.data) and identifies chapters based on a custom logic implemented in the _is_chapter function.
- Parameters:
as_ranges (bool, optional) – If True, returns chapters as dictionaries with keys as chapter names (obtained from the previous chapter) and values as ranges of indices (inclusive-exclusive) within the data list representing the chapter content. Defaults to False.
- Returns:
If as_ranges is False, returns a dictionary where keys are chapter names and values are corresponding chapter content extracted from the data list using the identified ranges. If as_ranges is True, returns a dictionary where keys are chapter names and values are ranges of indices (inclusive-exclusive) within the data list representing the chapter content.
- Return type:
dict or dict[str, range]
- get_template_from_meta(tformat='', template_dir=None, raise_on_error=False) pydocmaker.templating.DocTemplate
Gets the template from the metadata in this document if there is any defined.
- Parameters:
tformat (str, optional) – The format of the template either ‘tex’ or ‘html’. Defaults to ‘’.
template_dir (str, optional) – If this is given only this specific template dir is mounted to load templates from. Otherwise all registered templates are loaded
raise_on_error – (bool, optional): If this is False None will be returned in case of an error. Defaults to False.
- Returns:
The template object if a template_id is found in the metadata, otherwise None.
- Return type:
- set_template_to_meta(template_id: str, with_params=True, with_assets=True, test_found=True, on_exist='fail', template_params: dict = None) dict
Sets a template by a given template_id to the document metadata.
- Parameters:
template_id (str) – The ID of the template to set.
with_params (bool, optional) – Whether to include the (default) parameters from the template in the metadata. Defaults to True.
with_assets (bool, optional) – Whether to include the assets (files) from the template in the metadata. Defaults to True.
test_found (bool, optional) – Whether to test if the template exists before adding anything. Defaults to True.
on_exist (str, optional) – What to do if the parameters or assets from a template already exist in the metadata. Can be ‘fail’, ‘overwrite’, or ‘skip’. Defaults to ‘fail’.
template_params (dict, optional) – Additional parameters to add to the template. Defaults to None.
- Raises:
FileNotFoundError – If the template with the given ID does not exist.
AssertionError – If overwrite protection is enabled and the template would overwrite existing data.
ValueError – If an unknown value is passed for the on_exist parameter.
- Returns:
the meta elements data (content)
- Return type:
dict
- parse_filename_meta(doc_name, regex_pattern: str, fancy_title_analysis=True) dict
Parses the metadata from a document name using a regular expression pattern.
- Parameters:
doc_name (str) – The name of the document.
regex_pattern (str) – The regular expression pattern to use for parsing (can also give multiple as list or tuple).
fancy_title_analysis (bool, optional) – Will Analyse the title for “signed” in it and also resolve CamelCasing from it
- Returns:
A dictionary containing the parsed metadata.
- Return type:
dict
Example
>>> import pydocmaker as pyd >>> doc = pyd.Doc() >>> regex_pattern = r'(?P<title>\w+)-(?P<version>[a-zA-Z0-9]+)-(?P<state>\w+)' >>> doc_name = 'myfile-01-draft' >>> doc.parse_filename_meta(doc_name, regex_pattern) {'doc_name': 'myfile-01-draft', 'title': 'myfile', 'version': '01', 'state': 'draft'}
- set_meta(*args, **kwargs) dict
Sets the metadata for this document. Can be used in two ways: - By passing a dictionary: .set_meta({‘doc_name’: ‘test’}) - By passing keyword arguments: .set_meta(doc_name=’test’)
This method updates the existing metadata or creates new metadata if it doesn’t exist.
- Parameters:
*args – A single dictionary containing metadata.
**kwargs – Key-value pairs representing metadata.
- Returns:
The updated metadata.
- Return type:
dict
- get_meta(default=None) Dict | None
gets the (first) meta element in this document if it exists. If not returns None
- get_metadata() Dict | None
Equivalent to self.get_meta(default={}).get(‘data’, {}) Gets the data of the (first) meta element in this document if it exists. If not exists an new empty dict is returned
- has_meta() bool
tests if this document has one or more metadata objects
- update_meta(*args, **kwargs) Dict | None
Updates the metadata element in this document if it exists. If not, it will be added with the content provided. The content can be provided either as a dictionary or as keyword arguments.
Examples
.update_meta({‘doc_name’: ‘test’}) .update_meta(doc_name=’test’)
- Returns:
The updated metadata content.
- Return type:
dict
- add_meta(*args, **kwargs) dict
Adds a metadata element to this document. If the metadata already exists, it will be updated. The content can be provided either as a dictionary or as keyword arguments.
Examples
.add_meta({‘doc_name’: ‘test’}) .add_meta(doc_name=’test’)
- Returns:
The metadata element’s data (content).
- Return type:
dict
- add(part: dict = None, index=None, chapter=None, color='', end=None)
Appends a new document part to the given location or end of this document.
- Parameters:
part (dict) – The part to add. See the constr class for all possible parts.
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex (ONLY VALID FOR string INPUTS!). Empty string for default.
end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
- Raises:
ValueError – If the part is invalid, or if both index and chapter are specified.
AssertionError – If index is not an integer or is out of bounds.
- add_kw(typ, children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a document part to this document with a given typ
- Parameters:
typ (str, optional) – one of the allowed document part types. Either ‘markdown’, ‘verbatim’, ‘text’, ‘iter’ or ‘image’.
children (str or list) – the “children” for this element. Either text directly (as string) or a list of other parts
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex. Empty string for default.
end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
kwargs – the kwargs for such a document part
- add_text(children=None, index=None, chapter=None, color='', **kwargs)
add a raw text part to this document
- Parameters:
children (str or list) – the “children” for this element. Either text directly (as string) or a list of other parts
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex. Empty string for default.
kwargs – the kwargs for such a document part
- add_tex(children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a latex part to this document
- Parameters:
children (str or list) – the “children” for this element. Either text directly (as string) or a list of other parts
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex. Empty string for default.
kwargs – the kwargs for such a document part
- add_md(children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a markdown document part to this document
- Parameters:
children (str or list) – the “children” for this element. Either text directly (as string) or a list of other parts
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex. Empty string for default.
end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
kwargs – the kwargs for such a document part
- add_table(children=None, index=None, chapter=None, color='', end=None, header=None, caption='', n_rows=None, n_cols=None, borders=True, **kwargs)
add a table element to this document
- Parameters:
children (list of lists) – the “children” for this element. Must be a matrix (list of lists) with formatable elements in it.
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex. Empty string for default.
end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
header (list, optional) – The header row for the table. If given it must be a list with formatable elements in it.
caption (str, optional) – The caption to place at/under the table. Empty for no caption.
n_rows (int, optional) – The number of rows to give this table. If not given it will be determined from the number of rows in children.
n_cols (int, optional) – The number of columns to give this table. If not given it will be determined from the max number of columns in all rows in children.
borders (bool, optional) – Whether or not the table should have lines between its cells.
- add_pre(children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a verbaim (pre formatted) document part to this document
- Parameters:
children (str or list) – the “children” for this element. Either text directly (as string) or a list of other parts
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex. Empty string for default.
end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
kwargs – the kwargs for such a document part
- add_fig(fig=None, caption='', width=None, bbox_inches='tight', children=None, index=None, chapter=None, color='', end=None, **kwargs)
add a pyplot figure type dict from given image input.
- Parameters:
fig (matplotlib figure, optional) – the figure which to upload (or the current figure if None). Defaults to None.
caption (str, optional) – the caption to give to the image. Defaults to ‘’.
width (float, optional) – The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
bbox_inches (str, optional) – will give better spacing for matplotlib figures.
children (str, optional) – A specific name/id to give to the image (will be auto generated if None). Defaults to None.
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex. Empty string for default.
end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
- add_image(image, caption='', width=None, children=None, index=None, chapter=None, color='', end=None, **kwargs)
add an image type dict from given image input. image can be of type:
pyplot figure
link to download an image from
filelike
numpy NxMx1 or NxMx3 matrix
PIL image
- Parameters:
im (np.array) – the image as NxMx
caption (str, optional) – the caption to give to the image. Defaults to ‘’.
width (float, optional) – The width for the image to have in the document None will let the individual formatter determine the width. Defaults to None.
children (str, optional) – A specific name/id to give to the image (will be auto generated if None). Defaults to None.
index (int, optional) – The index where to insert the part. If None, appends to the end.
chapter (str | int, optional) – The chapter name or index where to insert the part. If None, appends to the end.
color (str, optional) – any color which can be rendered by html or latex. Empty string for default.
end (str, optional) – If you want to insert a different line ending (than the default) for this element set this argument to any string. None for default.
- dump() List[Dict]
dump this document to a basic list of dicts for document parts
- Returns:
the individual parts of the document
- Return type:
list
- _ret(m, path_or_stream)
internal method to return or write data
- to_json(path_or_stream=None) str
Converts the current object to a JSON file.
- Parameters:
path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.
- Returns:
The JSON data as string, or True if the data was saved successfully to a file or stream.
- Return type:
str
- to_markdown(path_or_stream=None, embed_images=True) str
Converts the current object to a Markdown string or writes it to a file.
- Parameters:
path_or_stream (str or io.IOBase, optional) – The path to save the Markdown file to, or a file-like object to write the data to. If not provided, the Markdown string will be returned.
embed_images (bool, optional) – Whether to embed images as base64 strings within the Markdown. Defaults to True.
- Returns:
The Markdown string if path_or_stream is not provided, or True if the Markdown was successfully written to the file or stream.
- Return type:
str or bool
- to_docx(path_or_stream=None, template: str = None, template_params=None, use_w32=False, as_pdf=False, compress_images=False, allow_pandoc=True) bytes
Converts the current object to a DOCX file, or a PDF file via DOCX (WARNING some options need win32com and word installed if selected).
- Parameters:
template (str, optional) – Path to a DOCX template file. Defaults to None.
template_params (dict, optional) – Parameters to replace fields in the template. Defaults to None.
use_w32 (bool, optional) – Whether to use win32com for document field updating and any of the following arguments, THIS OPTION NEEDS win32com and word installed. Defaults to False.
as_pdf (bool, optional) – Whether to output the document as a PDF (via docx and win32com). Defaults to False.
compress_images (bool, optional) – Whether to compress images in the document using win32com. Defaults to False.
allow_pandoc (bool, optional) – whether or not to allow the usage of pandoc instead of python-docx (usually pandoc creates nicer documents!)
- Returns:
The data as bytes, or True if the data was saved successfully to a file or stream.
- Return type:
bytes
- Raises:
ValueError – If attempting to export to PDF without win32com and Word.Application installed and use_w32 set to True.
- to_ipynb(path_or_stream=None) str
Converts the current object to an ipynb (iPython notebook) file.
- Parameters:
path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.
- Returns:
The data as string, or True if the data was saved successfully to a file or stream.
- Return type:
str
- to_html(path_or_stream=None, template=None, template_params=None) str
Converts the current object to a HTML file.
- Parameters:
path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.
template (str, optional) – A string containing the LaTeX code for the document template. Either a Jinja2 Latex template, or a string If not provided, a default template will be used.
template_params (dict, optional) – A dictionary containing the parameters for the document template which will be parsed to the “render” method of Jinja2
- Returns:
The data as string, or True if the data was saved successfully to a file or stream.
- Return type:
str
- to_typst(path_or_stream=None, template=None, template_params=None) str
Converts the current object to a Typst file.
- Parameters:
path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.
template (str, optional) – A string containing the LaTeX code for the document template. Either a Jinja2 Latex template, or a string If not provided, a default template will be used.
template_params (dict, optional) – A dictionary containing the parameters for the document template which will be parsed to the “render” method of Jinja2
- Returns:
The data as string, or True if the data was saved successfully to a file or stream.
- Return type:
str
- to_pdf(path_or_stream=None, docname='', files_to_upload=None, base_dir=None, engine=None, latex_compiler=None, n_times_make=None, verb=0, ignore_error=True, template=None, template_params=None, do_escape_template_params='auto', **kwargs) str | bytes | bool
Converts the current object to a PDF file or zipped latex project folder.
- Parameters:
path_or_stream (str or file-like object, optional) – The output destination. If it’s a string ending with ‘.pdf’, it will be written in pdf format to the given path. If it’s a string ending with ‘.zip’, the whole project folder used for making the pdf file will be zipped and saved under the given path. If it’s ‘zip’ or ‘pdf’, the data will be returned in the given format. If it’s None, the PDF data will be returned as a bytes object.
docname (str, optional) – The name of the output document. Defaults to a unix timestamp followed by ‘_mydocument’.
files_to_upload (optional) – A list of files to be uploaded with the document.
base_dir (str, optional) – The directory to use as the base directory for the temporary directory. Defaults to the system’s default temporary directory.
engine (str, optional) – the pdf engine to use (either “typst”, “tex”, “word”, or “libreoffice”). If None, the currently configured engine will be queried via config_pdf_engine_get().
latex_compiler (str, optional) – Only used if engine resolves to “tex”. The LaTeX compiler to use. Either ‘pdflatex’, ‘lualatex’, ‘xelatex’, or ‘pandoc’. If not specified, the function will try to use ‘pandoc’, ‘pdflatex’, ‘lualatex’, or ‘xelatex’ in that order.
n_times_make (int, optional) – Only used if engine resolves to “tex”. The number of times to run the LaTeX compiler. Defaults to 1 for pandoc and 3 for all others.
verb (int, optional) – The verbosity level (0, 1, 2). If greater than 0, the function will print more and more debug information. Defaults to 0.
ignore_error (bool, optional) – Whether to ignore errors during the LaTeX compilation. Defaults to True.
template (str, optional) – A string containing the LaTeX code for the document template. Either a Jinja2 Latex template, or a string If not provided, a default template will be used.
template_params (dict, optional) – A dictionary containing the parameters for the document template which will be parsed to the “render” method of Jinja2
do_escape_template_params (bool, optional) – Only valid for Latex templates. Whether to escape the template parameters. “auto” will scan for %%latex at the start of a string to determine if its a latex string. Defaults to ‘auto’.
- Returns:
Either the data as string, or bytes depending on if its binary. Or True|False to indicate if the data was saved successfully to a file or stream.
- Return type:
str
- Raises:
Warning – If the provided file path does not end with ‘.zip’ or ‘.pdf’, a warning is issued and the file is assumed to be in PDF format.
- to_tex(path_or_stream=None, additional_files=None, template=None, do_escape_template_params='auto', template_params=None, text_only=False)
Converts the current object to a TEX file (and attachments).
- Parameters:
path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as a string.
(dict[str (additional_files) – bytes], optional): Any additional files you want to upload to the tex document, such as an image as a logo in the header.
template (str, optional) – The LaTeX template to use.
do_escape_template_params (bool, optional) – Whether to escape the template parameters. “auto” will scan for %%latex at the start of a string to determine if its a latex string. Defaults to ‘auto’.
template_params (dict, optional) – Additional parameters to pass to the LaTeX template.
text_only (bool, optional) – Only valid if path_or_stream is None. Whether or not to return attachments as well. Defaults to False
- Returns:
True if the data was saved successfully to a file or stream. If returning:
str: The tex file as a string. dict: The additional input files needed for LaTeX (bytes) as values and their relative paths (str) as keys.
- Return type:
If saving to a file or stream
- to_textile(path_or_stream=None, text_only=False)
Converts the current object to a TEXTILE file (and attachments). If path_or_stream is given it will zip all contents and write it to the stream or file path given. If not it will return a tuple with textile (str), files (dict[str, bytes])
- Parameters:
path_or_stream (str or io.IOBase, optional) – The path to save the file to, or a file-like object to write the data to. If not provided, the data will be returned as string.
text_only (bool, optional) – Only valid if path_or_stream is None. Whether or not to return attachments as well. Defaults to False
- Returns:
True if the data was saved successfully to a file or stream. If returning:
str: The tex file as a string. dict: The additional input files needed for LaTeX (bytes) as values and their relative paths (str) as keys.
- Return type:
If saving to a file or stream
- to_redmine() Tuple[str, list]
Converts the current object to a Redmine Textile like text (and attachments) and returns them as tuple.
- to_redmine_upload(redmine, project_id: str, report_name=None, page_title=None, force_overwrite=False, verb=True)
Converts the current object to a Redmine Textile like text (and attachments) and Uploads it to a Redmine wiki page. This will also export the document to all possible formats and attach them to the wiki page.
- Parameters:
redmine (redminelib.Redmine) – A Redmine connection object.
project_id (str) – The ID of the Redmine project where the report should be uploaded.
report_name (str, optional) – The name of the report. If not provided, the follwoing schema %Y%m%d_%H%M_exported_report will be used.
page_title (str, optional) – The title of the Redmine wiki page. If not provided, it will be derived from the report name.
force_overwrite (bool, optional) – Whether to overwrite an existing page with the same title. Defaults to False.
verb (bool, optional) – Whether to print verbose output during upload. Defaults to True.
- Returns:
The uploaded Redmine wiki page object.
- Return type:
redminelib.WikiPage
- Raises:
AssertionError – If any of the doc, project_id or redmine arguments is None or empty.
- print_rich(path_or_stream=None, title=None, embed_images=True)
Parses the current object using python rich library and output it either on console or to any file / stream.
- Parameters:
path_or_stream – Either a file path (str) to write to, a file-like object with a write method, or None to output to stdout
title – Optional title for the documentation. If not provided, will attempt to extract from metadata using common title keys. If still None a default title will be used.
embed_images – if True this will make the images appear as simplified pixelized pictures on the console, if False it will insert a placeholder instead.
- Returns:
Only in path_or_stream is not None. True if successful, False otherwise
- Return type:
bool
Example
>>> doc.print_rich("output.rich") >>> doc.print_rich(sys.stdout) >>> doc.print_rich()
- to_pdf_print(path_or_stream=None)
Exports the document to a PDF file by using the systems “print to pdf” function to export from html to pdf.
WARNING: This function only works on posix like operating systems and requires a PDF printer to be installed and set as default printer. It will not work on windows or macos since they do not have a command line interface for printing to PDF. Use with caution and make sure to test it on your system before using it in production!
WARNING II: The resulting PDF file will not be of the same quality as a PDF file generated by a proper PDF engine like pdflatex, typst, or word. It is recommended to use this function only as a last resort if no other PDF engine is available and you need a quick and dirty PDF file.
- Parameters:
output_pdf_path (str, optional) – The path to save the PDF file to. If not provided, a temporary file will be used.
- Returns:
True if the data was saved successfully to a file or stream. If returning:
str: The PDF file as bytes.
- Return type:
If saving to a file or stream
- export_all(dir_path=None, report_name='exported_report', **kwargs)
Exports the document to all possible formats.
- Parameters:
dir_path (str, optional) – The path to the directory where the exported files should be saved. If not provided, a dict with the returned data from the exporters will be returned.
report (str, optional) – The base name for the exported files. Defaults to “exported_report”.
**kwargs – Additional keyword arguments specific to the chosen export formats.
- Returns:
A dictionary containing the exported data or paths for each engine.
- Return type:
dict
- export_many(engines: List[str] = None, dir_path=None, report_name='exported_report', **kwargs)
Exports the document to multiple formats.
- Parameters:
engines (list[str], optional) – A list of export engines to use. If not provided, all supported engines will be used.
dir_path (str, optional) – The path to the directory where the exported files should be saved. If not provided, a dict with the returned data from the exporters will be returned.
report (str, optional) – The base name for the exported files. Defaults to “exported_report”.
**kwargs – Additional keyword arguments specific to the chosen export formats.
- Returns:
A dictionary containing the exported data or paths for each engine.
- Return type:
dict
- export(engine: str, path_or_stream=None, **kwargs)
Exports the document to a specified format.
- Parameters:
engine (str) – The format to export to. Valid options are: ‘md’, ‘markdown’, ‘json’, ‘html’, ‘tex’, ‘latex’, ‘textile’, ‘word’, ‘docx’, and ‘redmine’.
path_or_stream (str or io.IOBase, optional) – The path to save the exported file to, or a file-like object to write the data to.
**kwargs – Additional keyword arguments specific to the chosen export format.
- Returns:
The exported data or True if the data was successfully written to a file or stream.
- Return type:
str or bool
- Raises:
KeyError – If the specified engine is not supported.
- upload(url, doc_name='', force_overwrite=False, page_title='', requests_kwargs=None, raise_on_fail=True, warn_on_fail=True)
- Uploads the document data to a specified URL using HTTP(s) and requests.
The json body is constructed as:
- upload = {
“doc_name”: doc_name, “doc”: self.dump(), “force_overwrite”: force_overwrite, “page_title”: page_title
}
- Parameters:
url (str) – The URL of the endpoint that accepts the document data.
doc_name (str, optional) – The name of the uploaded document. Defaults to ‘’.
force_overwrite (bool, optional) – Whether to overwrite an existing document. Defaults to False.
page_title (str, optional) – The title of the uploaded document (if applicable). Defaults to ‘’.
requests_kwargs – (dict, optional) with kwargs for requests.post(). Defaults to None.
raise_on_fail – (bool, optional): set True to raise an exception on failed upload. Defaults to True.
warn_on_fail – (bool, optional): set True to prompt some warning text with the feedback from server on a fail. Defaults to True.
- Returns:
The JSON response from the server after uploading the document.
- Return type:
dict
- Raises:
requests.exceptions.RequestException – If the upload request fails.
- show(engine=None, index=None, chapter=None, files_to_upload=None, template=None, template_params=None, do_escape_template_params=False, embed_images=True, **kwargs)
Displays the document or a specific part of it in ipython display or via print
- Parameters:
engine (str, optional) – The engine to use for displaying. None to decide based on the currently available console. Else either “html”, “markdown”, “md”, “tex”, “latex”, or “pdf” (pdf only works in Ipython!)
index (int, optional) – The index of the part to display.
chapter (str, optional) – The name of the chapter to display.
files_to_upload (dict, optional) – ONLY VALID WHEN engine=’pdf’. See to_pdf method for details. Defaults to None.
template (jinja2 template or string, optional) – ONLY VALID WHEN engine=’pdf’. See to_pdf method for details. Defaults to None.
template_params (dict, optional) – ONLY VALID WHEN engine=’pdf’. See to_pdf method for details. Defaults to None.
do_escape_template_params (bool, optional) – ONLY VALID WHEN engine=’pdf’. See to_pdf method for details. Defaults to False.
embed_images (bool, optional) – ONLY VALID WHEN engine=’md’ or ‘rich’. Whether to embed (show) images within the document, or placeholders. Defaults to True.
- Raises:
KeyError – if the specified engine is not found or not valid
AssertionError – If both index and chapter are specified.
- __repr__(*args, **kwargs)
- __str__(*args, **kwargs)
- classmethod get_example()
- pydocmaker.core._construct(v)
internal function
- pydocmaker.core.construct(typ: str, **kwargs)
construct a document-part dict from the given typ and some kwargs
- pydocmaker.core.load(doc: List[dict])
Loads a document from a list of dictionaries, a file path, or a stream-like object.
- Parameters:
doc (List[dict] | str | BinaryIO | TextIO]) – The document data, file path, or stream-like object.
- Returns:
A Doc object representing the loaded document.
- Return type:
- Raises:
ValueError – If the document is not a list, file path, or stream-like object, or if the file or stream cannot be loaded.
- pydocmaker.core.print_to_pdf(file_path, output_pdf_path)
Prints a file to a PDF file using the appropriate platform-specific command using subprocess
WARNING: This function only works on posix like operating systems and requires a PDF printer to be installed and set as default printer. It will not work on windows or macos since they do not have a command line interface for printing to PDF. Use with caution and make sure to test it on your system before using it in production!
WARNING II: The resulting PDF file will not be of the same quality as a PDF file generated by a proper PDF engine like pdflatex, typst, or word. It is recommended to use this function only as a last resort if no other PDF engine is available and you need a quick and dirty PDF file.
- Parameters:
file_path (str) – The path to the file to print.
output_pdf_path (str) – The path to the output PDF file.
- Raises:
ValueError – If the platform is not supported.