Communitygithub.com

Anhvu1107/pdf处理技能

在处理涉及PDF文件的读取、提取、拆分、合并、旋转、创建、验证、OCR、表单填写等任何生成或修改任务时,请务必使用此技能。

pdf处理技能 是什么?

该技能是一个全面的PDF处理指南,专为AI Agent(如Claude Code、Cursor、Codex)设计,以高效执行各种PDF相关任务。它支持多个平台,并提供了Python库(如pypdf、pdfplumber、reportlab)和命令行工具(如qpdf、pdftotext、pdftk)的详细代码和命令示例。该技能涵盖了从基本的合并、拆分、文本提取到高级的OCR识别、水印添加、表单填写和密码保护等常见操作。其核心价值在于为开发者提供了一个集中的参考点,避免了在多个文档或库之间切换的麻烦,显著提高了处理PDF文档的开发效率和准确性。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Anhvu1107/all-agent-skill/tree/HEAD/.agent/skills/pdf

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

PDF 处理指南

选择性阅读规则

首先阅读:

  • references/usage-routing.md
  • references/quality-checklist.md

然后,仅加载与用户实际任务匹配的继承文档、脚本、资产或示例。

选择性阅读规则

首先阅读:

  • references/senior-master-standard.md
  • references/task-routing.md
  • references/quality-checklist.md

然后阅读:

  • forms.md 用于 AcroForm 或表单填写任务
  • reference.md 当你需要更广泛的工具或库调研时

概述

本指南涵盖了使用 Python 库和命令行工具进行基本 PDF 处理操作。关于高级功能、JavaScript 库和详细示例,请参阅 REFERENCE.md。如果你需要填写 PDF 表单,请阅读 FORMS.md 并遵循其说明。

快速开始

from pypdf import PdfReader, PdfWriter

# 读取 PDF
reader = PdfReader("document.pdf")
print(f"页数: {len(reader.pages)}")

# 提取文本
text = ""
for page in reader.pages:
    text += page.extract_text()

Python 库

pypdf - 基本操作

合并 PDF

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)

拆分 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)

提取元数据

reader = PdfReader("document.pdf")
meta = reader.metadata
print(f"标题: {meta.title}")
print(f"作者: {meta.author}")
print(f"主题: {meta.subject}")
print(f"创建者: {meta.creator}")

旋转页面

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

page = reader.pages[0]
page.rotate(90)  # 顺时针旋转 90 度
writer.add_page(page)

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

pdfplumber - 文本与表格提取

保留布局提取文本

import pdfplumber

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

提取表格

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"第 {i+1} 页上的第 {j+1} 个表格:")
            for row in table:
                print(row)

高级表格提取

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:  # 检查表格是否非空
                df = pd.DataFrame(table[1:], columns=table[0])
                all_tables.append(df)

# 合并所有表格
if all_tables:
    combined_df = pd.concat(all_tables, ignore_index=True)
    combined_df.to_excel("extracted_tables.xlsx", index=False)

reportlab - 创建 PDF

基本 PDF 创建

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

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

# 添加文本
c.drawString(100, height - 100, "Hello World!")
c.drawString(100, height - 120, "This is a PDF created with reportlab")

# 添加一条线
c.line(100, height - 140, 400, height - 140)

# 保存
c.save()

创建多页 PDF

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 = []

# 添加内容
title = Paragraph("报告标题", styles['Title'])
story.append(title)
story.append(Spacer(1, 12))

body = Paragraph("这是报告正文。" * 20, styles['Normal'])
story.append(body)
story.append(PageBreak())

# 第二页
story.append(Paragraph("第二页", styles['Heading1']))
story.append(Paragraph("第二页的内容", styles['Normal']))

# 构建 PDF
doc.build(story)

下标和上标

重要:切勿在 ReportLab PDF 中使用 Unicode 下标/上标字符(₀₁₂₃₄₅₆₇₈₉, ⁰¹²³⁴⁵⁶⁷⁸⁹)。内置字体不包含这些字形,会导致它们渲染为实心黑色方块。

相反,应在 Paragraph 对象中使用 ReportLab 的 XML 标记标签:

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

styles = getSampleStyleSheet()

# 下标:使用 <sub> 标签
chemical = Paragraph("H<sub>2</sub>O", styles['Normal'])

# 上标:使用 <super> 标签
squared = Paragraph("x<super>2</super> + y<super>2</super>", styles['Normal'])

对于 canvas 绘制的文本(非 Paragraph 对象),手动调整字体大小和位置,而不是使用 Unicode 下标/上标。

命令行工具

pdftotext (poppler-utils)

# 提取文本
pdftotext input.pdf output.txt

# 保留布局提取文本
pdftotext -layout input.pdf output.txt

