Skip to main content
Glama
io.github.Edgar-311/ofdkit

io.github.Edgar-311/ofdkit

by Edgar-311

ofdkit

轻量的 Python 工具,用来读取 OFD 文件,提取里面的文字和发票字段,并能接入 AI 工具。OFD 是中国的国家标准版式文档格式(GB/T 33190),常见于电子发票和公文。

A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese fixed-layout format used for e-invoices and official documents): extract text and invoice fields, and use them from AI tools.

状态:0.5 版,更新记录见 CHANGELOG。 Status: 0.5. See the CHANGELOG.

能做什么 / What it does

  • Windows x64 用户可下载便携包,解压后双击运行。桌面窗口可搜索文字、跳页、选页保存,并筛选批量结果。 Windows x64 users can extract and launch the portable app. Search text, jump to pages, save selected pages, and filter batch results.

  • 桌面的跨文件搜索可以查一个 OFD 文件、文件夹或 ZIP。结果显示原页码、行号和原文片段。 Desktop search finds text across an OFD file, folder or ZIP and shows page and line references.

  • 用桌面窗口选 OFD 文件、逐页读文字,或把发票文件夹和 ZIP 导出到 Excel。文件在本机处理。 Open OFD text page by page or export invoices from a folder or ZIP in a local desktop window.

  • 看发票:一条命令显示发票号码、日期、购买方、销售方、金额和明细。 Show an invoice: number, date, buyer, seller, amounts and line items, with one command.

  • 把一个文件夹里的发票汇总到 Excel,也能直接读税务平台批量下载的 .zip 压缩包。发票号码保持原样(不会变成 2.4E+19),金额可以直接求和,重复的发票会标出来。 Summarise a folder of invoices, or a .zip archive downloaded from the tax service, into an Excel workbook: invoice numbers stay intact, amounts are numbers, duplicates are flagged.

  • 报销帮手:检查发票抬头(购买方名称、税号)对不对;按发票内容给文件改名,可以预览、可以改回去。 For reimbursement: check that invoices are made out to the right buyer, and rename invoice files after their contents, with a preview and an undo.

  • 按阅读顺序提取文字,包括模板和复合对象里的文字。 Text in reading order, including text in templates and composite objects.

  • 跨文件搜索关键词,导出逐页 JSON 和文字坐标,或把一批 OFD 保存成一个文字 ZIP。 Search across files, export page data and positioned text runs, or bundle a batch of text exports in a ZIP.

  • 按日期、购销方和问题筛选发票,检查金额与明细的一致性,导出单独的复核表。 Filter invoice review by date, party and issue, check extracted amounts, and export a review workbook.

  • 对比两次保存的复核结果,查看新发现、仍存在和已处理的问题。 Compare two saved review reports to track new, persistent and resolved findings.

  • 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。 For programs and AI: invoice fields as JSON, an MCP server, an Agent Skill and a MarkItDown plugin.

  • 只用 Python 标准库,没有任何第三方依赖;能读很多不规范的文件(路径写法不对、编码不对、XML 前缀错误等)。 Standard library only, no dependencies; reads many non-conforming files (bad paths, encodings, XML prefixes).

Related MCP server: MokuPDF

快速上手 / Quick start

Windows x64 可在 GitHub 发布页 下载 ofdkit-*-windows-x64.zip。完整解压后双击 ofdkit.exe,然后点“试用样例”开始。命令行、Python 库和 AI 接入可按下面的方法安装。 On Windows x64, download the portable ZIP, extract it, and open ofdkit.exe. Use the Python package for the CLI, library and AI integrations.

