← 返回 2026-10-30 简报

如何利用大语言模型从PDF中提取表格

How to Extract Tables from a PDF with an LLM

摘要
事件:OpenRouter发布指南,展示如何用大语言模型配合严格JSON Schema从PDF提取表格数据。 要点:测试五份PDF含扫描件,所有直接读取PDF的模型准确提取644个单元格。利用字段描述自动清理负数格式及脚注标记。 影响:开发者可低成本实现高精度表格结构化,但需注意长表截断及空结果处理,提升自动化数据处理效率。

要从 PDF 中提取表格,请将 PDF 发送给能够读取文件的模型,并附带一个描述表格单行结构的严格 JSON 模式。模型将返回带有类型信息的行数据。数量字段会返回为整数,写成 (3,878) 的损失值会返回为 -3878,而跨页的表格则会合并为一个列表返回。

我们在五个 PDF 文件上测试了此方法,其中两个是扫描件。所有直接读取 PDF 的模型都正确识别了全部 644 个单元格。测试中的失败源于 PDF 传输至模型的路径,其中两个案例返回了无错误的正常响应。

简而言之

针对单行设计的严格 JSON 模式可将 PDF 表格转换为带类型的行数据,而字段描述则能处理诸如括号内负数和脚注标记等清理工作。

在测试中,能够读取 PDF 的模型同时处理了数字文件和扫描件。无法直接读取 PDF 的模型需要借助 mistral-ocr 解析器来处理扫描件。

通过免费的 cloudflare-ai 解析器发送的扫描件会返回零行数据且无错误提示,因此应拒绝空结果。

长表格可能会因输出令牌限制而中断,因此应拒绝任何 finish_reason 为 “length” 的响应。

开始之前

运行示例需要以下内容。

一个拥有余额的 OpenRouter 账户,以及存储在 OPENROUTER_API_KEY 环境变量中的 API 密钥。本指南中使用的模型均为付费服务。

Python 3.10 或更高版本,以及 requests 包(执行 pip install requests)。

Node.js 18 或更高版本,但仅用于文末的 TypeScript 版本。

一个包含表格的 PDF 文件。它可以是数字导出文件,也可以是扫描件。

如果您之前未曾调用过该 API,快速入门指南展示了首次请求的方法。

代码适用于数字 PDF 和扫描件,但结果取决于 PDF 是否包含文本层、扫描件质量、解析器路径以及所使用的模型。示例使用了五个由已知数据生成的测试 PDF,以便将每个单元格与源数据进行核对。它们包括一张发票、一份季度报告、一个跨页的 58 行发货日志、一份扫描的采购订单,以及一个故意粗糙且包含合并单元格的扫描件。

步骤 1:如何发送 PDF 并获取行数据?

将以下内容保存为 extract_tables.py。它按照我们 PDF 输入页面的描述,将 PDF 作为文件内容部分发送,并通过结构化输出请求匹配您模式的 JSON 响应。当 strict 设置为 true 时,支持严格模式的提供商会将输出限制在模式范围内,因此每一行都包含具有正确类型的所有字段。各提供商的支持情况各不相同,结构化输出页面展示了如何仅路由至支持该功能的提供商。

import base64
import json
import os

import requests

API = "https://openrouter.ai/api/v1/chat/completions"
HEADERS = { "Authorization" : f "Bearer { os.environ[ 'OPENROUTER_API_KEY' ] } " }

def rows_schema (fields):
"""将单行的字段包装在用于 {"rows": [...]} 的严格模式中。"""
return {
"type" : "object" ,
"properties" : { "rows" : { "type" : "array" , "items" : {
"type" : "object" , "properties" : fields,
"required" : list (fields), "additionalProperties" : False }}},
"required" : [ "rows" ],
"additionalProperties" : False ,
}

def extract_table (pdf_path, schema, model = "anthropic/claude-haiku-5.5" ,
engine = None , max_tokens = 8000 ):
with open (pdf_path, "rb" ) as f:
data_url = "data:application/pdf;base64," + base64.b64encode(f.read()).decode()
body = {
"model" : model,
"max_tokens" : max_tokens,
"messages" : [{ "role" : "user" , "content" : [
{ "type" : "text" , "text" : "提取此 PDF 中表格的每一行。"
"包括每一页的行。"
"仅返回文档中的行。" },
{ "type" : "file" , "file" : { "filename" : os.path.basename(pdf_path),
"file_data" : data_url}},
]}],
"response_format" : { "type" : "json_schema" ,
"json_schema" : { "name" : "table" , "strict" : True ,
"schema" : schema}},
}
if engine:
body[ "plugins" ] = [{ "id" : "file-parser" , "pdf" : { "engine" : engine}}]

