翻篇收录说明
翻篇网页快照

How to Extract Tables from a PDF with an LLM (Python)

https://openrouter.ai/blog/tutorials/extract-tables-from-pdf-llm/

最近抓取:2026-12-04 13:14:14(北京时间)

最近内容变化:2026-12-01 20:41:01(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Extract tables from a PDF with an LLM in Python: send the PDF with a JSON schema, get typed rows, and catch the two failures that return no error.

正文摘录

How to Extract Tables from a PDF with an LLMOpenRouter ·10/29/2026Tl;drTl;drBefore you startStep 1: How do I send a PDF and get rows back?Step 2: How do I handle merged cells, parentheses and footnotes?Step 3: Which parser route should I use?Step 4: Why did my long table come back cut off?Step 5: How do I write the rows to CSV?Which model should you use?When is a PDF library enough?The same request in TypeScriptConclusionFrequently asked questionsNext stepsTo extract tables from a PDF with an LLM, send the PDF to a model that can read files, together with a strict JSON schema that describes one row of the table. The model returns typed rows. Quantities come back as integers, a loss written as (3,878) comes back as -3878, and a table that runs across two pages comes back as one list. We tested this on five PDFs, two of them scans. Every model that read the PDF directly got all 644 cells right. The failures in our tests came from the route the PDF took to reach the model, and two of them returned a normal response with no error. Tl;dr A strict JSON schema for one row turns a PDF table into typed rows, and field descriptions handle cleanup such as negatives in parentheses and footnote markers. Models that read PDFs handled both digital files and scans in our tests. A model that can’t read PDFs needs the mistral-ocr parser for scans. A scan sent through the free cloudflare-ai parser returns zero rows with no error, so reject empty results. Long tables can stop at the output token limit, so reject any response whose finish_reason is “length”. Before you start You need the following to run the examples. An OpenRouter account with credits, and an API key stored in the OPENROUTER_API_KEY environment variable. The models in this guide are paid. Python 3.10 or later and the requests package (pip install requests). Node.js 18 or later, but only for the TypeScript version near the end. A PDF that contains a table. It can be a digital export or a scan. If you haven’t called the API before, the quickstart shows a first request. The code works with digital PDFs and scans, but results depend on whether the PDF has a text layer, the scan quality, the parser route and the model. The examples use five test PDFs that we generated from known data, so that every cell could be checked against the source. They are an invoice, a quarterly report, a 58-row shipment log that runs onto a second page, a scanned purchase order, and a deliberately rough scan with merged cells. Step 1: How do I send a PDF and get rows back? Save the following as extract_tables.py. It sends the PDF as a file content part, as described on our PDF inputs page, and asks for JSON that matches your schema through structured outputs. With strict set to true, providers that support strict mode hold the output to the schema, so every row has every field with the right type. Support varies by provider, and the structured outputs page shows how to route only to providers that support it. 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): """Wrap the fields of one row in a strict schema for {"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": "Extract every row of the table in this PDF. " "Include rows from every page. " "Return only rows that are in the document."}, {"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"}, }) The two checks before the return catch the failures covered in steps 3 and 4, so leave them in. The cost comes from usage.cost, which usage accounting includes in every response. Run the function on the invoice. 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 The call took about six seconds. The PDF shows 6,067.00, and the row holds 6067.0, which is a number you can add up without cleaning it first. The field description is what removed the thousands separator. Step 2: How do I handle merged cells, parentheses and footnotes? Most of the cleanup a PDF table needs can go into the field descriptions of the schema. Our quarterly report has a “Fiscal 2026” header that spans four quarter columns, losses written in parentheses, and footnote markers on two segment names (Enterprise and Hardware resale). Field descriptions handle the parentheses and the footnote markers. The spanning header needs no description, because the field names already say which quarter each value belongs to. 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} In the Hardware resale row, (3,878) came back as -3878, and the footnote markers are gone from both segment names. A merged cell that runs down a column works the same way. In our rough scan, each Category cell spans six to nine rows. We described that field as “The category in the first column. It is a merged cell, so repeat it on every row it covers.” In our test, that was enough for all three models that read PDFs to fill in the category on all 30 rows. Step 3: Which parser route should I use? If a model can read files, we pass the PDF to it directly. If it can’t, we parse the PDF first and send the model the result. The engine setting of the file-parser plugin chooses the parser. When you leave it unset on a model that can’t read files, we use mistral-ocr, as the PDF inputs page states. Choose the route by what your PDFs look like. A model that reads PDFs. Leave engine unset. Claude Haiku 5.5, GPT-6 Luna and Gemini 3.8 Flash all read files, and all three handled both of our scans. The PDF is billed as input tokens. A model that can’t read PDFs, with OCR. Use engine="mistral-ocr", or leave it unset. It runs optical character recognition (OCR) on each page first, for $2 per 1,000 pages on top of the model’s tokens. A model that can’t read PDFs, with the free parser. Use engine="cloudflare-ai" only if every PDF has a text layer. Exported invoices and reports have one. Scans don’t. Here is the scanned purchase order sent to deepseek/deepseek-v4.1-flash with each parser. That model accepts images but not files, so the PDF has to go through a parser. Images, files and every other modality run through one API on OpenRouter, so switching usually means changing the model string and the content type. from extract_tables import extract_table, LINE_ITEMS # A model that can't read PDFs, with OCR in front of it 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}") # The same model with the free text parser 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'. That ValueError comes from the empty-rows check in step 1. Without the check, the second call returns 200 OK with finish_reas