微算力 · API 导航与自营网关
API 接入 EN
未登录登录
📄

PDF 全栈处理专家

Pdf · v1.0.0
办公 安全 S 级 作者 yang1002378395-cmyk 公开目录收录
1.8k 下载 0 安装 8.3k 收藏 21 浏览

简介

一站式 PDF 处理工具,支持读取、合并、拆分、提取文本表格、OCR、加密及创建 PDF,覆盖个人办公与自动化场景。

原始描述

Use this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multipl...

通过你的 Agent 添加

点「快速安装」复制一段指令,粘给你正在用的 Agent(Claude Code、Codex、OpenClaw 等),它会自己完成安装。

或者手动安装

Claude Codeunzip -o skill.zip -d ~/.claude/skills/pdf-27138/
其它 Agent解压到它自己的 skills 目录,目录名用 pdf-27138

包里是 SKILL.md 加作者附带的文件,解压后目录名就是技能名。 技能申请的权限由作者决定,装之前请确认它能读什么、能执行什么。

中文使用说明 来自收录源

核心用法

该Skill是PDF文档处理的完整解决方案,覆盖PDF生命周期的全场景操作。核心能力分为六大模块:文档读取与解析(使用pypdf读取元数据、提取文本、遍历页面结构)、内容提取(pdfplumber实现精准文本布局保留与表格结构化提取)、文档创建(reportlab生成复杂格式PDF,支持段落排版、多页文档、上下标特殊字符)、批量操作(合并、拆分、旋转页面、添加水印)、安全处理(密码加密/解密、权限控制)、图像与OCR(扫描件文字识别、图片提取)。命令行工具链(pdftotext、qpdf、pdftk)提供无Python环境的快速操作能力。

使用模式遵循"分析→选择工具→执行"的流程:首先判断任务类型(纯文本提取选pdfplumber,创建新文档选reportlab,简单操作选pypdf),然后调用对应代码模板或CLI命令,最后验证输出结果。OCR场景需预装tesseract引擎,表格提取支持自动转为pandas DataFrame并导出Excel。

显著优点

技术栈成熟可靠:pypdf/pdfplumber均为BSD/MIT许可的活跃项目,reportlab是Python PDF生成的事实标准,无授权风险。纯本地安全架构:零网络通信设计,敏感文档无需上传云端,满足金融、法律、医疗等强合规场景。功能覆盖完整:从简单读到复杂创建,从标准PDF到扫描件OCR,从单文件到批量处理,形成闭环能力。输出质量专业:保留原文档布局信息,表格提取支持行列对齐修复,生成PDF内置14种标准字体保障跨平台显示一致性。

潜在缺点与局限性

字体渲染限制:reportlab默认字体不包含Unicode上下标字符(如₂、⁵),必须用XML标签(/)替代,否则显示为黑框。OCR依赖外部引擎:pytesseract需单独安装tesseract-ocr二进制,Windows配置较复杂,且识别准确率受扫描质量影响。复杂表格识别局限:跨页表格、嵌套表头、单元格合并等场景可能提取错位,需人工校验。PDF标准兼容性:部分非标准生成器(如某些CAD导出)的PDF可能出现结构解析异常。性能瓶颈:大文件(>500页)或高分辨率扫描件的OCR处理耗时显著,内存占用较高。

适合的目标群体

知识工作者:研究人员提取论文数据表、法务人员批量处理合同、财务人员整合报表。开发者与数据工程师:构建文档自动化流水线、企业内容管理系统集成、RPA流程中的PDF处理节点。教育与出版领域:试卷生成、教材排版、学术资料数字化归档。中小型企业IT:替代Adobe Acrobat的授权成本,实现内部文档流程自动化。隐私敏感用户:医疗病历、金融对账单等机密文档的本地化处理需求者。

使用风险与注意事项