response = requests.post(API, headers=HEADERS, json=body, timeout=300)
response.raise_for_status()
data = response.json()
choice = data["choices"][0]
if choice["finish_reason"] == "length":
raise ValueError(f"Output stopped at max_tokens={max_tokens}. "
"Raise it or split the PDF.")
rows = json.loads(choice["message"]["content"])["rows"]
if not rows:
raise ValueError("No rows came back. If this PDF is a scan, use a model "
"that reads PDFs or engine='mistral-ocr'.")
return rows, data["usage"]["cost"]

LINE_ITEMS = rows_schema({
"sku": {"type": "string"},
"description": {"type": "string"},
"qty": {"type": "integer"},
"unit_price": {"type": "number",
"description": "USD, no currency symbol or thousands separator"},
"amount": {"type": "number",
"description": "USD, no currency symbol or thousands separator"},
})
return 之前的两个检查捕获了步骤 3 和 4 中涵盖的失败情况,因此请保留它们。成本来自 usage.cost,使用量会计将包含在每个响应中。

在发票上运行该函数。

from extract_tables import extract_table, LINE_ITEMS

rows, cost = extract_table("invoice.pdf", LINE_ITEMS)
for row in rows[:3]:
print(row)
print(f"{len(rows)} rows, ${cost:.5f}")
{'sku': 'NW-4100', 'description': 'Hex bolt M8x40', 'qty': 100, 'unit_price': 60.67, 'amount': 6067.0}
{'sku': 'NW-4107', 'description': 'Flange nut M8', 'qty': 2, 'unit_price': 41.72, 'amount': 83.44}
{'sku': 'NW-4114', 'description': 'Bearing 6204-2RS', 'qty': 10, 'unit_price': 52.59, 'amount': 525.9}
10 rows, $0.00067
调用耗时约六秒。PDF 显示为 6,067.00,而该行数据为 6067.0,这是一个无需清理即可直接相加的数字。字段 description 的作用是去除千位分隔符。

PDF 表格所需的大部分清理工作都可以放入 schema 的字段描述中。我们的季度报告有一个横跨四个季度列的“Fiscal 2026”标题,亏损用括号表示,并且在两个细分名称(Enterprise 和 Hardware resale)上有脚注标记。字段描述处理了括号和脚注标记。跨页标题不需要描述,因为字段名称已经说明了每个值所属的季度。

from extract_tables import extract_table, rows_schema

THOUSANDS = {"type": "integer",
"description": "Thousands of USD. A value in parentheses, like (1,204), is negative: -1204."}
QUARTERLY = rows_schema({
"segment": {"type": "string", "description": "Segment name without footnote markers"},
"q1": THOUSANDS, "q2": THOUSANDS, "q3": THOUSANDS, "q4": THOUSANDS, "fy_total": THOUSANDS,
})

rows, cost = extract_table("quarterly.pdf", QUARTERLY)
for row in rows:
print(row)
{'segment': 'Inference API', 'q1': 1813, 'q2': 7299, 'q3': 1612, 'q4': 4422, 'fy_total': 15146}
{'segment': 'Enterprise', 'q1': 1563, 'q2': 2981, 'q3': 5544, 'q4': 7667, 'fy_total': 17755}
{'segment': 'Data products', 'q1': 3163, 'q2': 9658, 'q3': 2729, 'q4': 5854, 'fy_total': 21404}
{'segment': 'Hardware resale', 'q1': 3761, 'q2': -3878, 'q3': -9774, 'q4': -1776, 'fy_total': -11667}
{'segment': 'Professional services', 'q1': 8933, 'q2': 9511, 'q3': 7805, 'q4': 5946, 'fy_total': 32195}
{'segment': 'Total operating income', 'q1': 19233, 'q2': 25571, 'q3': 7916, 'q4': 22113, 'fy_total': 74833}
在 Hardware resale 行中,(3,878) 返回为 -3878,且两个细分名称中的脚注标记均已消失。

沿列延伸的合并单元格也是同样的处理方式。在我们粗糙的扫描中,每个 Category 单元格横跨六到九行。我们将该字段描述为“第一列中的类别。它是一个合并单元格,因此在它覆盖的每一行上重复显示。”在我们的测试中,这对于所有三个读取 PDF 的模型来说都足够了,它们在所有 30 行上都填充了类别信息。

