68 lines
2.5 KiB
Markdown
68 lines
2.5 KiB
Markdown
# PDF 批注修复脚本(pymupdf/fitz)
|
|
|
|
## 用途
|
|
修复已生成的 PDF 合同批注中的颜色不一致和内容问题。
|
|
|
|
## 使用场景
|
|
- workflow 生成的 PDF 批注中 Highlight 和 Text 注解颜色不一致
|
|
- 批注内容过于空洞(只说"请核实"不给建议)
|
|
- 需要统一所有批注为同一颜色
|
|
|
|
## 修复脚本
|
|
|
|
```python
|
|
import fitz
|
|
|
|
UNIFIED_COLOR = [1.0, 1.0, 0.0] # 统一黄色
|
|
|
|
doc = fitz.open("input.pdf")
|
|
|
|
for page_num in range(doc.page_count):
|
|
page = doc[page_num]
|
|
for annot in page.annots():
|
|
# 1. 统一颜色
|
|
current = annot.colors['stroke']
|
|
if current != UNIFIED_COLOR:
|
|
annot.set_colors(stroke=UNIFIED_COLOR)
|
|
annot.update()
|
|
|
|
# 2. 修复 Text 注解内容(按需)
|
|
if annot.type[0] == 0: # Text annotation
|
|
content = annot.info.get("content", "")
|
|
if "请核实" in content and "建议" not in content:
|
|
# 替换为有实质内容的建议
|
|
new_content = fix_annotation_content(content)
|
|
rect = annot.rect
|
|
color = annot.colors['stroke']
|
|
page.delete_annot(annot)
|
|
new_annot = page.add_text_annot(rect.tl, new_content)
|
|
new_annot.set_colors(stroke=color)
|
|
new_annot.set_info(title="WB")
|
|
new_annot.update()
|
|
|
|
doc.save("output.pdf")
|
|
doc.close()
|
|
```
|
|
|
|
## 验证
|
|
```python
|
|
# 验证所有批注颜色一致
|
|
doc = fitz.open("output.pdf")
|
|
colors = set()
|
|
for page in doc:
|
|
for annot in page.annots():
|
|
colors.add(tuple(annot.colors['stroke']))
|
|
assert len(colors) == 1, f"Found {len(colors)} different colors"
|
|
doc.close()
|
|
```
|
|
|
|
## 注意事项
|
|
- pymupdf 的 `annot.info["content"]` 修改后需要 `delete_annot` + `add_text_annot` 重建才能生效
|
|
- 直接设置 `annot.info["content"] = new_value` + `annot.update()` 对某些 PDF 不生效
|
|
- 颜色统一后必须清 OnlyOffice 缓存:`docker exec nextcloud-onlyoffice-1 bash -c "rm -rf /var/lib/onlyoffice/documentserver/App_Data/cache/files/data/*"`
|
|
|
|
## 2026-06-29 实证
|
|
医疗急救中心救护车采购合同 PDF,14对批注中6对颜色不一致(Highlight 黄色 + Text 红色)。修复后全部统一为黄色。同时修复了2处空洞批注:
|
|
- "验收方式未勾选,请选择(1)或(2)" → "验收方式未勾选,建议选择第(1)种方式(买方收货后自行检查验收)"
|
|
- "质量保证期月数未填写,请填写具体月数" → "质量保证期月数未填写,请根据招标文件要求填写具体月数"
|