Metadata-Version: 2.1
Name: renderapi-sdk
Version: 1.0.0
Summary: Official Python SDK for the RenderAPI screenshot and PDF rendering service
Project-URL: Homepage, https://renderapi.com
Project-URL: Documentation, https://renderapi.com/docs
Project-URL: Repository, https://github.com/renderapi/renderapi-python
Project-URL: Issues, https://github.com/renderapi/renderapi-python/issues
Author-email: RenderAPI <support@renderapi.com>
License-File: LICENSE
Keywords: api,html-to-image,html-to-pdf,pdf,render,renderapi,screenshot
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.8
Requires-Dist: requests>=2.20.0
Description-Content-Type: text/markdown

# renderapi

Official Python SDK for [RenderAPI](https://renderapi.com) — convert URLs and HTML to screenshots and PDFs via a simple API.

## Installation

```bash
pip install renderapi
```

Requires Python 3.8+.

## Quick Start

```python
from renderapi import RenderAPI

client = RenderAPI("rapi_live_your_api_key")

# Take a screenshot
result = client.screenshot(url="https://example.com")
print(result["url"])  # URL to the rendered image
```

## API Reference

### `RenderAPI(api_key, *, base_url=None, timeout=120)`

Create a client instance.

| Parameter  | Type    | Description                                  |
|------------|---------|----------------------------------------------|
| `api_key`  | `str`   | **Required.** Your API key (`rapi_live_*` or `rapi_test_*`) |
| `base_url` | `str`   | Custom API base URL                          |
| `timeout`  | `float` | Request timeout in seconds. Default: 120     |

---

### `client.screenshot(**options)`

Take a screenshot of a URL or HTML string.

```python
# Screenshot a URL
result = client.screenshot(
    url="https://example.com",
    format="png",
    width=1440,
    height=900,
    full_page=True,
)
print(result["url"])
print(result["file_size_bytes"])
```

```python
# Screenshot from HTML
result = client.screenshot(
    html='<h1 style="color: red;">Hello World</h1>',
    format="jpeg",
    quality=90,
    width=800,
    height=600,
)
```

```python
# Dark mode with CSS injection
result = client.screenshot(
    url="https://news.ycombinator.com",
    dark_mode=True,
    block_ads=True,
    inject_css='body { font-family: "Inter", sans-serif; }',
    device_scale_factor=2,
)
```

```python
# Capture a specific element
result = client.screenshot(
    url="https://example.com",
    selector="#main-chart",
    wait_for="networkidle",
    delay_ms=1000,
)
```

```python
# With caching and webhook
result = client.screenshot(
    url="https://example.com/dashboard",
    cache_ttl=3600,
    webhook_url="https://your-server.com/webhook",
)
```

#### Screenshot Options

| Option               | Type    | Default         | Description                          |
|----------------------|---------|-----------------|--------------------------------------|
| `url`                | `str`   | —               | URL to capture (provide `url` or `html`) |
| `html`               | `str`   | —               | HTML to render                       |
| `format`             | `str`   | `"png"`         | `"png"`, `"jpeg"`, or `"webp"`      |
| `width`              | `int`   | `1280`          | Viewport width (100–3840)            |
| `height`             | `int`   | `800`           | Viewport height (100–2160)           |
| `full_page`          | `bool`  | `False`         | Capture full scrollable page         |
| `device_scale_factor`| `float` | `1`             | Device pixel ratio (1–3)             |
| `quality`            | `int`   | `80`            | Image quality (1–100)                |
| `wait_for`           | `str`   | `"networkidle"` | Wait condition                       |
| `delay_ms`           | `int`   | `0`             | Extra delay after load (0–10000)     |
| `selector`           | `str`   | —               | CSS selector to capture              |
| `dark_mode`          | `bool`  | `False`         | Emulate dark mode                    |
| `block_ads`          | `bool`  | `True`          | Block ads/trackers                   |
| `inject_css`         | `str`   | —               | Custom CSS to inject                 |
| `inject_js`          | `str`   | —               | Custom JS to inject                  |
| `cache_ttl`          | `int`   | `0`             | Cache TTL in seconds (0–86400)       |
| `webhook_url`        | `str`   | —               | Webhook URL for async notification   |

---

### `client.pdf(**options)`

Generate a PDF from a URL or HTML string.

```python
# PDF from URL
result = client.pdf(
    url="https://example.com/report",
    format="A4",
    landscape=False,
)
print(result["url"])
print(result["pages"])
```

```python
# PDF from HTML with margins and header/footer
result = client.pdf(
    html="<h1>Invoice #1234</h1><p>Total: $99.00</p>",
    format="Letter",
    margin={
        "top": "25mm",
        "bottom": "25mm",
        "left": "20mm",
        "right": "20mm",
    },
    header_html='<div style="font-size:10px;text-align:center;">ACME Corp</div>',
    footer_html='<div style="font-size:10px;text-align:center;">Page <span class="pageNumber"></span></div>',
    print_background=True,
)
```

```python
# PDF with custom dimensions
result = client.pdf(
    html="<div>Custom size document</div>",
    format="custom",
    width="210mm",
    height="148mm",
)
```

#### PDF Options

| Option             | Type   | Default         | Description                          |
|--------------------|--------|-----------------|--------------------------------------|
| `url`              | `str`  | —               | URL to render                        |
| `html`             | `str`  | —               | HTML to render                       |
| `format`           | `str`  | `"A4"`          | `"A4"`, `"Letter"`, `"Legal"`, `"custom"` |
| `width`            | `str`  | —               | Custom width (for `"custom"` format) |
| `height`           | `str`  | —               | Custom height (for `"custom"` format)|
| `landscape`        | `bool` | `False`         | Landscape orientation                |
| `margin`           | `dict` | —               | `{"top", "right", "bottom", "left"}` |
| `header_html`      | `str`  | —               | Page header HTML                     |
| `footer_html`      | `str`  | —               | Page footer HTML                     |
| `print_background` | `bool` | `True`          | Include backgrounds                  |
| `wait_for`         | `str`  | `"networkidle"` | Wait condition                       |
| `delay_ms`         | `int`  | `0`             | Extra delay (0–10000)                |
| `inject_css`       | `str`  | —               | Custom CSS                           |
| `inject_js`        | `str`  | —               | Custom JS                            |
| `webhook_url`      | `str`  | —               | Webhook URL                          |

---

### `client.usage()`

Get usage data for the current billing period.

```python
usage = client.usage()

print(usage["plan"])             # "starter"
print(usage["renders_used"])     # 1523
print(usage["renders_included"]) # 5000
print(usage["screenshots"])      # 1200
print(usage["pdfs"])             # 323
```

---

### `client.get_render(render_id)`

Retrieve details of a previous render by ID.

```python
render = client.get_render("rnd_abc123")

print(render["type"])    # "screenshot"
print(render["status"])  # "completed"
print(render["url"])     # Download URL
```

---

### `client.templates.list()`

List all templates.

```python
response = client.templates.list()

for t in response["templates"]:
    print(f"{t['name']} ({t['id']})")
```

---

### `client.templates.create(name, html, **options)`

Create a new Handlebars template.

```python
template = client.templates.create(
    name="Invoice",
    html="""
        <h1>Invoice #{{invoice_number}}</h1>
        <p>Customer: {{customer_name}}</p>
        <p>Amount: ${{amount}}</p>
    """,
    sample_data={
        "invoice_number": "1001",
        "customer_name": "Jane Doe",
        "amount": "150.00",
    },
    default_output="pdf",
)

print(template["id"])  # Use this ID to render
```

---

### `client.templates.render(template_id, data, **options)`

Render a template with data.

```python
# Render as PDF (default)
result = client.templates.render(
    "tmpl_abc123",
    {"invoice_number": "1042", "customer_name": "John Smith", "amount": "250.00"},
)
print(result["url"])
```

```python
# Render as PNG
result = client.templates.render(
    "tmpl_abc123",
    {"invoice_number": "1042", "customer_name": "John Smith"},
    output="png",
    format="Letter",
)
```

| Option   | Type  | Default  | Description                          |
|----------|-------|----------|--------------------------------------|
| `output` | `str` | `"pdf"`  | `"pdf"`, `"png"`, `"jpeg"`, `"webp"`|
| `format` | `str` | `"A4"`   | Page format (PDF output)             |

---

## Error Handling

All API errors raise `RenderAPIError` with structured details.

```python
from renderapi import RenderAPI, RenderAPIError

client = RenderAPI("rapi_live_your_key")

try:
    client.screenshot(url="https://example.com")
except RenderAPIError as e:
    print(e.message)   # Human-readable message
    print(e.status)    # HTTP status (400, 401, 408, 422, etc.)
    print(e.code)      # Error code ("render_timeout", "render_failed", etc.)
    print(e.details)   # Validation details (for 400 errors)
```

## Type Hints

The package is fully typed and ships with a `py.typed` marker. TypedDict classes for all
request options and response objects are available in `renderapi.types`:

```python
from renderapi.types import ScreenshotOptions, ScreenshotResult, PdfOptions, PdfResult
```

## License

MIT