步骤 3:我应该使用哪种解析器路径?

如果模型能够读取文件,我们直接将 PDF 传递给它。如果无法读取,我们先解析 PDF,然后将结果发送给模型。file-parser 插件的 engine 设置用于选择解析器。当你在无法读取文件的模型上未设置该选项时,我们会使用 mistral-ocr,正如 PDF 输入页面所述。根据你的 PDF 内容选择合适的路由方式。

能够读取 PDF 的模型:不设置 engine。Claude Haiku 5.5、GPT-6 Luna 和 Gemini 3.8 Flash 均支持文件读取,且这三者都成功处理了我们的两份扫描件。PDF 作为输入 token 计费。

无法读取 PDF 但配备 OCR 的模型:使用 engine="mistral-ocr",或不设置该选项。它首先对每一页运行光学字符识别(OCR),费用为每 1,000 页 2 美元,此外还需支付模型的 token 费用。

无法读取 PDF 但使用免费解析器的模型:仅在每个 PDF 都包含文本层时使用 engine="cloudflare-ai"。导出的发票和报告通常包含文本层,而扫描件则不包含。

以下是发送给 deepseek/deepseek-v4.1-flash 的扫描采购订单,分别使用每种解析器处理。该模型接受图像但不接受文件,因此 PDF 必须经过解析器处理。

from extract_tables import extract_table, LINE_ITEMS

# 无法读取 PDF 但前置 OCR 的模型
rows, cost = extract_table( "scanned.pdf" , LINE_ITEMS ,
model = "deepseek/deepseek-v4.1-flash" , engine = "mistral-ocr" )
print ( f "mistral-ocr: {len (rows) } rows, $ { cost :.5f } " )

# 同一模型使用免费的文本解析器
rows, cost = extract_table( "scanned.pdf" , LINE_ITEMS ,
model = "deepseek/deepseek-v4.1-flash" , engine = "cloudflare-ai" )
mistral-ocr: 6 rows, $0.00211
ValueError: No rows came back. If this PDF is a scan, use a model that reads PDFs or engine='mistral-ocr'.

该 ValueError 来自步骤 1 中的空行检查。如果没有此检查,第二次调用将返回 200 OK,状态为 finish_reason: "stop",内容为 {"rows": []}。解析器在扫描件中未找到任何文本,模型也正确报告了空表。由于没有引发错误,缺少该检查的流水线会存储零行并继续处理下一个文件。这是两个静默失败中的第一个。我们的粗略扫描件表现相同,30 行中得分为 0。

另外两种路由错误会抛出明显异常。拼写错误的 engine 名称返回以下错误:

400 {"error":{"message":"plugins.0.pdf.engine: Invalid input","code":400}}

原生引擎仅适用于能够读取文件的模型。当我们无论如何都在 DeepSeek V4.1 Flash 上设置 engine="native" 时,请求成功了一次,随后两次因提供商错误而失败:

400 Provider returned error: "The request was rejected. Possible causes: input exceeds the model's maximum context length, or the request contains invalid parameters."

在相同模型上不设置 engine 选项时,我们两次尝试均成功,因此不要对无法读取文件的模型设置 native。

步骤 4:为什么我的长表格被截断了?

模型写入的每一行都会消耗输出 token,因此长表格需要较高的 max_tokens。我们的 58 行发货日志根据模型不同,使用了 2,500 到 7,700 个输出 token,这导致最冗长的模型在 extract_table 默认的 8,000 限制下几乎没有剩余空间。平均每行消耗 43 到 133 个 token。对于长表格,建议从每预期行约 150 个 token 开始。然后测量你自己的行数并保留 finish_reason 检查,因为计数因模型和模式而异。以下是限制过低时会发生的情况:

from extract_tables import extract_table, rows_schema

SHIPMENTS = rows_schema({
"date" : { "type" : "string" , "description" : "YYYY-MM-DD" },
"shipment_id" : { "type" : "string" },
"origin" : { "type" : "string" },
"destination" : { "type" : "string" },
"weight_kg" : { "type" : "number" , "description" : "No thousands separator" },
"status" : { "type" : "string" },
})

rows, cost = extract_table( "shipments.pdf" , SHIPMENTS , max_tokens = 600 )
ValueError: Output stopped at max_tokens=600. Raise it or split the PDF.
Without the finish_reason check, this request fails in one of two ways. Plain JSON parsing raises an error on the cut-off array.