输入验证风险:当前实现未严格校验文件路径有效性,极端路径构造可能导致非预期文件访问(已在安全报告中列为LOW级风险)。建议用户确保传入参数来源可信。权限管理:Skill需要文件系统读写权限,处理多租户或共享环境时应配置目录隔离沙箱。依赖版本冲突:pypdf 3.x与2.x API不兼容,pdfplumber对Pillow版本敏感,建议使用虚拟环境并锁定requirements.txt。数据丢失风险:加密/解密、合并拆分等操作直接覆盖原文件逻辑,重要文档操作前务必备份。OCR准确性免责声明:法律场景下的扫描件OCR结果需人工复核,不可作为单一证据来源。

技能正文


name: pdf description: Use this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill. license: Proprietary. LICENSE.txt has complete terms

PDF Processing Guide

Overview

This guide covers essential PDF processing operations using Python libraries and command-line tools. For advanced features, JavaScript libraries, and detailed examples, see REFERENCE.md. If you need to fill out a PDF form, read FORMS.md and follow its instructions.

Quick Start

from pypdf import PdfReader, PdfWriter

# Read a PDF
reader = PdfReader("document.pdf")
print(f"Pages: {len(reader.pages)}")

# Extract text
text = ""
for page in reader.pages:
    text += page.extract_text()

Python Libraries

pypdf - Basic Operations

Merge PDFs

from pypdf import PdfWriter, PdfReader

writer = PdfWriter()
for pdf_file in ["doc1.pdf", "doc2.pdf", "doc3.pdf"]:
    reader = PdfReader(pdf_file)
    for page in reader.pages:
        writer.add_page(page)

with open("merged.pdf", "wb") as output:
    writer.write(output)

Split PDF

reader = PdfReader("input.pdf")
for i, page in enumerate(reader.pages):
    writer = PdfWriter()
    writer.add_page(page)
    with open(f"page_{i+1}.pdf", "wb") as output:
        writer.write(output)

Extract Metadata

reader = PdfReader("document.pdf")
meta = reader.metadata
print(f"Title: {meta.title}")
print(f"Author: {meta.author}")
print(f"Subject: {meta.subject}")
print(f"Creator: {meta.creator}")

Rotate Pages

reader = PdfReader("input.pdf")
writer = PdfWriter()

page = reader.pages[0]
page.rotate(90)  # Rotate 90 degrees clockwise
writer.add_page(page)

with open("rotated.pdf", "wb") as output:
    writer.write(output)

pdfplumber - Text and Table Extraction

Extract Text with Layout

import pdfplumber

with pdfplumber.open("document.pdf") as pdf:
    for page in pdf.pages:
        text = page.extract_text()
        print(text)

Extract Tables

with pdfplumber.open("document.pdf") as pdf:
    for i, page in enumerate(pdf.pages):
        tables = page.extract_tables()
        for j, table in enumerate(tables):
            print(f"Table {j+1} on page {i+1}:")
            for row in table:
                print(row)

Advanced Table Extraction

import pandas as pd

with pdfplumber.open("document.pdf") as pdf:
    all_tables = []
    for page in pdf.pages:
        tables = page.extract_tables()
        for table in tables:
            if table:  # Check if table is not empty
                df = pd.DataFrame(table[1:], columns=table[0])
                all_tables.append(df)

# Combine all tables
if all_tables:
    combined_df = pd.concat(all_tables, ignore_index=True)
    combined_df.to_excel("extracted_tables.xlsx", index=False)

reportlab - Create PDFs

Basic PDF Creation

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

c = canvas.Canvas("hello.pdf", pagesize=letter)
width, height = letter

# Add text
c.drawString(100, height - 100, "Hello World!")
c.drawString(100, height - 120, "This is a PDF created with reportlab")

# Add a line
c.line(100, height - 140, 400, height - 140)

# Save
c.save()

Create PDF with Multiple Pages

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet

doc = SimpleDocTemplate("report.pdf", pagesize=letter)
styles = getSampleStyleSheet()
story = []

# Add content
title = Paragraph("Report Title", styles['Title'])
story.append(title)
story.append(Spacer(1, 12))

body = Paragraph("This is the body of the report. " * 20, styles['Normal'])
story.append(body)
story.append(PageBreak())

