PDF Batch Processing: The Only 'Done' Is a Second Extraction's Count
Handling a Batch of PDFs — How Do You Know It's Really Done?
Batch processing PDFs, the fear is when script finishes silently, you don't know if any page was quietly missed.
So you need to lay out the places to check: how to verify after splitting pages, which pages had no text extracted, whether text still exists after covering, and which files on the checklist need separate marking.
Every step's output is re-extracted once. Script not erroring and output files all present don't count; only the numbers from the second extraction speak.
Below we go through 5 course materials: course papers, exercise notes, past exemplars — before archiving, we need to split pages, extract tables, cover author info and answer pages.
1. First classify by "if wrong, can we redo?"
To decide how strict each verification needs to be, first separate the tasks by one thing: if you mess up, can you re-run to fix it?
5 mock materials: 4 complete, 1 is a file that was partway downloaded and not finished.
raw = path.read_bytes()
if not raw.startswith(b"%PDF-") or b"%%EOF" not in raw:
raise ValueError("文件不完整,打不开")
待归档文件 5 份: ['下载中断.pdf', '习题讲义_01.pdf', '往届范文.pdf', '课程论文_01.pdf', '课程论文_02.pdf']
按「错了能不能重来」分两组:
可逆:拆分页数、抽取文本、生成清单 → 发现不对重跑一次就行
不可逆:遮盖作者信息与答案 → 归档公开后收不回来,必须验完再发
| 分组 | 包含的活 | 错了会怎样 |
|---|---|---|
| 可逆 | 拆分页数、抽取文本、生成清单 | 发现不对,重跑一次就行 |
| 不可逆 | 遮盖作者信息、答案页 | 归档公开后收不回来 |
The two check lines above are the first gate before grouping: 下载中断.pdf stops at %%EOF, throws ValueError, the checklist's "can open" becomes "No".
PDF has a feature that makes this more troublesome: unlike a table where a missing row is visible at a glance, a page is just a container; text hides in the content stream, and after modification, the appearance shows almost no difference. So "looks fine" is especially unreliable on such files.
Grouping isn't for nice classification; it decides how strictly to verify each step.
Reversible group mistakes just waste time; irreversible group if not caught, the material has already been sent out.
So the order of the next three sections is increasing risk, not operation order——these tasks have no sequential dependency; splitting doesn't need to wait for extraction, and the checklist doesn't need to wait for covering.
2. After splitting, do page counts match?
In the reversible group, start with the task least likely to go wrong: split a 5-page handout into 3 parts every 2 pages, getting 2, 2, 1 pages, summing to 5.
How to stitch files, how to write page numbers — not discussed; what's discussed is what to use to verify.
declared = int(re.search(r"/Count\s+(\d+)", text).group(1))
page_objs = len(re.findall(r"/Type\s*/Page\b", text))
原文件页数(数内容流): 5 → 拆成 3 份: [2, 2, 1] ;相加 = 5
核对: 对得上
课程论文_02:/Count 声明 3 页, 全文扫到 /Type /Page 对象 4 个 → 不一致,得查
The pitfall is in the last line. /Count declares 3 pages, but scanning the whole text finds 4 /Type /Page objects — the extra one is an orphan object not attached to the page tree.
PDF allows incremental updates to leave such residue; readers open normally, but a script that only trusts the declared value will miss it. So verifying page count must count actual content streams, not just the number in metadata. When splitting by "every N pages", the last part with fewer than N pages is also most easily missed in a loop; the output [2, 2, 1] ; sum = 5 step cannot be skipped.
The 3 split parts are written to the output directory, page count matches, only then is this step done. But "matches" only means no pages lost, not that all content on the pages was retrieved.
3. Which pages extracted nothing?
Page count matches, but one more step: check how much text each page actually extracted.
Text in PDF isn't pixels; it's a series of encodings in the content stream, like <FEFF...> Tj.
The extractor's job is to find these strings and decode them back to text.
for s in streams:
lines = [ln for ln in s.split("\n") if "Tj" in ln]
if not lines:
empty_pages += 1
习题讲义_01.pdf:5 页里 2 页没抽出任何文字
合计没抽出文字的页: 2 → 空字符串不等于「这页是空的」,可能整页是扫描图
Running through, 2 of the 5 pages in the handout extracted zero text; these two pages are scanned versions, whole page is just an image, no text layer.
The trouble is the extractor doesn't report an error for this; it just silently returns an empty string.
If you treat an empty string as "this page has no content" and skip it, the checklist would never show these two pages exist.
So pages without a text layer must be counted and flagged separately, not mixed into normal results. As for whether those two pages go to OCR or human review, the script doesn't decide; it just flags them — only flags, doesn't delete for you — a rule repeated throughout this whole flow.
That's also why this step comes before covering: you need to know which pages were never read before you can talk about whether covering went right.
4. Covered doesn't mean deleted
After the two reversible checks, it's the irreversible group's turn.
Need to cover: author's name, student ID, reference answers and explanations — 5 places in this material.
Make two versions: one draws a black rectangle in that area, leaving the text line; the other removes the entire line of Tj containing the sensitive term.
if sensitive:
drawn_lines.append("0 0 0 rg 45 762 500 20 re f") # 只盖一层黑框
removed_lines.append("") # 真删:连 Tj 一起去掉
After generating both, extract text again and count sensitive words. Script prints:
遮盖前文本层里的敏感词: 5 处
只画黑框后,再抽一次: 5 处 → 看着盖住了,文字还在
真正删掉 Tj 后,再抽一次: 0 处
结论: 遮住了不等于删掉了
The black-box version looks tightly covered, but re-extracting still shows 5 occurrences; the text remains in the content stream, and search, copy, or any extraction script can pull it out as-is. The reason: in PDF, text and graphics are two layers; the rectangle just sits on top, not touching the text beneath.
The true deletion version removes that Tj line; re-extraction gives 0.
This "overlay a graphic" practice is common; many editors' redaction tools are implemented that way, exporting with the underlying text untouched.
So verification can't be a human eye sweep; it must be a second extraction baked into the script: every time after covering, automatically count again; count to 0 is pass. This is the most concrete layer of "how do you know it's really done": the file is generated, the page looks right — none of that counts; extract once more, the numbers decide. If the reversible group isn't caught, worst case is re-running; if this group isn't caught, the material is already public.
5. Checklist and silent failures
After verifying each item, gather all file results into a checklist; script prints:
| 文件 | 实际页 | 无文本层页 | 能打开 | 备注 |
|---|---|---|---|---|
| 下载中断.pdf | — | — | 否 | 文件不完整 |
| 习题讲义_01.pdf | 5 | 2 | 是 | 含扫描页 |
| 往届范文.pdf | 2 | 0 | 是 | — |
| 课程论文_01.pdf | 4 | 0 | 是 | — |
| 课程论文_02.pdf | 3 | 0 | 是 | 元数据与页面对象数不一致 |
print("标记出来的:",
[r["文件"] for r in table if r["备注"] or r["能打开"] == "否"])
标记出来的: ['下载中断.pdf', '习题讲义_01.pdf', '课程论文_02.pdf']
3 of 5 are flagged: one can't open, one has two pages never read, one metadata mismatch.
None of these three cases would make the script error, and the output files are all present — silent failure is most easily mistaken for success. The checklist, besides page count and byte count, deliberately has "can open", "pages without text layer", "notes" columns to prevent them from staying silent.
Inside the script, "declared page count" and "page object count" are also kept as two separate values: for 课程论文_02, 3 vs 4, the two numbers fighting is itself a signal; if merged into one column, it becomes invisible.
There's also an awkward ordering: the checklist should actually run first. Knowing which files don't open and which are entirely scanned before deciding how to split, extract, and whether to OCR first is far more sensible than discovering it after processing everything. Writing it as a closing report wastes a step.
6. Wire it into one entry
With the verifications and checklist ready, finally gather them into one entry.
Each of the five steps is a function; run_pipeline runs them in order, clearing the output directory before re-running to avoid old split files mixing into the checklist.
files = overview(cfg)
split_check(cfg)
extract_check(cfg)
cover_check(cfg)
inventory(cfg, files)
The output directory leaves 3 split PDFs, two covered PDF versions, and one 清单.csv.
The few dozen lines of boilerplate for generating these minimal PDFs and parsing content streams are in pdf_pipeline.py, not pasted here — it uses a standard Chinese font object and UTF-16 encoded content streams, producing structurally valid PDFs, but the positioning is only "make the text layer visible"; normal PDF readers may not open them, which is expected.
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
The step of re-extracting text after redaction cannot be skipped.