JSONDecodeError: Unterminated string starting at: line 1 column 627 (char 626)
The second way is the other silent failure. With the Response Healing plugin turned on, the JSON parses and you get 5 rows of 58 with no exception. Healing repairs the syntax of the output, and its docs warn that it can’t recover output cut off by max_tokens , so it can’t add the rows the model never wrote. The finish_reason check catches both cases.

Step 5: How do I write the rows to CSV?

Every row has the keys defined in the schema, so csv.DictWriter can take its column names from the schema and write the rows as they are. Excel opens the result directly.

import csv

from extract_tables import extract_table

Define SHIPMENTS here, copied from step 4

rows, cost = extract_table( "shipments.pdf" , SHIPMENTS , model = "openai/gpt-6-luna" )
with open ( "shipments.csv" , "w" , newline = "" ) as f:
fieldnames = list ( SHIPMENTS [ "properties" ][ "rows" ][ "items" ][ "properties" ])
writer = csv.DictWriter(f, fieldnames = fieldnames)
writer.writeheader()
writer.writerows(rows)
print ( f "Wrote {len (rows) } rows to shipments.csv ($ { cost :.5f } )" )
Wrote 58 rows to shipments.csv ($0.00130)

date,shipment_id,origin,destination,weight_kg,status
2026-09-01,SHP-88200,Savannah,Valencia,8754.6,In transit
2026-09-01,SHP-88213,Busan,Los Angeles,2074.7,Customs hold
The table ran onto a second page with its header repeated there. The CSV has one header and all 58 rows.

Which model should you use?

We ran each route once over all five PDFs, which came to six pages and 644 cells, and compared every cell with the data the PDFs were generated from. Every run used the extract_table function and prompt above, with our default provider routing. The cost per 1,000 pages is the total usage.cost for the six pages, scaled up. The models and prices are from our model catalog as of October 8, 2026. These results describe this test set, not model performance in general.

On this test set, GPT-6 Luna and Claude Haiku 5.5 were the cheapest routes that got every cell right, including on the rough scan, and both list at $0.10 per million input tokens. That makes them a reasonable first test on your own PDFs. Gemini 3.8 Flash was just as accurate but cost eight to ten times as much per page on the same files. Its list price is $1.50 per million input tokens, discounted to $0.75 on October 21, 2026.

The OCR route costs more than DeepSeek’s low token price suggests, because the $2 per 1,000 pages for OCR is added to every request, and you can see it in usage.cost . Its two misses were the footnote markers on Enterprise and Hardware resale, which it kept even though the schema asked for them to be removed. The free parser got all three digital PDFs right and both scans completely wrong.

The cost column is extrapolated from six pages per route. Use it to compare routes, then measure accuracy, time and cost on a sample of your own PDFs before you choose one, using a golden eval set , because denser pages cost more and other layouts may behave differently.

When is a PDF library enough?

If all your PDFs are digital and each table has a single header row, a free library such as pdfplumber will find the tables. We ran it on the same files. It found every table in the three digital PDFs and returned each cell as a string, such as ‘6,067.00’ or ‘(3,878)’. The quarterly report’s two-level header came back as two rows with None in the merged cells, and the shipment log came back as two separate tables, one per page. It found nothing in either scan, because a scan has no text layer to read.

当你的表格结构较为简单且 PDF 文件为数字格式时,使用一个库就足够了。一旦你需要编写用于处理合并表头、分页符和数字格式的清理代码,第二步中的模式在维护上会显得更为轻松。

TypeScript 中的相同请求

请求体在任何语言中都是相同的。将其保存为 extract.mjs,并在 Node.js 18 或更高版本中通过运行 node extract.mjs invoice.pdf 来执行。

import { readFileSync } from "node:fs" ;
import { basename } from "node:path" ;

const path = process.argv[ 2 ];
const fileData = data:application/pdf;base64,${ readFileSync ( path ). toString ( "base64" ) }

本条评分 9.9 score-v1
  • 来源权威 8
    注册表 priority=8(OpenRouter)
  • 时效 1.945
    发布 22.5 小时前,衰减到 1.94/3.0
  • 多源印证 0
    只有 1 家在报(无旁证)
  • 社区信号 0
    无社区数据(本管线走 RSS,HN 的 hn_fetcher 未接入)

首次收录 · 2026-10-30 · 9.95 分

原文链接:https://openrouter.ai/blog/tutorials/extract-tables-from-pdf-llm/
来源:OpenRouter
以上内容由 AI 自动翻译,仅供参考。
← 返回简报