# Page 2
story.append(Paragraph("Page 2", styles['Heading1']))
story.append(Paragraph("Content for page 2", styles['Normal']))

# Build PDF
doc.build(story)

Subscripts and Superscripts

IMPORTANT: Never use Unicode subscript/superscript characters (₀₁₂₃₄₅₆₇₈₉, ⁰¹²³⁴⁵⁶⁷⁸⁹) in ReportLab PDFs. The built-in fonts do not include these glyphs, causing them to render as solid black boxes.

Instead, use ReportLab's XML markup tags in Paragraph objects:

from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet

styles = getSampleStyleSheet()

# Subscripts: use <sub> tag
chemical = Paragraph("H<sub>2</sub>O", styles['Normal'])

# Superscripts: use <super> tag
squared = Paragraph("x<super>2</super> + y<super>2</super>", styles['Normal'])

For canvas-drawn text (not Paragraph objects), manually adjust font the size and position rather than using Unicode subscripts/superscripts.

Command-Line Tools

pdftotext (poppler-utils)

# Extract text
pdftotext input.pdf output.txt

# Extract text preserving layout
pdftotext -layout input.pdf output.txt

# Extract specific pages
pdftotext -f 1 -l 5 input.pdf output.txt  # Pages 1-5

qpdf

# Merge PDFs
qpdf --empty --pages file1.pdf file2.pdf -- merged.pdf

# Split pages
qpdf input.pdf --pages . 1-5 -- pages1-5.pdf
qpdf input.pdf --pages . 6-10 -- pages6-10.pdf

# Rotate pages
qpdf input.pdf output.pdf --rotate=+90:1  # Rotate page 1 by 90 degrees

# Remove password
qpdf --password=mypassword --decrypt encrypted.pdf decrypted.pdf

pdftk (if available)

# Merge
pdftk file1.pdf file2.pdf cat output merged.pdf

# Split
pdftk input.pdf burst

# Rotate
pdftk input.pdf rotate 1east output rotated.pdf

Common Tasks

Extract Text from Scanned PDFs

# Requires: pip install pytesseract pdf2image
import pytesseract
from pdf2image import convert_from_path

# Convert PDF to images
images = convert_from_path('scanned.pdf')

# OCR each page
text = ""
for i, image in enumerate(images):
    text += f"Page {i+1}:\n"
    text += pytesseract.image_to_string(image)
    text += "\n\n"

print(text)

Add Watermark

from pypdf import PdfReader, PdfWriter

# Create watermark (or load existing)
watermark = PdfReader("watermark.pdf").pages[0]

# Apply to all pages
reader = PdfReader("document.pdf")
writer = PdfWriter()

for page in reader.pages:
    page.merge_page(watermark)
    writer.add_page(page)

with open("watermarked.pdf", "wb") as output:
    writer.write(output)

Extract Images

# Using pdfimages (poppler-utils)
pdfimages -j input.pdf output_prefix

# This extracts all images as output_prefix-000.jpg, output_prefix-001.jpg, etc.

Password Protection

from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")
writer = PdfWriter()

for page in reader.pages:
    writer.add_page(page)

# Add password
writer.encrypt("userpassword", "ownerpassword")

with open("encrypted.pdf", "wb") as output:
    writer.write(output)

Quick Reference

Task Best Tool Command/Code
Merge PDFs pypdf writer.add_page(page)
Split PDFs pypdf One page per file
Extract text pdfplumber page.extract_text()
Extract tables pdfplumber page.extract_tables()
Create PDFs reportlab Canvas or Platypus
Command line merge qpdf qpdf --empty --pages ...
OCR scanned PDFs pytesseract Convert to image first
Fill PDF forms pdf-lib or pypdf (see FORMS.md) See FORMS.md

Next Steps

  • For advanced pypdfium2 usage, see REFERENCE.md
  • For JavaScript libraries (pdf-lib), see REFERENCE.md
  • If you need to fill out a PDF form, follow the instructions in FORMS.md
  • For troubleshooting guides, see REFERENCE.md

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

pdfdocument-processingocrdata-extractionautomationpythonreport-generation

同类 Skill