# 提取特定页面
pdftotext -f 1 -l 5 input.pdf output.txt  # 第 1-5 页

qpdf

# 合并 PDF
qpdf --empty --pages file1.pdf file2.pdf -- merged.pdf

# 拆分页面
qpdf input.pdf --pages . 1-5 -- pages1-5.pdf
qpdf input.pdf --pages . 6-10 -- pages6-10.pdf

# 旋转页面
qpdf input.pdf output.pdf --rotate=+90:1  # 将第 1 页旋转 90 度

# 移除密码
qpdf --password=mypassword --decrypt encrypted.pdf decrypted.pdf

pdftk (如果可用)

# 合并
pdftk file1.pdf file2.pdf cat output merged.pdf

# 拆分
pdftk input.pdf burst

# 旋转
pdftk input.pdf rotate 1east output rotated.pdf

常见任务

从扫描版 PDF 中提取文本

# 需要: pip install pytesseract pdf2image
import pytesseract
from pdf2image import convert_from_path

# 将 PDF 转换为图像
images = convert_from_path('scanned.pdf')

# 对每页进行 OCR
text = ""
for i, image in enumerate(images):
    text += f"第 {i+1} 页:\n"
    text += pytesseract.image_to_string(image)
    text += "\n\n"

print(text)

添加水印

from pypdf import PdfReader, PdfWriter

# 创建水印(或加载现有水印)
watermark = PdfReader("watermark.pdf").pages[0]

# 应用于所有页面
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)

提取图像

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

# 这将把所有图像提取为 output_prefix-000.jpg, output_prefix-001.jpg 等文件。

密码保护

from pypdf import PdfReader, PdfWriter

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

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

# 添加密码
writer.encrypt("用户密码", "所有者密码")

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

快速参考

任务最佳工具命令/代码
合并 PDFpypdfwriter.add_page(page)
拆分 PDFpypdf每页一个文件
提取文本pdfplumberpage.extract_text()
提取表格pdfplumberpage.extract_tables()
创建 PDFreportlabCanvas 或 Platypus
命令行合并qpdfqpdf --empty --pages ...
OCR 扫描版 PDFpytesseract先转换为图像
填写 PDF 表单pdf-lib 或 pypdf (参见 FORMS.md)参见 FORMS.md

后续步骤

  • 关于高级 pypdfium2 用法,请参阅 REFERENCE.md
  • 关于 JavaScript 库 (pdf-lib),请参阅 REFERENCE.md
  • 如果你需要填写 PDF 表单,请遵循 FORMS.md 中的说明
  • 关于故障排除指南,请参阅 REFERENCE.md

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches 007: Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Agentfolio: Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Animejs Animation: Advanced JavaScript animation library skill for creating complex, high-performance web animations.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Astropy: Astropy is the core Python package for astronomy, providing essential functionality for astronomical research and data analysis.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Astro: Build content-focused websites with Astro — zero JS by default, islands architecture, multi-framework components, and Markdown/MDX support.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Emotional ARC Designer: One sentence - what this skill does and when to invoke it

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Fixing Motion Performance: Audit and fix animation performance issues including layout thrashing, compositor properties, scroll-linked motion, and blur effects.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches I18n Localization: Internationalization and localization patterns.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Interactive Portfolio: Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches JQ: Expert jq usage for JSON querying, filtering, transformation, and pipeline integration.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Landing Page Generator: Generates high-converting Next.js/React landing pages with Tailwind CSS.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches LEX: Centralized ''Truth Engine'' for cross-jurisdictional legal context (US, EU, CA) and contract scaffolding.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Magic Animator: AI-powered animation tool for creating motion in logos, UI, icons, and social media assets.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Makepad Animation: CRITICAL: Use for Makepad animation system.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Nextjs APP Router Patterns: Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.

Anhvu1107/all-agent-skill

ALWAYS use this when the user mentions Nextjs Best Practices, asks to build, debug, review, document, automate, test, configure, migrate, or make decisions in this domain, or the task clearly depends on Nextjs Best Practices; scope: Next.js App Router principles. Apply the bundled workflow, references, scripts, Senior Master standard, and Codex strict review gate before final output.

Anhvu1107/all-agent-skill

description: ALWAYS use this when the work is specifically about modern Next.js or React architecture, data flow, rendering strategy, routing, or performance-sensitive frontend behavior.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Nextjs Supabase Auth: Expert integration of Supabase Auth with Next.js App Router

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches React Nextjs Development: React and Next.js 14+ application development with App Router, Server Components, TypeScript, Tailwind CSS, and modern frontend patterns.

Anhvu1107/all-agent-skill

ALWAYS use this when working with Remotion code, video compositions, rendering logic, timing, media assets, or React-based motion workflows.

相关技能