第一次用命令行?先看 Windows 新手指南:包含普通测试样例、带空格的路径写法、Excel 输出位置和常见报错处理。 New to the command line? The Windows beginner guide (Chinese) includes a synthetic sample and troubleshooting.

  1. 安装 Python 3.10 或更新版本,安装后重新打开终端。 Install Python 3.10 or newer.

  2. 打开命令行(Windows 在开始菜单搜索"终端"或"cmd",Mac 打开"终端"),安装 ofdkit: Open a terminal and install ofdkit:

    python -m pip install --upgrade ofdkit
    python -m ofdkit --version

    如果 Windows 上 python 不可用而 py 可用,把上述 python 换成 py;macOS / Linux 通常使用 python3。下文的 ofdkit 命令也可以写成 python -m ofdkit,使用与安装时相同的 Python。 Use the same Python to install and run. python -m ofdkit also works when the ofdkit command is not on PATH.

    想用鼠标操作?运行 python -m ofdkit gui。在“查看 OFD”选文件,或在“批量复核”选文件夹或 ZIP。桌面窗口需要 Python 的 Tk 支持,可用 python -m tkinter 检查。桌面使用指南 Run python -m ofdkit gui to open the desktop window. Use python -m tkinter to check Tk support. 用 python -m ofdkit demo --gui 打开内置的三页样例,或用 python -m ofdkit doctor --check-window 检查安装和图形窗口。 Use python -m ofdkit demo --gui for an offline demo or python -m ofdkit doctor --check-window to test the installation and GUI.

  3. 看一张发票(把文件拖进命令行窗口就能填上路径): Show an invoice (drag the file into the terminal window to type its path):

    ofdkit 发票.ofd
    电子发票(普通发票)
    
    发票号码  00000000000000000001
    开票日期  2026-01-02
    购买方    测试单位甲
              税号 TESTBUYER0001
    销售方    测试单位乙
              税号 TESTSELLER0002
    金额      100.00
    税额      6.00
    价税合计  106.00
    明细      *测试*服务项目  100.00  6%
    开票人    测试人员

    (数据是虚构的 / fictional data)

  4. 看一个文件夹或 .zip 压缩包里的所有发票和合计,然后导出到 Excel: List every invoice in a folder or .zip archive with totals, then export to Excel:

    ofdkit 发票文件夹
    ofdkit batch 发票文件夹 -o 发票汇总.xlsx

    Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红,有其他提醒的发票(抬头不对、金额缺少或不是数字)标橙,都在"提醒"一栏写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行;不是数字的金额保留原样、不算进合计,合计下面会注明有几张。 The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red, other reminders such as another buyer or an amount that is missing or not a number in orange, each explained) and 明细 (one row per line item). Totals use SUBTOTAL, so they follow filters.

  5. 检查发票抬头:加上 --buyer,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次: Check who the invoices are made out to: with --buyer, invoices for another buyer name or tax ID are flagged (orange in Excel). Repeat it to check both:

    ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
  6. 按发票内容给文件改名,例如 dzfp_2411…_20240528.ofd 改成 2024-05-28_某某公司_4449.00_2411….ofd。不加 --apply 只是预览;同名的 PDF、XML 会一起改(其中一个改不了,这张发票的文件都保持原名);改名前会先写好改名记录,写不了就一个文件也不改;用 --undo 可以按记录改回去,运行几次都没关系: Rename invoice files after their contents. Without --apply it only previews; PDF and XML copies with the same name are renamed too (if one cannot be, that invoice's files all keep their names); the log is written before anything is renamed, and nothing is renamed if it cannot be; --undo restores the old names from the log and is safe to run again:

    ofdkit rename 发票文件夹            # 预览 / preview
    ofdkit rename 发票文件夹 --apply    # 改名 / rename
    ofdkit rename --undo 发票文件夹/改名记录_20261028_093000.csv

    名字的格式可以改,例如 --pattern "{开票日期}_{购买方}_{商品}"。可以用的字段:开票日期、发票号码、发票代码、发票种类、销售方、销售方税号、购买方、购买方税号、金额、税额、价税合计、商品、原文件名。 The name format can be changed with --pattern; fields are listed by ofdkit rename --help (English names such as {date}, {seller} and {total} work too).

命令行 / Command line

ofdkit 文件.ofd                              # 看发票,不是发票就显示文字 / show an invoice, or the text
ofdkit 文件夹或压缩包.zip                     # 发票列表和合计 / list invoices with totals
ofdkit batch 文件夹 -o 发票汇总.xlsx          # 导出 Excel / export to Excel
ofdkit batch 文件夹 --exclude-duplicates -o 发票汇总.xlsx  # 合计时排除一致的重复记录
ofdkit batch 文件夹 -o 发票汇总.csv           # 导出 CSV(给程序用)/ export CSV for programs
ofdkit 文件夹 --buyer 公司名或税号             # 检查发票抬头 / check the buyer
ofdkit rename 文件夹                         # 按内容改名(先预览)/ rename after contents (preview first)
ofdkit text 文件.ofd                         # 提取文字 / print text
ofdkit text 文件.ofd --pages 1,3-5 --markdown -o 摘录.md    # 提取指定页
ofdkit invoice 发票.ofd                      # 发票字段(JSON)/ invoice fields as JSON
ofdkit info 文件.ofd                         # 页数、作者等信息 / pages and metadata
ofdkit describe 文件.ofd -o 结构.json         # 打码的结构,用于报告问题 / masked structure for bug reports
ofdkit gui                                  # 打开桌面窗口 / open the desktop window
ofdkit search "付款条件" 文件夹 -r              # 跨文件查文字,显示页码和上下文
ofdkit pages 文件.ofd --pages 2-4 --runs -o 页面.json  # 导出页号、文字、尺寸和坐标
ofdkit export-text 文件夹 -r --markdown -o 文本.zip   # 批量导出文字和文件索引
ofdkit review 文件夹 --only-issues -o 复核.xlsx       # 把需要人工核对的记录单独列出
ofdkit review-diff 上次.json 本次.json               # 比较两次复核结果
ofdkit demo                                  # 试读内置样例 / read the included example
ofdkit doctor                                # 检查安装和样例 / check this installation
ofdkit doctor --file 文件.ofd -o 诊断.json           # 输出不含文件路径和正文的读取诊断

搜索和逐页导出的参数见文档工具指南。

发票复核的筛选、问题代码和表格说明见发票复核指南。

export-text 接受多个文件、文件夹或 ZIP。输出使用编号文件名,在 manifest.json 中对应原名称、ZIP 成员和读取提示。默认保留已经读出的文档,--strict 在读取不完整时保留旧报表。

show、batch 和 rename 加 -r 会连子文件夹一起找。ofdkit 文件.ofd 是 ofdkit show 文件.ofd 的简写。 Add -r to show, batch and rename to include subfolders. ofdkit PATH is short for ofdkit show PATH.

--pages 1,3-5 会按原文顺序提取第 1、3、4、5 页。合用 --markdown 时,每节保留原页码,只输出选定页的文字。 With --pages, text or Markdown contains only the selected pages, in the original order.

--exclude-duplicates 只影响金额合计。带有相同发票标识且关键信息和金额一致的记录只计一次。信息冲突或金额不全的组会全部保留在合计中,请人工核对。使用该选项时,Excel 显示整表合计,筛选时合计数不变。Excel 和 CSV 都保留所有行,CSV 的合计显示在命令行提示中。 With --exclude-duplicates, matching copies count once in totals. Conflicting or incomplete groups stay in totals for review. Excel shows a fixed whole-report total. Excel and CSV keep all rows.

导出结果请使用新文件名,保留原 OFD 和 ZIP。程序会检查输出路径,只有新文件保存完整才会替换同名旧报表。 Exports protect the source and replace an existing report only after the new file has been written in full.

ofdkit invoice 的输出示例(数据是虚构的)/ Example output (fictional data):

{
  "invoice_number": "00000000000000000001",
  "invoice_code": null,
  "issue_date": "2026-01-02",
  "check_code": null,
  "machine_number": null,
  "buyer": {"name": "测试单位甲", "tax_id": "TESTBUYER0001", "address_phone": null, "bank_account": null},
  "seller": {"name": "测试单位乙", "tax_id": "TESTSELLER0002", "address_phone": null, "bank_account": null},
  "amount_without_tax": "100.00",
  "tax_amount": "6.00",
  "total_amount": "106.00",
  "issuer": "测试人员",
  "payee": null,
  "reviewer": null,
  "note": null,
  "items": [
    {"name": "*测试*服务项目", "specification": null, "unit": null, "quantity": null,
     "unit_price": null, "amount": "100.00", "tax_rate": "6%", "tax_amount": "6.00"}
  ],
  "sources": ["custom_tags"],
  "warnings": []
}

金额是字符串,不会丢失精度。如果"合计金额 + 合计税额"不等于"价税合计",或者某个金额不是数字(比如"无法识别",这时保留原样),warnings 里会提示。汇总时只加真正的数字:0 就是 0,缺少的和不是数字的不算进合计,并单独计数(not_summed)。 Amounts are decimal strings, so no precision is lost. warnings notes totals that do not add up and amounts that are not numbers (kept as found). Summaries add only real numbers: 0 counts as 0, while missing amounts and amounts that are not numbers are left out and counted in not_summed.

在 AI 工具里使用 / Use from AI tools

MCP 服务器 / MCP server

让 Claude、Codex、Cursor 等 AI 工具直接读取 OFD 文件。需要先安装 uv。所有工具都是只读的。 Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires uv. All tools are read-only.

已在官方 MCP Registry 上架,名字是 io.github.Edgar-311/ofdkit;支持这个目录的工具可以直接搜索安装。 Listed in the official MCP Registry as io.github.Edgar-311/ofdkit; tools that read the registry can install it from there.

工具 / Tool

作用 / What it does

read_ofd_text

按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range

read_ofd_pages

结构化逐页文字和尺寸 / structured page text and dimensions

search_ofd_text

搜索本机 OFD 文档,返回页码、行号和片段 / local text search with page and line references

read_ofd_invoice

发票字段 / invoice fields

ofd_info

页数、尺寸、元数据 / pages, sizes, metadata

list_ofd_invoices

汇总文件夹里的发票,可查抬头或去重合计 / folder totals with buyer and duplicate options

review_ofd_invoices

检查金额、明细及提取问题 / check internally inconsistent fields or extraction issues

Claude Code:

claude mcp add ofdkit -- uvx --from "ofdkit[mcp]" ofdkit mcp

Claude Desktop、Cursor 等使用 JSON 配置的工具 / tools with a JSON config:

{
  "mcpServers": {
    "ofdkit": {
      "command": "uvx",
      "args": ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]
    }
  }
}

