# Invoice & Table Structurer — PDFs to JSON/CSV (`variable_paddock/invoice-to-json`) Actor

Extract invoice fields (number, dates, parties, totals, tax) and rebuild tables from digital PDFs into JSON/CSV. Chinese invoices first. No OCR, explicit warnings on every heuristic.

- **URL**: https://apify.com/variable_paddock/invoice-to-json.md
- **Developed by:** [Tang](https://apify.com/variable_paddock) (community)
- **Categories:** Developer tools, AI
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Invoice & Table Structurer — PDFs to JSON/CSV

Extract **invoice fields** and **tables** from **digital (text-layer) PDFs** into structured JSON/CSV.
Deterministic heuristics, Chinese invoice / ledger first. **No OCR, no LLM, no external services.**

### Input

| Field | Type | Default | Description |
|---|---|---|---|
| `startUrls` | array of objects | — | Each item: `{ "fileUrl": "https://.../invoice.pdf" }` (local path / `file://` works in local run) |
| `pdfBase64` | string | — | Alternative to `startUrls` for small PDFs |
| `docType` | `auto` / `invoice` / `statement` / `table` | `invoice` | Extraction profile |
| `maxPages` | integer | `20` (cap 100) | Pages to parse |
| `format` | `json` / `csv` | `json` | `csv` adds a CSV string of the first table |
| `includePageText` | boolean | `false` | Include raw page text |

#### Example input

```json
{
  "startUrls": [{ "fileUrl": "https://example.com/invoice.pdf" }],
  "docType": "invoice",
  "format": "json"
}
```

### Output (dataset, one record per PDF)

```json
{
  "ok": true,
  "error": null,
  "docType": "invoice",
  "pages": [...],
  "tables": [ { "rows": [ ["项目", "数量", "金额"], ["..."], ... ] } ],
  "fields": {
    "发票代码": "044001900111",
    "发票号码": "12345678",
    "开票日期": "2026年11月10日",
    "购买方名称": "桂林星辰科技有限公司",
    "购买方税号": "91450300MA5K1234X",
    "销售方名称": "南宁云帆信息技术有限公司",
    "价税合计": "陆仟壹佰捌拾元整 ￥6180.00"
  },
  "issues": [],
  "warnings": [],
  "stats": { "bytes": 78140, "pagesTotal": 1, "pagesParsed": 1, "tables": 1, "fields": 7, "chars": ... }
}
```

### Local run

```bash
npm install
mkdir -p storage/key_value_stores/default
echo '{"startUrls":[{"fileUrl":"C:/path/to/sample-invoice.pdf"}],"docType":"invoice"}' > storage/key_value_stores/default/INPUT.json
node src/main.js
## results: storage/datasets/default/*.json
```

Verified locally with `sample-invoice.pdf`: exit 0, 7 invoice fields + 1 table extracted (log: `logs/run-sample.log`).

### Limitations

- **Digital PDFs only** (must have a text layer). **Scanned/image PDFs need OCR** — not supported here.
- **No handwriting recognition** (handwritten invoice/ledger entries are ignored).
- No LLM cleanup: field extraction is heuristic + regex; unusual layouts may produce warnings/`issues`.
- Max 10 MB per PDF, max 100 pages (hard caps).
- Chinese invoice layout / common ledger tables are the primary target; other layouts may need tuning.

### Platform notes (Apify upload)

- `.actor/actor.json` uses **`actorSpecification: 1`** (not `actorSpecVersion`).
- `package.json`: `main` / `start` = **`src/main.js`**.
- `input_schema.json`: `startUrls.items.type` = **`object`** with `fileUrl` field.
- When creating/updating the Actor, pass **source file contents as plain text**, not base64 (Apify platform pitfall).
- Both `input_schema.json` (root) and `.actor/input_schema.json` are kept in sync for local tooling + platform.

### Files

| File | Purpose |
|---|---|
| `src/main.js` | Actor code (Node stdlib + pinned pdfjs-dist, apify SDK) |
| `input_schema.json` | Actor input schema |
| `.actor/actor.json` | Actor definition |
| `.actor/dataset_schema.json`, `.actor/output_schema.json` | Dataset/output schema |
| `Dockerfile` | Node official image + `npm ci --omit=dev` + `CMD node src/main.js` |
| `sample-invoice.pdf` | Local test fixture |

### Example output (real run on the bundled sample invoice PDF)

```json
{
  "ok": true,
  "docType": "invoice",
  "fields": {
    "发票代码": "...", "发票号码": "...", "开票日期": "...",
    "购买方名称": "...", "购买方税号": "...", "销售方名称": "...", "价税合计": "..."
  },
  "tables": [ { "rows": [ ["项目","数量","金额"], "..." ] } ],
  "pages": [ "..." ],
  "warnings": [ { "code": "TABLE_LOW_CONFIDENCE", "message": "table confidence 75%" } ],
  "stats": { "pages": 1, "tables": 1 }
}
```

> 7 invoice fields + 1 reconstructed table.

# Actor input Schema

## `startUrls` (type: `array`):

One or more PDF files. Each item must be an object: { "fileUrl": "https://.../file.pdf" } (local path or file:// works for local runs).

## `pdfBase64` (type: `string`):

Base64 or data:application/pdf;base64,... for small files. Alternative to startUrls.

## `docType` (type: `string`):

Document type

## `maxPages` (type: `integer`):

Max pages

## `format` (type: `string`):

Output format

## `includePageText` (type: `boolean`):

Include page text

## Actor input object example

```json
{
  "docType": "invoice",
  "maxPages": 20,
  "format": "json",
  "includePageText": false
}
```

# Actor output Schema

## `dataset` (type: `string`):

Tables and invoice fields extracted from the PDF

## `output` (type: `string`):

ok/error/docType/stats summary

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("variable_paddock/invoice-to-json").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("variable_paddock/invoice-to-json").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call variable_paddock/invoice-to-json --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,variable_paddock/invoice-to-json"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/c18CcmLWNCgthRArI/builds/vvcXGbqoAdgBYfxag/openapi.json
