all2md.api
The major exported API functions for document conversion.
- all2md.api.to_markdown(source: str | Path | IO[bytes] | bytes | Document, *, parser_options: BaseParserOptions | None = None, renderer_options: MarkdownRendererOptions | None = None, options: BaseParserOptions | None = None, source_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'auto', flavor: str | None = None, transforms: list | None = None, hooks: dict | None = None, progress_callback: Callable[[ProgressEvent], None] | None = None, remote_input_options: RemoteInputOptions | None = None, **kwargs: Any) str
Convert document to Markdown format with enhanced format detection.
This is the main entry point for the all2md library. It can detect file formats from filenames, content analysis, or explicit format specification, then routes to the appropriate specialized converter for processing.
- Parameters:
source (str, Path, IO[bytes|str], bytes, or Document) – Source document data, which can be a file path, a file-like object, raw bytes, or an AST Document object (for cases where you already have a parsed AST).
parser_options (BaseParserOptions, optional) – Pre-configured parser options for format-specific parsing settings (e.g., PdfOptions, DocxOptions, HtmlOptions).
renderer_options (BaseRendererOptions, optional) – Pre-configured renderer options for Markdown rendering settings (e.g., MarkdownOptions).
options (BaseParserOptions, optional) –
Deprecated since version Use:
parser_optionsinstead.Deprecated alias for
parser_options. Cannot be used together withparser_options.source_format (DocumentFormat, default "auto") – Explicitly specify the source document format. If “auto”, the format is detected from the filename or content.
flavor (str, optional) – Markdown flavor/dialect to use for output. Options: “gfm”, “commonmark”, “multimarkdown”, “pandoc”, “kramdown”, “markdown_plus”. Shorthand for renderer_options=MarkdownOptions(flavor=…).
transforms (list, optional) – List of AST transforms to apply before rendering. Can be transform names (strings) or NodeTransformer instances. Transforms are applied in order. See all2md.transforms for available transforms.
hooks (dict, optional) – Transform hooks to execute during processing. Maps hook names to callable functions that execute at specific points in the transform pipeline.
progress_callback (ProgressCallback, optional) – Optional callback function for progress updates. Receives ProgressEvent objects with event_type, message, current/total counts, and metadata. See all2md.progress for details.
remote_input_options (RemoteInputOptions, optional) – Controls remote retrieval behaviour (network allowlists, size limits, etc.). Defaults to None, which disables remote fetching.
kwargs (Any) – Individual conversion options. Kwargs are intelligently split between parser and renderer based on field names. Parser-related kwargs override fields in parser_options, renderer-related kwargs override fields in renderer_options.
- Returns:
Document content converted to Markdown format.
- Return type:
str
- Raises:
DependencyError – If required dependencies for a specific format are not installed.
ParsingError – If file processing fails due to corruption or format issues.
Examples
- Basic conversion:
>>> markdown = to_markdown("document.pdf")
- With parser options:
>>> pdf_opts = PdfOptions(pages=[0, 1, 2], attachment_mode="save") >>> markdown = to_markdown("document.pdf", parser_options=pdf_opts)
- With renderer options:
>>> md_opts = MarkdownRendererOptions(emphasis_symbol="_", flavor="commonmark") >>> markdown = to_markdown("document.pdf", renderer_options=md_opts)
- Using both parser and renderer options:
>>> markdown = to_markdown("doc.pdf", ... parser_options=PdfOptions(pages=[0, 1]), ... renderer_options=MarkdownRendererOptions(flavor="gfm"))
- Using kwargs (automatically split):
>>> markdown = to_markdown("doc.pdf", pages=[0, 1], emphasis_symbol="_")
- Using flavor shorthand:
>>> markdown = to_markdown("document.pdf", flavor="commonmark")
- With transforms:
>>> markdown = to_markdown("doc.pdf", transforms=["remove-images"])
- From AST Document:
>>> ast_doc = to_ast("document.pdf") >>> # Apply custom processing to ast_doc... >>> markdown = to_markdown(ast_doc)
- all2md.api.to_ast(source: str | Path | IO[bytes] | bytes, *, parser_options: BaseParserOptions | None = None, source_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'auto', progress_callback: Callable[[ProgressEvent], None] | None = None, remote_input_options: RemoteInputOptions | None = None, **kwargs: Any) Document
Convert document to AST (Abstract Syntax Tree) format.
This function provides advanced users with direct access to the document AST, enabling custom processing, transformation, and analysis of document structure. The AST can be manipulated using utilities from all2md.ast.transforms and serialized to JSON using all2md.ast.serialization.
- Parameters:
source (str, Path, IO[bytes], or bytes) – Source document data, which can be a file path, a file-like object, or raw bytes.
parser_options (BaseParserOptions, optional) – Pre-configured parser options for format-specific parsing settings (e.g., PdfOptions, DocxOptions, HtmlOptions).
source_format (DocumentFormat, default "auto") – Explicitly specify the source document format. If “auto”, the format is detected from the filename or content.
progress_callback (ProgressCallback, optional) – Optional callback function for progress updates. Receives ProgressEvent objects with event_type, message, current/total counts, and metadata. See all2md.progress for details.
remote_input_options (RemoteInputOptions, optional) – Controls remote retrieval behaviour for the source input. Defaults to None (remote fetching disabled).
kwargs (Any) – Individual parser options that override settings in parser_options.
- Returns:
AST Document node representing the document structure
- Return type:
- Raises:
FormatError – If the format cannot be detected or is unsupported
DependencyError – If required dependencies for the format are not installed
ParsingError – If conversion fails
Examples
- Get AST from a document:
>>> from all2md import to_ast >>> ast_doc = to_ast("document.pdf")
- Manipulate AST and convert to markdown:
>>> from all2md.ast import transforms >>> from all2md.renderers.markdown import MarkdownRenderer >>> ast_doc = to_ast("document.pdf") >>> filtered_doc = transforms.filter_nodes(ast_doc, lambda n: not isinstance(n, Image)) >>> renderer = MarkdownRenderer() >>> markdown = renderer.render_to_string(filtered_doc)
- Extract specific nodes:
>>> from all2md.ast import transforms, Heading >>> ast_doc = to_ast("document.docx") >>> headings = transforms.extract_nodes(ast_doc, Heading)
- Serialize to JSON:
>>> from all2md.ast import serialization >>> ast_doc = to_ast("document.html") >>> json_str = serialization.ast_to_json(ast_doc, indent=2)
- all2md.api.chunk(source: str | Path | IO[bytes] | bytes, *, strategy: str = 'semantic', max_tokens: int = 512, overlap: int = 0, min_tokens: int = 0, include_preamble: bool = True, heading_merge: bool = True, max_heading_level: int | None = None, avoid_table_split: bool = False, avoid_code_split: bool = False, elide_data_uris: bool = True, drop_elements: list[str] | None = None, token_counter: str = 'auto', document_id: str | None = None, source_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'auto', **converter_options: Any) list[ProvenanceChunk]
Convert a document and split it into provenance-carrying chunks in one call.
The one-call equivalent of
to_ast+all2md.chunking.chunk_ast: convertsource(a path, bytes, or file-like object) to an AST, optionally strip node types, and return chunks each carrying its section heading/level and — where the source format records it — the originating page span. Ideal for RAG / LLM pipelines.- Parameters:
source (str, Path, IO[bytes], or bytes) – Document to chunk (any supported format).
strategy (str) – Chunking strategy; see
all2md.chunking.STRATEGIES(semanticdefault).max_tokens (int) – Size controls — token budget per chunk, window overlap, and a floor below which chunks are dropped.
overlap (int) – Size controls — token budget per chunk, window overlap, and a floor below which chunks are dropped.
min_tokens (int) – Size controls — token budget per chunk, window overlap, and a floor below which chunks are dropped.
include_preamble (bool) – Structure toggles (emit pre-heading content; prepend each heading to its section’s chunks).
heading_merge (bool) – Structure toggles (emit pre-heading content; prepend each heading to its section’s chunks).
max_heading_level (int, optional) – For fine strategies, only descend into sections at or above this level.
avoid_table_split (bool) – Keep tables / fenced code blocks whole (one atomic chunk each).
avoid_code_split (bool) – Keep tables / fenced code blocks whole (one atomic chunk each).
elide_data_uris (bool) – Replace long base64
data:URIs with a short placeholder (default True).drop_elements (list of str, optional) – AST node types to strip before chunking (e.g.
["image", "table"]).token_counter ({"auto", "tiktoken", "whitespace"}) – Token-counting backend.
document_id (str, optional) – Identifier woven into chunk ids; defaults to the file stem (or
"document").source_format (DocumentFormat, default "auto") – Explicit source format, or auto-detect.
converter_options (Any) – Extra options forwarded to
to_ast()(e.g.attachment_mode="skip",pages=[1, 2]).
- Returns:
Chunks in reading order, with
prev/nextids linked. Callchunk.to_dict()for a JSON-serializable record.- Return type:
list of ProvenanceChunk
Examples
>>> import all2md >>> chunks = all2md.chunk("report.pdf", strategy="semantic", max_tokens=512, overlap=64) >>> chunks[0].section_heading, chunks[0].page, chunks[0].token_count
- all2md.api.confidence_report(source: str | Path | IO[bytes] | bytes | Document, *, parser_options: BaseParserOptions | None = None, source_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'auto', progress_callback: Callable[[ProgressEvent], None] | None = None, remote_input_options: RemoteInputOptions | None = None, **kwargs: Any) ConfidenceReport
Convert a document and return its conversion confidence report (“quality card”).
A reference-free read on how much to trust a conversion, built from the sanity signals converters already compute (meaningful-text density, OCR reliance, rejected tables, dropped images) plus discrete degraded-content incidents. The single
0-100scoredoubles as an optimizer fitness function.- Parameters:
source (str, Path, IO[bytes], bytes, or Document) – Document to inspect. A pre-parsed
Documentis read directly (its report was attached when it was first parsed viato_ast()).parser_options (BaseParserOptions, optional) – Pre-configured parser options.
source_format (DocumentFormat, default "auto") – Explicit source format, or auto-detect.
progress_callback (ProgressCallback, optional) – Optional progress callback forwarded to parsing.
remote_input_options (RemoteInputOptions, optional) – Controls remote retrieval behaviour. Defaults to None (disabled).
kwargs (Any) – Individual parser options forwarded to
to_ast().
- Returns:
The scored quality card. Formats that produce no scored signals and record no degraded events yield a
scoreof 100 banded"not_assessed"– the converter ran no quality checks, so the 100 is not a clean bill of health.- Return type:
ConfidenceReport
Examples
>>> from all2md import confidence_report >>> report = confidence_report("scan.pdf") >>> report.score, report.band (72, 'medium')
- all2md.api.roundtrippable_formats() list[str]
Return the formats that can be both rendered to and parsed back from.
These are the formats accepted by
roundtrip_report()’sviaparameter: a round trip needs a renderer to get there and a parser to get back.
- all2md.api.roundtrip_report(source: str | Path | IO[bytes] | bytes | Document, *, via: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'markdown', source_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'auto', parser_options: BaseParserOptions | None = None, renderer_options: BaseRendererOptions | None = None, progress_callback: Callable[[ProgressEvent], None] | None = None, remote_input_options: RemoteInputOptions | None = None, **kwargs: Any) RoundTripReport
Round-trip a document through
viaand score what survived.Renders the parsed document to the
viaformat, parses the result straight back, and compares the two ASTs structurally. Unlikeconfidence_report(), this has a ground truth to measure against – the source AST – so a clean document round-tripping through a lossless format scores exactly100and any drift is a real defect.- Parameters:
source (str, Path, IO[bytes], bytes, or Document) – Document to round-trip. A pre-parsed
Documentis used directly as the ground truth, in which casesource_formatis only a label.via (DocumentFormat, default "markdown") – Intermediate format to round-trip through. Must have both a renderer and a parser – see
roundtrippable_formats().source_format (DocumentFormat, default "auto") – Explicit source format, or auto-detect.
parser_options (BaseParserOptions, optional) – Options for parsing the source. The intermediate is always parsed with that format’s defaults, since it is machine-generated.
renderer_options (BaseRendererOptions, optional) – Options for rendering to
via.progress_callback (ProgressCallback, optional) – Optional progress callback forwarded to the initial parse.
remote_input_options (RemoteInputOptions, optional) – Controls remote retrieval behaviour. Defaults to None (disabled).
kwargs (Any) – Individual options, split between the source parser and the
viarenderer.
- Returns:
The
0-100fidelity score, per-dimension metrics, and the concrete structural differences found.- Return type:
RoundTripReport
- Raises:
FormatError – If
viacannot be both rendered to and parsed back from.
Examples
>>> from all2md import roundtrip_report >>> report = roundtrip_report("report.docx") >>> report.score, report.metrics["structure"] (94, 91)
- Check what a conversion to reStructuredText would cost:
>>> report = roundtrip_report("notes.md", via="rst")
- all2md.api.optimizable_formats() list[str]
Return the formats
optimize_options()knows how to tune.
- all2md.api.optimize_options(source: str | Path | IO[bytes] | bytes, *, source_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'auto', parser_options: BaseParserOptions | None = None, rounds: int = 1, include_presets: bool = True, sample_pages: int | None = None, remote_input_options: RemoteInputOptions | None = None) OptimizationReport
Search converter options for the settings that convert
sourcebest.Converts the document many times under different settings and ranks them by a reference-free fidelity objective (see
all2md.optimize), so this works on the documents that need it most: the ones with no known-good output to compare against. Returns the winning options as a diff from the defaults, ready to drop into an.all2md.toml.This is not cheap — it is tens of conversions. Use
sample_pagesto tune on a slice of a long document, and enable the conversion cache (all2md.conversion_cache.use_conversion_cache()) to skip re-converting option sets already tried.- Parameters:
source (str or Path or file-like or bytes) – The document to tune against.
source_format (str, default "auto") – Override format detection.
parser_options (BaseParserOptions, optional) – Starting point for the search. Options outside the searched knobs are held fixed at whatever this specifies, so it doubles as a way to pin settings the optimizer must not touch.
rounds (int, default 1) – Coordinate-descent passes over the knobs. More rounds can recover knobs that only pay off in combination, at proportionally more conversions.
include_presets (bool, default True) – Score the named presets (
quality,complete, …) before refining.sample_pages (int, optional) – Tune against only the first N pages, so a 400-page document does not have to be reconverted in full for every candidate. Paginated formats only. Use at least 2 (ideally 3+): running headers and footers are recognized by the fact that they repeat, so a single-page sample cannot see them at all.
remote_input_options (RemoteInputOptions, optional) – Controls retrieval when
sourceis a URL.
- Returns:
The winning options, the fitness they scored, what the defaults scored, and every candidate evaluated.
- Return type:
OptimizationReport
- Raises:
FormatError – If the detected format has no tunable knobs.
Examples
>>> from all2md import optimize_options >>> report = optimize_options("scanned.pdf") >>> report.best_options {'table_detection_mode': 'ruling', 'detect_columns': True}
- all2md.api.from_ast(ast_doc: Document, target_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'], output: str | Path | IO[bytes] | IO[str] | None = None, *, renderer_options: BaseRendererOptions | None = None, transforms: list | None = None, hooks: dict | None = None, progress_callback: Callable[[ProgressEvent], None] | None = None, preserve_formatting: bool = False, **kwargs: Any) None | str | bytes
Render AST document to a target format.
- Parameters:
ast_doc (Document) – AST Document node to render
target_format (DocumentFormat) – Target format name (e.g., “markdown”, “docx”, “pdf”)
output (str, Path, IO[bytes], IO[str], or None, optional) – Output destination. If None, returns rendered content directly. Can be: - None: Returns str (for text formats) or bytes (for binary formats) - str or Path: Writes content to file at that path - IO[bytes]: Writes content to binary file-like object - IO[str]: Writes content to text file-like object
renderer_options (BaseRendererOptions, optional) – Renderer options for the target format
transforms (list, optional) – AST transforms to apply before rendering
hooks (dict, optional) – Transform hooks to execute during processing
progress_callback (ProgressCallback, optional) – Optional callback function for progress updates. Receives ProgressEvent objects with event_type, message, current/total counts, and metadata. See all2md.progress for details.
preserve_formatting (bool, default False) – When True and
target_formatis"docx", use the AST’s stashedsource_path(populated byto_astfor file-based inputs) as the rendering template and clear its body before rendering. This preserves page setup, theme, headers/footers, and custom style definitions from the original document on a docx round-trip. Ignored if no source path is stashed or the caller already specified atemplate_path.kwargs (Any) – Additional renderer options that override renderer_options
- Returns:
None if output was specified (content written to output)
str if output=None and format is text-based (markdown, html, rst, etc.)
bytes if output=None and format is binary (docx, pdf, epub, etc.)
- Return type:
None, str, or bytes
Notes
If you need a file-like object instead of direct content, pass a StringIO or BytesIO instance to the output parameter:
>>> from io import StringIO, BytesIO >>> buffer = StringIO() >>> from_ast(doc, "markdown", output=buffer) # Returns None, buffer populated >>> markdown_text = buffer.getvalue()
Examples
- Render AST to string (text formats):
>>> ast_doc = to_ast("document.pdf") >>> markdown_text = from_ast(ast_doc, "markdown") >>> isinstance(markdown_text, str) True
- Render AST to bytes (binary formats):
>>> pdf_bytes = from_ast(ast_doc, "pdf") >>> isinstance(pdf_bytes, bytes) True
- Render AST to file:
>>> from_ast(ast_doc, "markdown", output="output.md")
- With renderer options:
>>> md_opts = MarkdownRendererOptions(flavor="commonmark") >>> markdown_text = from_ast(ast_doc, "markdown", renderer_options=md_opts)
- all2md.api.from_markdown(source: str | Path | IO[bytes] | IO[str], target_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'], output: str | Path | IO[bytes] | IO[str] | None = None, *, parser_options: MarkdownParserOptions | None = None, renderer_options: BaseRendererOptions | None = None, transforms: list | None = None, hooks: dict | None = None, progress_callback: Callable[[ProgressEvent], None] | None = None, preserve_formatting: bool = False, **kwargs: Any) None | str | bytes
Convert Markdown content to another format.
- Parameters:
source (str, Path, IO[bytes], or IO[str]) – Markdown source content as string, file path, or file-like object
target_format (DocumentFormat) – Target format name (e.g., “docx”, “pdf”, “html”)
output (str, Path, IO[bytes], IO[str], or None, optional) – Output destination. If None, returns rendered content. Can be: - None: Returns str (for text formats) or bytes (for binary formats) - str or Path: Writes content to file at that path - IO[bytes]: Writes content to binary file-like object - IO[str]: Writes content to text file-like object
parser_options (MarkdownParserOptions, optional) – Options for parsing Markdown
renderer_options (BaseRendererOptions, optional) – Options for rendering to target format
transforms (list, optional) – AST transforms to apply
hooks (dict, optional) – Transform hooks to execute
progress_callback (ProgressCallback, optional) – Optional callback function for progress updates. Receives ProgressEvent objects with event_type, message, current/total counts, and metadata. See all2md.progress for details.
preserve_formatting (bool, default False) – When True and
target_formatis"docx", use the AST’s stashedsource_pathas a rendering template and clear its body. Only useful when the markdown source was originally derived from a docx file whose path is still available; in that case passtemplate_pathexplicitly instead. Seefrom_astfor details.kwargs (Any) – Additional options split between parser and renderer
- Returns:
None if output was specified (content written to output)
str if output=None and format is text-based (html, rst, etc.)
bytes if output=None and format is binary (docx, pdf, epub, etc.)
- Return type:
None, str, or bytes
Notes
If you need a file-like object instead of direct content, pass a StringIO or BytesIO instance to the output parameter:
>>> from io import StringIO, BytesIO >>> buffer = StringIO() >>> from_markdown("# Title", "html", output=buffer) # Returns None >>> html_text = buffer.getvalue()
Examples
- Convert markdown string to HTML:
>>> html_text = from_markdown("# Title\\n\\nContent", "html") >>> isinstance(html_text, str) True
- Convert markdown to binary format:
>>> pdf_bytes = from_markdown("# Title", "pdf") >>> isinstance(pdf_bytes, bytes) True
- Convert markdown file to DOCX file:
>>> from_markdown("input.md", "docx", output="output.docx")
- With options:
>>> html_content = from_markdown("input.md", "html", ... parser_options=MarkdownParserOptions(flavor="gfm"), ... renderer_options=HtmlOptions(...))
- all2md.api.convert(source: str | Path | IO[bytes] | IO[str] | bytes, output: str | Path | IO[bytes] | IO[str] | None = None, *, parser_options: BaseParserOptions | None = None, renderer_options: BaseRendererOptions | None = None, source_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'auto', target_format: Literal['auto', 'archive', 'asciidoc', 'ast', 'bbcode', 'chm', 'csv', 'docx', 'dokuwiki', 'eml', 'enex', 'epub', 'fb2', 'html', 'ini', 'ipynb', 'jinja', 'json', 'latex', 'markdown', 'mbox', 'mediawiki', 'mhtml', 'odp', 'ods', 'odt', 'openapi', 'org', 'outlook', 'pdf', 'plaintext', 'pptx', 'rst', 'rtf', 'sourcecode', 'textile', 'toml', 'webarchive', 'xlsx', 'yaml', 'zip'] = 'auto', transforms: list | None = None, hooks: dict | None = None, renderer: str | type | object | None = None, flavor: str | None = None, progress_callback: Callable[[ProgressEvent], None] | None = None, remote_input_options: RemoteInputOptions | None = None, preserve_formatting: bool = False, **kwargs: Any) None | str | bytes
Convert between document formats.
- Parameters:
source (str, Path, IO[bytes], IO[str], or bytes) – Source document (file path, file-like object, or content)
output (str, Path, IO[bytes], IO[str], or None, optional) – Output destination. If None, returns rendered content. Can be: - None: Returns str (for text formats) or bytes (for binary formats) - str or Path: Writes content to file at that path - IO[bytes]: Writes content to binary file-like object - IO[str]: Writes content to text file-like object
parser_options (BaseParserOptions, optional) – Options for parsing source format
renderer_options (BaseRendererOptions, optional) – Options for rendering target format
source_format (DocumentFormat, default "auto") – Source format (auto-detected if “auto”)
target_format (DocumentFormat, default "auto") – Target format (inferred from output or defaults to “markdown”)
transforms (list, optional) – AST transforms to apply
hooks (dict, optional) – Transform hooks to execute
renderer (str, type, or object, optional) – Custom renderer (overrides target_format)
flavor (str, optional) – Markdown flavor shorthand for renderer_options
progress_callback (ProgressCallback, optional) – Optional callback function for progress updates. Receives ProgressEvent objects with event_type, message, current/total counts, and metadata. See all2md.progress for details.
remote_input_options (RemoteInputOptions, optional) – Controls remote retrieval behaviour for the source input. Defaults to None (remote fetching disabled).
preserve_formatting (bool, default False) – When True and the target is
"docx"and the source is a docx file, the rendered output uses the source as its template and the source’s body is cleared before rendering. This makes a docx round-trip (e.g.convert("in.docx", "out.docx")) preserve page setup, theme, headers/footers, and custom paragraph styles instead of regenerating a generic-looking document.kwargs (Any) – Additional options split between parser and renderer
- Returns:
None if output was specified (content written to output)
str if output=None and format is text-based (markdown, html, rst, etc.)
bytes if output=None and format is binary (docx, pdf, epub, etc.)
- Return type:
None, str, or bytes
Notes
If you need a file-like object instead of direct content, pass a StringIO or BytesIO instance to the output parameter:
>>> from io import StringIO, BytesIO >>> buffer = StringIO() >>> convert("doc.pdf", output=buffer, target_format="markdown") # Returns None >>> markdown_text = buffer.getvalue()
Examples
- Convert PDF to markdown:
>>> markdown_text = convert("doc.pdf", target_format="markdown") >>> isinstance(markdown_text, str) True
- Convert to binary format:
>>> pdf_bytes = convert("input.md", target_format="pdf") >>> isinstance(pdf_bytes, bytes) True
- Convert with output file:
>>> convert("doc.pdf", "output.md", ... parser_options=PdfOptions(pages=[0, 1]), ... renderer_options=MarkdownRendererOptions(flavor="commonmark"))
- Bidirectional with transforms:
>>> convert("input.docx", "output.md", ... transforms=["remove-images", "heading-offset"])