Codex(~/.codex/config.toml):

[mcp_servers.ofdkit]
command = "uvx"
args = ["--from", "ofdkit[mcp]", "ofdkit", "mcp"]

加上 --root 文件夹 可以只允许读取这个文件夹里的文件。判断的是文件的真实位置:文件夹里指向外面的快捷方式式链接(符号链接、Windows 的目录联接)不会被读取,汇总文件夹时会跳过并计数(skipped_outside_root)。 Add --root FOLDER to allow only files inside that folder. The check uses each file's real location, so symbolic links and Windows directory junctions that lead outside are not read; folder listings skip and count them (skipped_outside_root).

Agent Skill

skills/ofd-reader 告诉 AI 什么时候、怎么用 ofdkit 命令行,适用于支持 Agent Skills 的工具。把这个文件夹复制到: skills/ofd-reader tells an AI agent when and how to use the ofdkit command line. Copy the folder to:

  • Claude Code: ~/.claude/skills/ofd-reader/

  • Codex: ~/.codex/skills/ofd-reader/

MarkItDown 插件 / MarkItDown plugin

MarkItDown 是把各种文件转成 Markdown 给 AI 读的工具。安装插件后它就能读 OFD: MarkItDown converts files to Markdown for AI. With this plugin it reads OFD too:

