> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.datalab.to/llms.txt
> Use this file to discover all available pages before exploring further.

# Document Conversion

> Convert PDFs, images, and documents to Markdown, HTML, JSON, or chunks using the Datalab SDK.

<Warning>
  A completed request can return `success=False` and `error` without raising an SDK exception. Check `result.success` before reading the output.

  Python SDK 0.5.0 does not download signed regional results automatically. For EU requests, use the [REST polling and download flow](/docs/recipes/conversion/conversion-api-overview#regional-result-downloads).
</Warning>

## Basic Usage

```python theme={null}
from datalab_sdk import DatalabClient

client = DatalabClient()

# Convert to markdown (default)
result = client.convert("document.pdf")
if not result.success:
    raise RuntimeError(result.error or "Document processing failed")
print(result.markdown)

# Convert from URL
result = client.convert(file_url="https://example.com/document.pdf")
print(result.markdown)
```

## Conversion Options

Use `ConvertOptions` to control the conversion:

```python theme={null}
from datalab_sdk import DatalabClient, ConvertOptions

client = DatalabClient()

options = ConvertOptions(
    output_format="markdown",     # Output format
    mode="balanced",              # Processing mode
    paginate=True,                # Add page delimiters
    page_range="0-5,10",          # Specific pages (0-indexed); do not combine with max_pages
)

result = client.convert("document.pdf", options=options)
```

### All Options

| Option | Type | Default | Description |
| - | - | - | - |
| `output_format` | str | `"markdown"` | Output format: `"markdown"`, `"html"`, `"json"`, `"chunks"` |
| `mode` | str | `"fast"` | Processing mode: `"fast"`, `"balanced"`, `"accurate"` |
| `paginate` | bool | `False` | Add page delimiters to output |
| `max_pages` | int | None | Maximum number of pages to process |
| `page_range` | str | None | Specific pages to process (e.g., `"0-5,10,15-20"`). For spreadsheets, filters by sheet index. |
| `skip_cache` | bool | `False` | Skip cached results, force reprocessing |
| `disable_image_extraction` | bool | `False` | Don't extract images from document |
| `disable_image_captions` | bool | `False` | Don't generate captions for images |
| `token_efficient_markdown` | bool | `False` | Optimize markdown output for LLM token usage |
| `fence_synthetic_captions` | bool | `False` | Fence synthetic image captions |
| `include_markdown_in_chunks` | bool | `False` | Include markdown in chunks/JSON output |
| `save_checkpoint` | bool | `False` | Save intermediate checkpoint for reuse |
| `extras` | str | None | Comma-separated features: `"track_changes"`, `"chart_understanding"`, `"extract_links"`, `"extract_bookmarks"`, `"table_cell_bboxes"`, `"list_item_bboxes"`, `"infographic"`, `"new_block_types"`. (`"table_row_bboxes"` is deprecated — use `"table_cell_bboxes"` instead.) |
| `add_block_ids` | bool | `False` | Add block IDs to HTML output for citations |
| `keep_spreadsheet_formatting` | bool | `False` | Preserve spreadsheet styling in HTML output |
| `eval_rubric_id` | int | None | ID of an active evaluation rubric owned by your team. Runs after ordinary document conversion and returns `evaluation`; does not run for spreadsheets or `track_changes`. |
| `webhook_url` | str | None | Override account webhook URL for this request |
| `additional_config` | dict | None | Additional configuration, including `disable_html_prettify=True` for compact HTML output |

<Info>
  Use the [REST API](/docs/recipes/conversion/conversion-api-overview) for `merge_cross_page`, `word_bboxes`, and `processing_location`; these are not fields in `ConvertOptions`.
</Info>

<Tip>
  Use `save_checkpoint=True` to save the parsed document state. Then call `client.extract()` or `client.segment()` with the returned `checkpoint_id` to run extraction or segmentation without re-parsing.
</Tip>

### Processing Modes

| Mode | Description | Use Case |
| - | - | - |
| `fast` | Lowest latency (default) | Simple documents, real-time applications |
| `balanced` | Balance of speed and accuracy | General use |
| `accurate` | Highest accuracy | Complex layouts, tables, figures |

### Output Formats

| Format | Description |
| - | - |
| `markdown` | Clean markdown with headers, lists, tables |
| `html` | Structured HTML preserving layout |
| `json` | Block-level structure with bounding boxes |
| `chunks` | Pre-chunked output for RAG applications |

## Conversion Result

The `ConversionResult` object contains the converted content and metadata:

```python theme={null}
result = client.convert("document.pdf")

# Access content based on output format
print(result.markdown)        # Markdown output
print(result.html)            # HTML output
print(result.json)            # JSON structure
print(result.chunks)          # Chunked output

# Metadata
print(result.success)         # True if conversion succeeded
print(result.page_count)      # Number of pages processed
print(result.images)          # Dict of extracted images (filename -> base64)
print(result.metadata)        # Document metadata
print(result.parse_quality_score)  # Quality score (0-5)
print(result.cost_breakdown)  # Cost in cents
```

### Result Fields

| Field | Type | Description |
| - | - | - |
| `success` | bool | Whether conversion succeeded |
| `markdown` | str | Markdown output (if format is markdown) |
| `html` | str | HTML output (if format is html) |
| `json` | dict | JSON output (if format is json) |
| `chunks` | dict | Chunked output (if format is chunks) |
| `images` | dict | Extracted images as `{filename: base64_data}` |
| `metadata` | dict | Document metadata. When present, `failed_pages` lists original, 0-indexed pages that could not be parsed. An empty list means no page failures were reported. With `extras="extract_bookmarks"`, `pdf_bookmarks` contains the PDF outline; check `pdf_bookmarks_truncated` for incomplete extraction. |
| `page_count` | int | Number of pages processed |
| `parse_quality_score` | float | Quality score from 0-5 |
| `cost_breakdown` | dict | Cost details (`list_cost_cents`, `final_cost_cents`) |
| `checkpoint_id` | str | Checkpoint ID if `save_checkpoint` was True |
| `evaluation` | dict | Evaluation results when a rubric was requested |
| `error` | str | Error message if conversion failed |

## Saving Output

Save the conversion result to files:

```python theme={null}
# Save during conversion
result = client.convert("document.pdf", save_output="output/document")

# Or save afterward
result.save_output("output/document", save_images=True)
```

This creates:

* `document.md` (or `.html`, `.json` based on format)
* `document_images/` directory with extracted images (if `save_images=True`)

## Async Usage

For high-throughput applications:

```python theme={null}
import asyncio
from datalab_sdk import AsyncDatalabClient, ConvertOptions

async def convert_documents():
    async with AsyncDatalabClient() as client:
        options = ConvertOptions(mode="fast", max_pages=5)
        result = await client.convert("document.pdf", options=options)
        return result.markdown

markdown = asyncio.run(convert_documents())
```

## Polling Configuration

Control polling behavior for long-running conversions:

```python theme={null}
result = client.convert(
    "large_document.pdf",
    max_polls=600,        # Maximum polling attempts (default: 300)
    poll_interval=2,      # Seconds between polls (default: 1)
)
```

## Special Features

### Track Changes

Extract tracked changes and comments from DOCX, PDF, and image files:

```python theme={null}
options = ConvertOptions(
    output_format="html",
    extras="track_changes",
)
result = client.convert("contract.docx", options=options)
# HTML contains <ins>, <del>, and <comment> tags
```

### Chart Understanding

Extract data from charts and graphs:

```python theme={null}
options = ConvertOptions(
    extras="chart_understanding",
)
result = client.convert("report.pdf", options=options)
```

### Block IDs for Citations

Add block IDs for tracking content back to source locations:

```python theme={null}
options = ConvertOptions(
    output_format="html",
    add_block_ids=True,
)
result = client.convert("document.pdf", options=options)
# HTML elements include data-block-id attributes
```

### Structured Extraction

For structured data extraction, use the dedicated [`client.extract()`](/docs/welcome/sdk/extraction) method.

## Next Steps

<CardGroup cols={2}>
  <Card title="Structured Extraction Recipe" icon="table" href="/docs/recipes/structured-extraction/api-overview">
    Extract structured data from documents using JSON schemas.
  </Card>

  <Card title="Batch Processing" icon="layer-group" href="/docs/recipes/conversion/batch-documents">
    Process multiple documents efficiently in parallel.
  </Card>

  <Card title="Form Filling SDK" icon="pen-to-square" href="/docs/welcome/sdk/form-filling">
    Programmatically fill PDF and image forms with field data.
  </Card>

  <Card title="CLI Reference" icon="terminal" href="/docs/welcome/sdk/cli">
    Convert documents from the command line.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.