# OCR de DANFE e Nota Fiscal: extraia os dados por foto ou PDF (`brasildados/danfe-nota-fiscal-ocr`) Actor

Extraia os dados de uma DANFE ou foto de nota fiscal com IA: chave de acesso, emitente, destinatário, valores e itens em formato tabular. Faça upload do arquivo ou informe URLs; em lote ou API.

- **URL**: https://apify.com/brasildados/danfe-nota-fiscal-ocr.md
- **Developed by:** [BrasilDados.org](https://apify.com/brasildados) (community)
- **Categories:** Automation, E-commerce, Integrations
- **Stats:** 1 total users, 1 monthly users, 0.0% runs succeeded, NaN bookmarks
- **User rating**: No ratings yet

## Pricing

from $250.00 / 1,000 por nfe - danfe extraídas

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## 🧾 OCR de DANFE e Nota Fiscal: extraia os dados por foto ou PDF

Tem só a **DANFE** ou uma **foto da nota fiscal**? Este Actor extrai os dados com IA e devolve tudo **estruturado em JSON**: chave de acesso, emitente, destinatário, valores e os **itens em formato tabular** - pronto para o seu sistema, planilha ou ERP.

> 🎯 **Feito para a nota fiscal brasileira.** Como a DANFE tem campos conhecidos (NF-e modelo 55 e NFC-e modelo 65), a extração é direcionada a eles - mais assertiva que um OCR genérico.

> ℹ️ Este Actor **lê a imagem/PDF** que você envia (não consulta a SEFAZ). Se você tem a **chave de acesso** e quer o XML oficial, use o [Consulta NFe por Chave](https://apify.com/brasildados/api-consulta-nfe-por-chave?fpr=t5lwzq).

---

### O que você recebe (por documento)

| Campo | Descrição |
|---|---|
| `chaveAcesso` | Chave de acesso de 44 dígitos |
| `numero`, `serie`, `modelo` | Identificação da nota (55 = NF-e, 65 = NFC-e) |
| `dataEmissao`, `naturezaOperacao` | Emissão e natureza da operação |
| `emitenteRazaoSocial`, `emitenteCnpj`, `emitenteInscricaoEstadual`... | Dados do emitente |
| `destinatarioNome`, `destinatarioCnpjCpf`... | Dados do destinatário |
| `valorTotalProdutos`, `valorIcms`, `valorTotalNota`... | Valores e impostos |
| `itens[]` | Produtos da nota em **tabela** (código, descrição, NCM, CFOP, qtd, valor unitário, total) |

---

### Como usar

**Faça upload** da DANFE/foto no campo de input, ou **informe URLs** para lote:

```json
{
  "documentos": [
    "https://upload.wikimedia.org/wikipedia/commons/9/97/Nfe.png"
  ]
}
````

Aceita **PDF, PNG, JPG e WebP**. Até **50 documentos por execução**. PDFs são lidos nativamente (multipágina); imagens são otimizadas antes da análise.

***

### Precificação

Cobrado **por nota extraída com sucesso** (evento `danfe-extraida`). Documentos que falham no download ou não são notas fiscais **não geram cobrança**.

***

### Exemplo de saída

```json
[
  {
    "documentoUrl": "https://upload.wikimedia.org/wikipedia/commons/9/97/Nfe.png",
    "sucesso": true,
    "chaveAcesso": "43090890627936000130550010000001750008965360",
    "numero": "000175", "serie": "1", "modelo": "55",
    "dataEmissao": "2009-08-26",
    "naturezaOperacao": "Venda de mercadoria",
    "emitenteRazaoSocial": "Empresa Teste LTDA.",
    "emitenteCnpj": "90627936000130",
    "destinatarioNome": "Cliente Exemplo",
    "destinatarioCnpjCpf": "00000000000",
    "valorTotalProdutos": 230.0, "valorIcms": 41.4, "valorTotalNota": 230.0,
    "itens": [
      { "codigo": "001", "descricao": "Produto A", "ncm": "00000000", "cfop": "5102", "unidade": "UN", "quantidade": 1, "valorUnitario": 100.0, "valorTotal": 100.0 },
      { "codigo": "002", "descricao": "Produto B", "ncm": "00000000", "cfop": "5102", "unidade": "UN", "quantidade": 1, "valorUnitario": 130.0, "valorTotal": 130.0 }
    ],
    "metadadosArquivo": { "tipo": "png", "tamanhoBytes": 84210, "paginas": null },
    "motivoFalha": null,
    "processadoEm": "2026-01-01T12:00:00.000Z",
    "erro": null
  }
]
```

***

### Perguntas frequentes

**Que documentos funcionam melhor?**
DANFEs em PDF e fotos/scans nítidos. Imagens muito escuras, tortas ou de baixa resolução podem não ser lidas - o motivo vem em `motivoFalha`.

**Funciona com NFC-e (cupom) e DANFE de NF-e?**
Sim, ambos (modelo 55 e 65). Os itens vêm em formato tabular nos dois casos.

**Posso enviar vários de uma vez?**
Sim, até 50 por execução, via upload múltiplo ou lista de URLs.

**Posso chamar em tempo real?**
Sim. O endpoint Standby `POST /extrair` responde de forma síncrona. Veja abaixo.

***

#### 🔌 Integração via API

**Execução em lote:**

```bash
curl -X POST "https://api.apify.com/v2/acts/brasildados~danfe-nota-fiscal-ocr/run-sync-get-dataset-items?token=SEU_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"documentos":["https://upload.wikimedia.org/wikipedia/commons/9/97/Nfe.png"]}'
```

**Standby (`POST /extrair`):**

```bash
curl -X POST "https://brasildados--danfe-nota-fiscal-ocr.apify.actor/extrair" \
  -H "Authorization: Bearer SEU_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  --compressed \
  -d '{"documentos":["https://upload.wikimedia.org/wikipedia/commons/9/97/Nfe.png"]}'
```

O token vai no header `Authorization: Bearer`, nunca na URL.

***

### Actors relacionados

| Actor | Descrição |
|---|---|
| [Consulta NFe por Chave](https://apify.com/brasildados/api-consulta-nfe-por-chave?fpr=t5lwzq) | Já tem a chave? Busque o XML e o DANFE oficiais |
| [Baixar NF-e em Lote](https://apify.com/brasildados/baixar-nfes-lote-api?fpr=t5lwzq) | XML + DANFE de várias chaves num ZIP |
| [Enriquecimento por CNPJ](https://apify.com/brasildados/brazil-enrich-data-lead-by-cnpj?fpr=t5lwzq) | Dados cadastrais completos por CNPJ |

***

### Legal

Este Actor analisa os documentos que você envia. Você é responsável por ter o direito de processá-los e os dados pessoais/fiscais que contiverem.

# Actor input Schema

## `documentos` (type: `array`):

Faça upload de uma ou mais DANFEs/fotos de nota fiscal (PDF, PNG, JPG, WebP) ou cole URLs públicas. Até 50 por execução.

## Actor input object example

```json
{
  "documentos": [
    "https://upload.wikimedia.org/wikipedia/commons/9/97/Nfe.png"
  ]
}
```

# Actor output Schema

## `resultados` (type: `string`):

Notas fiscais extraídas (um registro por documento).

# 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 = {
    "documentos": [
        "https://upload.wikimedia.org/wikipedia/commons/9/97/Nfe.png"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("brasildados/danfe-nota-fiscal-ocr").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 = { "documentos": ["https://upload.wikimedia.org/wikipedia/commons/9/97/Nfe.png"] }

# Run the Actor and wait for it to finish
run = client.actor("brasildados/danfe-nota-fiscal-ocr").call(run_input=run_input)

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

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

```

## CLI example

```bash
echo '{
  "documentos": [
    "https://upload.wikimedia.org/wikipedia/commons/9/97/Nfe.png"
  ]
}' |
apify call brasildados/danfe-nota-fiscal-ocr --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=brasildados/danfe-nota-fiscal-ocr",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "OCR de DANFE e Nota Fiscal: extraia os dados por foto ou PDF",
        "description": "Extraia os dados de uma DANFE ou foto de nota fiscal com IA: chave de acesso, emitente, destinatário, valores e itens em formato tabular. Faça upload do arquivo ou informe URLs; em lote ou API.",
        "version": "1.0",
        "x-build-id": "NXJTmb2m7yhRAqe9A"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/brasildados~danfe-nota-fiscal-ocr/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-brasildados-danfe-nota-fiscal-ocr",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/brasildados~danfe-nota-fiscal-ocr/runs": {
            "post": {
                "operationId": "runs-sync-brasildados-danfe-nota-fiscal-ocr",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/brasildados~danfe-nota-fiscal-ocr/run-sync": {
            "post": {
                "operationId": "run-sync-brasildados-danfe-nota-fiscal-ocr",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "documentos"
                ],
                "properties": {
                    "documentos": {
                        "title": "Documentos (upload ou URLs)",
                        "minItems": 1,
                        "maxItems": 50,
                        "type": "array",
                        "description": "Faça upload de uma ou mais DANFEs/fotos de nota fiscal (PDF, PNG, JPG, WebP) ou cole URLs públicas. Até 50 por execução.",
                        "items": {
                            "type": "string"
                        }
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