pip install "ofdkit[markitdown]"
markitdown --use-plugins 发票.ofd

Python

import ofdkit

with ofdkit.open("发票.ofd") as doc:
    print(doc.text())
    invoice = doc.invoice()        # 不是发票时返回 None / None if not an invoice
    if invoice:
        print(invoice.invoice_number, invoice.total_amount)

# 文件夹、.zip 压缩包或多个文件 / folders, ZIP archives or several files
for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["某某有限公司"]):
    if result.invoice:
        print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "", result.buyer_mismatch)
    else:
        print(result.file, result.error)

遇到读不出的文件 / Reporting a problem

请不要把真实发票发到网上。用这个命令导出文件结构,然后附在 GitHub issue 里。文字、文件名和较长的号码会打码(汉字变成"字",数字变成"0",字母变成 x),只保留结构、坐标和 OFD 格式自己的名字(如 Doc_0、Content.xml)。打码是尽力而为,发出去之前请自己再看一遍: Please do not post real invoices. Export the structure and attach it to a GitHub issue. Text, file names and long numbers are masked; the structure, coordinates and the OFD format's own names (Doc_0, Content.xml) are kept. Masking is a best effort, so look through the file before posting it:

ofdkit describe 文件.ofd -o 结构.json

注意 / Notes

  • ofdkit 只读取文件里写了什么,不验证发票真伪。查验真伪请使用国家税务总局的发票查验平台。 ofdkit reports what a file contains. It does not verify that an invoice is genuine.

  • 文字如果是画成图形或图片的,就读不出来(需要 OCR,不在本项目范围内)。 Text drawn as shapes or images cannot be extracted (that needs OCR, which is out of scope).

  • 阅读顺序是根据位置推测的。两栏的正文会按栏读,表格按行读;版面特别复杂的页面(比如多栏加图片的杂志页)可能不完全准确。 Reading order is inferred from positions. Prose columns are read column by column and tables row by row; very complex pages (magazine layouts with pictures) may not come out perfectly.

原则 / Principles

  • 只读取 OFD,不生成、不修改发票。 Reads OFD only. It never creates or modifies invoices.

  • 本项目由 Edgar-311 维护,开发过程使用了 AI 辅助。 Edgar-311 maintains the project. Development uses AI assistance.

许可证 / License

Apache-2.0

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides intelligent OCR and PDF processing capabilities that automatically detect whether PDFs contain digital text or scanned images and apply appropriate extraction methods. Supports text extraction, OCR processing, structure analysis, and batch operations.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI applications to read and process PDF files with intelligent file search, text extraction, image processing, and optional OCR support for scanned documents.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables read-only file-management operations from AI assistants, including health checks, connection and folder listings, search, share-link resolution, metadata retrieval, and on-demand document reading.
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      Enables AI assistants to locate invoice files, extract embedded ZUGFeRD/Factur-X XML from PDF/A-3 documents, and validate compliance with § 14 UStG and EN 16931, including direct PDF invoice checks.
      3
      1
      MIT