Skip to content

Kotlin (Android) API Reference

Convert HTML to Markdown, Djot, or plain text.

Returns a ConversionResult with converted content plus optional metadata, document structure, table data, inline images, and warnings depending on the enabled features and conversion options.

Errors:

Returns an error if HTML parsing fails or if the input contains invalid UTF-8.

Emits an html_to_markdown.convert span at INFO level with fields input_len, output_format, wrap, extract_metadata, extract_images, and tier_strategy. These field names are part of the public observability contract and are kept stable across releases. This crate never installs a tracing subscriber — attach one in the consuming application to observe these spans and events.

Signature:

@Throws(ConversionError::class)
fun convert(html: String, options: ConversionOptions? = null): ConversionResult

Example:

val result = convert("value", ConversionOptions())

Parameters:

Name Type Required Description
html String Yes The html
options ConversionOptions? No The options to use

Returns: ConversionResult

Errors: Throws ConversionError.


Main conversion options for HTML to Markdown conversion.

Use ConversionOptions.builder() to construct, or the default constructor for defaults.

Field Type Default Description
headingStyle HeadingStyle HeadingStyle.Atx Heading style to use in Markdown output (ATX # or Setext underline).
listIndentType ListIndentType ListIndentType.Spaces How to indent nested list items (spaces or tab).
listIndentWidth Long 2 Number of spaces (or tabs) to use for each level of list indentation.
bullets String "-*+" Bullet character(s) to use for unordered list items (e.g. "-", "*").
strongEmSymbol String "*" Character used for bold/italic emphasis markers (* or _).
escapeAsterisks Boolean false Escape * characters in plain text to avoid unintended bold/italic.
escapeUnderscores Boolean false Escape _ characters in plain text to avoid unintended bold/italic.
escapeMisc Boolean false Escape miscellaneous Markdown metacharacters ([]()# etc.) in plain text.
escapeAscii Boolean false Escape ASCII characters that have special meaning in certain Markdown dialects.
codeLanguage String "" Default language annotation for fenced code blocks that have no language hint.
autolinks Boolean true Automatically convert bare URLs into Markdown autolinks.
defaultTitle Boolean false Emit a default title when no <title> tag is present.
brInTables Boolean false Render <br> elements inside table cells as literal line breaks.
compactTables Boolean false Emit tables without column padding (compact GFM format). When true, column widths are not computed and cells are emitted with no trailing spaces. Separator rows use exactly --- per column. Produces token-efficient output suitable for RAG / LLM contexts. Default false (aligned padding preserved).
highlightStyle HighlightStyle HighlightStyle.DoubleEqual Style used for <mark> / highlighted text (e.g. ==text==).
extractMetadata Boolean true Populate result.metadata with <head> / <meta> extraction (title, description, Open Graph, Twitter Card, JSON-LD, …). Default true. Disabling skips the metadata pass only — table extraction into result.tables runs unconditionally.
whitespaceMode WhitespaceMode WhitespaceMode.Normalized Controls how whitespace sequences are normalised in the converted output. - WhitespaceMode.Normalized (default) — collapses consecutive whitespace characters (spaces, tabs, newlines) to a single space, matching browser rendering behaviour. - WhitespaceMode.Strict — preserves all whitespace exactly as it appears in the source HTML, including runs of spaces and embedded newlines. Choose Strict only when the source HTML uses deliberate whitespace (e.g. pre-formatted content outside <pre> tags). For most documents Normalized produces cleaner output.
stripNewlines Boolean false Strip all newlines from the output, producing a single-line result.
wrap Boolean false Wrap long lines at wrap_width characters.
wrapWidth Long 80 Maximum output line width in characters when wrap is true (default 80). Lines are broken at word boundaries so that no line exceeds this length. A value of 0 is treated as “no limit” — equivalent to leaving wrap disabled. Has no effect when wrap is false.
convertAsInline Boolean false Treat the entire document as inline content (no block-level wrappers).
subSymbol String "" Markdown notation for subscript text (e.g. "~").
supSymbol String "" Markdown notation for superscript text (e.g. "^").
newlineStyle NewlineStyle NewlineStyle.Spaces How to encode hard line breaks (<br>) in Markdown.
codeBlockStyle CodeBlockStyle CodeBlockStyle.Backticks Style used for fenced code blocks (backticks or tilde).
keepInlineImagesIn List<String> [] HTML tag names whose <img> children are kept inline instead of block.
preprocessing PreprocessingOptions Options for the HTML pre-processing pass applied before conversion begins. Pre-processing runs before the HTML is handed to the converter and can perform operations such as unwrapping redundant wrapper elements, removing tracking pixels, and normalising vendor-specific markup. See PreprocessingOptions for the full set of knobs. Defaults to the standard preprocessing options, which enables the standard cleaning passes. Set individual fields on PreprocessingOptions (or construct via ConversionOptions.builder) to opt in or out of specific passes.
encoding String "utf-8" Expected character encoding of the input HTML (default "utf-8").
debug Boolean false Emit debug information during conversion.
stripTags List<String> [] HTML tag names whose content is stripped from the output entirely.
preserveTags List<String> [] HTML tag names that are preserved verbatim in the output.
skipImages Boolean false Skip conversion of <img> elements (omit images from output).
urlEscapeStyle UrlEscapeStyle UrlEscapeStyle.Angle URL encoding strategy for link and image destinations. Controls how special characters in URL destinations are escaped: - UrlEscapeStyle.Angle (default) — wraps the destination in angle brackets when it contains spaces or newlines. Some parsers misinterpret > inside such a destination. - UrlEscapeStyle.Percent — percent-encodes every character that is not an RFC 3986 unreserved character or /, producing a destination that all Markdown parsers handle correctly even when the URL contains <, >, spaces, or parentheses.
linkStyle LinkStyle LinkStyle.Inline Link rendering style (inline or reference).
outputFormat OutputFormat OutputFormat.Markdown Target output format (Markdown, plain text, etc.).
includeDocumentStructure Boolean false Include structured document tree in result.
extractImages Boolean false Extract inline images from data URIs and SVGs.
maxImageSize Long 5242880 Maximum decoded image size in bytes (default 5MB).
captureSvg Boolean false Capture SVG elements as images.
inferDimensions Boolean true Infer image dimensions from data.
maxDepth Long? null Maximum DOM traversal depth. null uses the library’s internal native-stack safety limit. Explicit values above that safety limit are clamped to prevent process-aborting stack overflows on pathologically deep DOM trees.
excludeSelectors List<String> [] CSS selectors for elements to exclude entirely (element + all content). Unlike strip_tags (which removes the tag wrapper but keeps children), excluded elements and all their descendants are dropped from the output. Supports any CSS selector that tl supports: tag names, .class, #id, [attribute], etc. Invalid selectors are silently skipped at conversion time. Example: [".cookie-banner", "#ad-container", "[role='complementary']"]
tierStrategy TierStrategy TierStrategy.Auto Which conversion tier to use. - TierStrategy.Auto (default) — automatically choose the best path. - TierStrategy.Tier2 — always use the Tier-2 DOM-walk path. - TierStrategy.Tier1 — always attempt Tier-1 (testkit only).

The primary result of HTML conversion and extraction.

Contains the converted text output, optional structured document tree, metadata, extracted tables, images, and processing warnings.

Field Type Default Description
content String? null Converted text output in the selected format: Markdown, Djot, or plain text.
document DocumentStructure? null Structured document tree with semantic elements. Populated when the include_document_structure option is true. null otherwise (the default), which avoids the overhead of building the tree. When present, the tree mirrors the converted document: headings open Group sections, paragraphs and list items carry inline TextAnnotations, and tables reference the same TableGrid data exposed in the result’s tables field. Note: this field is independent of the metadata feature flag. Document structure collection is always available at runtime; it is gated only by the runtime option, not by a compile-time feature.
metadata HtmlMetadata Extracted HTML metadata (title, OG, links, images, structured data).
tables List<TableData> [] Extracted tables with structured cell data and markdown representation. Table data is collected by the same pass that builds Self.document, so it is populated only when the include_document_structure option is true. With the default options this is an empty list even for input that contains tables — the tables still appear in Self.content as rendered Markdown.
warnings List<ProcessingWarning> [] Non-fatal processing warnings.

Document-level metadata extracted from <head> and top-level elements.

Contains all metadata typically used by search engines, social media platforms, and browsers for document indexing and presentation.

Field Type Default Description
title String? null Document title from <title> tag
description String? null Document description from <meta name="description"> tag
keywords List<String> [] Document keywords from <meta name="keywords"> tag, split on commas
author String? null Document author from <meta name="author"> tag
canonicalUrl String? null Canonical URL from <link rel="canonical"> tag
baseHref String? null Base URL from <base href=""> tag for resolving relative URLs
language String? null Document language from lang attribute
textDirection TextDirection? null Document text direction from dir attribute
openGraph Map<String, String> {} Open Graph metadata (og:* properties) for social media Keys like “title”, “description”, “image”, “url”, etc.
twitterCard Map<String, String> {} Twitter Card metadata (twitter:* properties) Keys like “card”, “site”, “creator”, “title”, “description”, “image”, etc.
metaTags Map<String, String> {} Additional meta tags not covered by specific fields Keys are meta name/property attributes, values are content

A single node in the document tree.

Field Type Default Description
id String Deterministic node identifier.
content NodeContent The semantic content of this node.
parent Int? null Index of the parent node (None for root nodes).
children List<Int> /* serde(default) */ Indices of child nodes in reading order.
annotations List<TextAnnotation> /* serde(default) */ Inline formatting annotations (bold, italic, links, etc.) with byte offsets into the text.
attributes Map<String, String>? null Format-specific attributes preserved from the source HTML element. Keys are lowercased attribute names as they appear in the HTML (e.g. "class", "id", "data-foo"). Values are the raw attribute strings, copied verbatim from the source — no HTML entity decoding is applied here. The map is null when no attributes are present (omitted entirely in serialized output). Not every HTML attribute is preserved: only attributes that carry semantic or structural significance for the node type are collected. For example, heading nodes capture the "id" attribute for anchor linking; other element-level attributes may be silently dropped.

A structured document tree representing the semantic content of an HTML document.

Uses a flat node array with index-based parent/child references for efficient traversal.

Field Type Default Description
nodes List<DocumentNode> All nodes in document reading order.
sourceFormat String? null The source format (always “html” for this library).

A single cell in a table grid.

Field Type Default Description
content String The text content of the cell.
row Int 0-indexed row position.
col Int 0-indexed column position.
rowSpan Int default_span() Number of rows this cell spans (default 1).
colSpan Int default_span() Number of columns this cell spans (default 1).
isHeader Boolean /* serde(default) */ Whether this is a header cell (<th>).

Header element metadata with hierarchy tracking.

Captures heading elements (h1-h6) with their text content, identifiers, and position in the document structure.

Field Type Default Description
level Byte Header level: 1 (h1) through 6 (h6)
text String Normalized text content of the header
id String? null HTML id attribute if present
depth Long Document tree depth at the header element
htmlOffset Long Byte offset in original HTML document

Comprehensive metadata extraction result from HTML document.

Contains all extracted metadata types in a single structure, suitable for serialization and transmission across language boundaries.

Field Type Default Description
document DocumentMetadata Document-level metadata (title, description, canonical, etc.)
headers List<HeaderMetadata> [] Extracted header elements with hierarchy
links List<LinkMetadata> [] Extracted hyperlinks with type classification
images List<ImageMetadata> [] Extracted images with source and dimensions
structuredData List<StructuredData> [] Extracted structured data blocks

Image dimensions in pixels.

Binding-safe replacement for (u32, u32) tuples, which degrade to List<List<String>> when sanitized for cross-language binding generation. Used by both ImageMetadata and InlineImage.

Field Type Default Description
width Int Width in pixels.
height Int Height in pixels.

Image metadata with source and dimensions.

Captures <img> elements and inline <svg> elements with metadata for image analysis and optimization.

Field Type Default Description
src String Image source (URL, data URI, or SVG content identifier)
alt String? null Alternative text from alt attribute (for accessibility)
title String? null Title attribute (often shown as tooltip)
dimensions ImageDimensions? null Image dimensions in pixels, if available.
imageType ImageType Image type classification
attributes Map<String, String> Additional HTML attributes

Hyperlink metadata with categorization and attributes.

Represents <a> elements with parsed href values, text content, and link type classification.

Field Type Default Description
href String The href URL value
text String Link text content (normalized, concatenated if mixed with elements)
title String? null Optional title attribute (often shown as tooltip)
linkType LinkType Link type classification
rel List<String> Rel attribute values (e.g., “nofollow”, “stylesheet”, “canonical”)
attributes Map<String, String> Additional HTML attributes

A single key-value metadata entry from <head> meta tags.

Binding-safe replacement for (String, String) tuples used in NodeContent.MetadataBlock. Tuple pairs cannot be represented across language boundaries without lossy degradation.

Field Type Default Description
key String Metadata key (e.g. "title", "description", "og:title").
value String Metadata value.

HTML preprocessing options for document cleanup before conversion.

Field Type Default Description
enabled Boolean true Enable HTML preprocessing globally
preset PreprocessingPreset PreprocessingPreset.Standard Preprocessing preset level (Minimal, Standard, Aggressive)
removeNavigation Boolean true Remove navigation elements (nav, breadcrumbs, menus, sidebars)
removeForms Boolean true Remove form elements (forms, inputs, buttons, etc.)

A non-fatal diagnostic produced during HTML conversion.

Warnings indicate that conversion completed but some content may have been handled differently than expected — for example, an image that could not be extracted, a truncated input, or malformed HTML that was repaired with best-effort parsing.

Conversion always succeeds (returns ConversionResult) even when warnings are present. Callers should inspect warnings and decide how to handle them based on their tolerance for partial results:

  • Logging pipelines: emit each warning at WARN level and continue.
  • Strict pipelines: treat any warning as a hard error by checking result.warnings.is_empty() before using the output.

See WarningKind for the full taxonomy of warning categories.

Field Type Default Description
message String Human-readable warning message.
kind WarningKind The category of warning.

Structured data block (JSON-LD, Microdata, or RDFa).

Represents machine-readable structured data found in the document. JSON-LD blocks are collected as raw JSON strings for flexibility.

Field Type Default Description
dataType StructuredDataType Type of structured data (JSON-LD, Microdata, RDFa)
rawJson String Raw JSON string (for JSON-LD) or serialized representation
schemaType String? null Schema type if detectable (e.g., “Article”, “Event”, “Product”)

A top-level extracted table with both structured data and markdown representation.

Field Type Default Description
grid TableGrid The structured table grid.
markdown String The markdown rendering of this table.

A structured table grid with cell-level data including spans.

Field Type Default Description
rows Int Number of rows.
cols Int Number of columns.
cells List<GridCell> [] All cells in the table as a flat, sparse list. The list is ordered by (row, col) but is not a dense rows × cols matrix: cells that are covered by a spanning cell (via row_span > 1 or col_span > 1) do not appear in the list. Only the top-left “origin” cell of a span is present, with its row_span and col_span fields set accordingly. To reconstruct the full visual grid, iterate over all cells and mark the rectangular region [row .. row+row_span, col .. col+col_span] as occupied by that cell. Any (row, col) position that is not the origin of any cell is covered by a span from an earlier cell. The length of this list is ≤ rows * cols. An empty table (rows == 0 || cols == 0) produces an empty list.

A styling or semantic annotation that applies to a byte range within a node’s text.

Unlike DocumentNode, which captures block-level structure (headings, paragraphs, etc.), a TextAnnotation describes inline-level markup — bold, italic, links, code spans, and similar — that spans a contiguous run of bytes inside DocumentNode.content’s text field.

Byte offsets (start..end) are into the UTF-8 encoded text of the parent node. The range is half-open: start is inclusive and end is exclusive.

Multiple annotations on the same node can overlap (e.g. bold-italic text), and they are stored in the order they are encountered during DOM traversal.

See AnnotationKind for the full list of supported annotation types.

Field Type Default Description
start Int Start byte offset (inclusive) into the parent node’s text.
end Int End byte offset (exclusive) into the parent node’s text.
kind AnnotationKind The type of annotation.

Text directionality of document content.

Corresponds to the HTML dir attribute and bdi element directionality.

Value Description
LeftToRight Left-to-right text flow (default for Latin scripts)
RightToLeft Right-to-left text flow (Hebrew, Arabic, Urdu, etc.)
Auto Automatic directionality detection

Link classification based on href value and document context.

Used to categorize links during extraction for filtering and analysis.

Value Description
Anchor Anchor link within same document (href starts with #)
Internal Internal link within same domain
External External link to different domain
Email Email link (mailto:)
Phone Phone link (tel:)
Other Other protocol or unclassifiable

Image source classification for proper handling and processing.

Determines whether an image is embedded (data URI), inline SVG, external, or relative.

Value Description
DataUri Data URI embedded image (base64 or other encoding)
InlineSvg Inline SVG element
External External image URL (http/https)
Relative Relative image path

Structured data format type.

Identifies the schema/format used for structured data markup.

Value Description
JsonLd JSON-LD (JSON for Linking Data) script blocks
Microdata HTML5 Microdata attributes (itemscope, itemtype, itemprop)
RDFa RDF in Attributes (RDFa) markup

Controls which conversion tier is used.

Value Description
Auto Automatically pick the best tier for the input (default). Runs the classifier against the prescan report and uses Tier-1 when eligible; falls back to Tier-2 on bail or when the classifier routes to Tier-2.
Tier2 Always use the Tier-2 (tl.parse + walk) path, skipping Tier-1.
Tier1 Force the Tier-1 byte scanner; if it bails, fall back to Tier-2. Testkit-only; not stable API.

HTML preprocessing aggressiveness level.

Controls the extent of cleanup performed before conversion. Higher levels remove more elements.

Value Description
Minimal Minimal cleanup. Remove only essential noise (scripts, styles).
Standard Standard cleanup. Default. Removes navigation, forms, and other auxiliary content.
Aggressive Aggressive cleanup. Remove extensive non-content elements and structure.

Heading style options for Markdown output.

Controls how headings (h1-h6) are rendered in the output Markdown.

Value Description
Underlined Underlined style (=== for h1, — for h2).
Atx ATX style (# for h1, ## for h2, etc.). Default.
AtxClosed ATX closed style (# title #, with closing hashes).

List indentation character type.

Controls whether list items are indented with spaces or tabs.

Value Description
Spaces Use spaces for indentation. Default. Width controlled by list_indent_width.
Tabs Use tabs for indentation.

Whitespace handling strategy during conversion.

Determines how sequences of whitespace characters (spaces, tabs, newlines) are processed.

Value Description
Normalized Collapse multiple whitespace characters to single spaces. Default. Matches browser behavior.
Strict Preserve all whitespace exactly as it appears in the HTML.

Line break syntax in Markdown output.

Controls how soft line breaks (from <br> or line breaks in source) are rendered.

Value Description
Spaces Two trailing spaces at end of line. Default. Standard Markdown syntax.
Backslash Backslash at end of line. Alternative Markdown syntax.

Code block fence style in Markdown output.

Determines how code blocks (<pre><code>) are rendered in Markdown.

Value Description
Indented Indented code blocks (4 spaces). CommonMark standard.
Backticks Fenced code blocks with triple backticks. Default (GFM). Supports language hints.
Tildes Fenced code blocks with tildes (~~~). Supports language hints.

Highlight rendering style for <mark> elements.

Controls how highlighted text is rendered in Markdown output.

Value Description
DoubleEqual Double equals syntax (==text==). Default. Pandoc-compatible.
Html Preserve as HTML (==text==). Original HTML tag.
Bold Render as bold (text). Uses strong emphasis.
None Strip formatting, render as plain text. No markup.

Link rendering style in Markdown output.

Controls whether links and images use inline text syntax or reference-style [text][1] syntax with definitions collected at the end.

Value Description
Inline Inline links: text. Default.
Reference Reference-style links: [text][1] with [1]: url at end of document.

URL encoding strategy for link and image destinations.

Controls how special characters in URL destinations are handled when they require escaping to produce valid Markdown.

The Angle variant (default) wraps the destination in angle brackets: [text](<url with spaces>). This is the CommonMark-specified escape hatch but breaks when the URL itself contains >.

The Percent variant percent-encodes every character that is not an RFC 3986 unreserved character or /, producing a destination safe for all Markdown parsers: [text](url%20with%20spaces).

Value Description
Angle Wrap destinations that contain spaces or newlines in angle brackets. Default.
Percent Percent-encode all characters that are not RFC 3986 unreserved or /.

Output format for conversion.

Specifies the target markup language format for the conversion output.

Value Description
Markdown Standard Markdown (CommonMark compatible). Default.
Djot Djot lightweight markup language.
Plain Plain text output (no markup, visible text only).

The semantic content type of a document node.

Uses internally tagged representation ("node_type": "heading") for JSON serialization.

Value Description
Heading A heading element (h1-h6). — Fields: level: Byte, text: String
Paragraph A paragraph of text. — Fields: text: String
List A list container (ordered or unordered). Children are ListItem nodes. — Fields: ordered: Boolean
ListItem A single list item. — Fields: text: String
Table A table with structured cell data. — Fields: grid: TableGrid
Image An image element. — Fields: description: String, src: String, imageIndex: Int
Code A code block or inline code. — Fields: text: String, language: String
Quote A block quote container.
DefinitionList A definition list container.
DefinitionItem A definition list entry with term and description. — Fields: term: String, definition: String
RawBlock A raw block preserved as-is (e.g. <script>, <style> content). — Fields: format: String, content: String
MetadataBlock A block of key-value metadata pairs (from <head> meta tags). — Fields: entries: List<MetadataEntry>
Group A section grouping container (auto-generated from heading hierarchy). — Fields: label: String, headingLevel: Byte, headingText: String

The type of an inline text annotation.

Uses internally tagged representation ("annotation_type": "bold") for JSON serialization.

Value Description
Bold Bold / strong emphasis.
Italic Italic / emphasis.
Underline Underline.
Strikethrough Strikethrough / deleted text.
Code Inline code.
Subscript Subscript text.
Superscript Superscript text.
Highlight Highlighted / marked text.
Link A hyperlink sourced from an <a href="..."> element. — Fields: url: String, title: String

Categories of processing warnings.

Value Description
ImageExtractionFailed An image could not be extracted (e.g. invalid data URI, unsupported format).
EncodingFallback The input encoding was not recognized; fell back to UTF-8.
TruncatedInput The input was truncated due to size limits.
MalformedHtml The HTML was malformed but processing continued with best effort.
SanitizationApplied Sanitization was applied to remove potentially unsafe content.
DepthLimitExceeded DOM traversal was truncated because max_depth was exceeded.

Errors that can occur during HTML to Markdown conversion.

Variant Description
ParseError HTML parsing error
SanitizationError HTML sanitization error
ConfigError Invalid configuration
IoError I/O error — stores the error message string so the variant is FFI-safe. Use ConversionError.from(io_error) to convert from an operating-system I/O error.
Panic Internal error caught during conversion
InvalidInput Invalid input data
Other Generic conversion error