Communitygithub.com

PDF 处理技能合集

当用户需要处理 PDF 文件时使用此技能。包括读取或提取文本/表格、合并、拆分、旋转页面、添加水印、创建新 PDF、填写表单、加密/解密、提取图像以及对扫描件进行 OCR 使其可搜索。如果用户提到 .pdf 文件或要求生成一个,请使用此技能。

PDF 处理技能合集 是什么?

这是一个全面的 PDF 处理技能包,专为开发者设计,支持使用 Python 库(如 pypdf、pdfplumber、reportlab)和命令行工具(如 qpdf、pdftotext、pdfimages)执行几乎所有的 PDF 操作。该技能覆盖了从基本的文本提取、页面合并/拆分、旋转、添加水印,到高级的表格提取、扫描件 OCR、图像提取、表单填写以及加密解密等功能。它适用于 AI 编码助手(如 Claude Code、Cursor、Codex 等)和任何 Python 或命令行环境。技能的核心在于提供了可直接复用的代码片段和命令示例,并通过 REFERENCE.md 和 FORMS.md 补充了更高级的特性和表单处理说明。使用此技能时,AI 应优先参考其文档中列出的最佳工具和对应方法,确保生成准确、高效的代码或命令。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/bg-szy/TOP-SKILLS/tree/HEAD/skills/skills/pdf

在你喜欢的 AI 中提问

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

文档

PDF 处理指南

概述

本指南涵盖了使用 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, "这是使用 reportlab 创建的 PDF")

# 添加一条线
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 下标/上标字符(₀₁₂₃₄₅₆₇₈₉、⁰¹²³⁴⁵⁶⁷⁸⁹)。内置字体不包含这些字形,会导致它们显示为黑色实心方块。

应改用 ReportLab 在 Paragraph 对象中的 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

常见任务

从扫描件中提取文本

# 需要: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("userpassword", "ownerpassword")

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 ...
扫描件 OCRpytesseract先转换为图像
填写 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.

bg-szy/TOP-SKILLS

Brand-first landing page designer — runs a brand-identity interview (colors, typography, shape language), then generates and iterates on a polished landing page via Stitch with deployment-ready HTML. Use when the user asks to create, design, or build a landing page, homepage, or marketing page and has no established visual direction. Skip when they have a design mockup, need a dashboard or app UI, are working at component level, building a multi-page app, or restyling with known design tokens — use frontend-design instead.

bg-szy/TOP-SKILLS

Fill out Microsoft Azure Landing Zone (ALZ) Accelerator checklists by interviewing the user, mapping their Azure subscriptions, integrating IP addressing documentation, and applying Microsoft Cloud Adoption Framework best practices. Produces a completed Excel checklist (.xlsx) ready for ALZ deployment. Use this skill whenever the user mentions Azure Landing Zone, ALZ checklist, landing zone accelerator, platform landing zone configuration, ALZ bootstrap, hub-and-spoke setup, Azure network topology planning, or wants to fill out any ALZ-related checklist or configuration file. Also trigger when the user uploads an Excel file that contains tabs like "Accelerator - Bootstrap", "Accelerator - Bicep", or "Accelerator - Terraform".

bg-szy/TOP-SKILLS

Compose a premium, animated landing page section by section in Next.js + Tailwind + Motion (Framer Motion) — built on a real design system, with editorial copy and motion that feels human-crafted, not template-generated. Use when building or rebuilding a landing page, marketing site, or hero/feature/pricing/CTA sections that need to look production-ready and bespoke from day one.

bg-szy/TOP-SKILLS

Write high-converting landing page copy using proven frameworks like PAS (Problem-Agitate-Solution), AIDA, and StoryBrand. Creates headlines, value propositions, CTAs, and full page sections optimized for conversion. Use when users need landing page copy, sales page content, or marketing website text.

bg-szy/TOP-SKILLS

Optimize landing pages for conversions, performance, and SEO. Use when improving landing pages, increasing conversions, or optimizing page performance.

bg-szy/TOP-SKILLS

Review investment portfolios for risk, diversification, fees. Asset allocation recommendations, tax-loss harvesting, rebalancing.

bg-szy/TOP-SKILLS

Beads Viewer - Graph-aware triage engine for Beads projects. Computes PageRank, betweenness, critical path, and cycles. Use --robot-* flags for AI agents.

bg-szy/TOP-SKILLS

CI red? Call us. Pipeline fire brigade deploys. Use when user mentions CI failures, build errors, test failures, or pipeline issues. Do NOT load for: local builds, standard implementation work, reviews, or setup.

bg-szy/TOP-SKILLS

CASS Memory System - procedural memory for AI coding agents. Three-layer cognitive architecture with confidence decay, anti-pattern learning, cross-agent knowledge transfer, trauma guard safety system. Bun/TypeScript CLI.

bg-szy/TOP-SKILLS

Mandatory entry point: read this first for any request to make, create, edit, animate, or render a video, animation, or motion graphic, including a promo, explainer, captioned clip, title card, overlay, slideshow or interactive deck, Remotion port, or any HyperFrames HTML composition. Also use it to inspect, diagnose, validate, preview, publish, or batch-render an existing HyperFrames project. Inputs may be a website URL, GitHub PR, Figma design or URL, text or brief, existing footage, or music. It resumes project state, captures intent when applicable, selects and installs the owning workflow, and routes domain capabilities. HyperFrames is the default output framework unless the user explicitly chooses another framework for the deliverable or asks only to record a browser session.

bg-szy/TOP-SKILLS

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

bg-szy/TOP-SKILLS

Use when the user asks to "pre-launch check the landing page", "run a Quality-Score preflight", or "verify ad-to-page message match before launch"; produces an ad↔page continuity report — message-match gaps, above-the-fold check, page-speed read, form-friction count, mobile-render flags — as a pass/fix punch list. Not for redesigning or rewriting the page — use landing-optimizer; not for scoring the account or the RQS — use ad-account-auditor. 落地页体验预检/广告落地页一致性检查

bg-szy/TOP-SKILLS

Use when the user asks to "optimize our landing page for influencer traffic", "fix our promo-code landing page", or "improve conversion from a creator campaign"; produces a message-match audit, page-structure and social-proof recommendations, a promo-code/CTA conversion plan, and an A/B test roadmap. Not for measuring campaign results after launch — use performance-analyzer.

bg-szy/TOP-SKILLS

Audit a landing page, sales page or checkout page for conversion leaks and return a fix list ordered by expected revenue impact. Use when asked to review, critique or improve a landing page, sales page, opt-in page, product page or checkout flow, when conversion rate is low, when paid traffic is not converting, or when someone asks "why isn't this page converting" or wants a CRO / landing page review.

bg-szy/TOP-SKILLS

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

bg-szy/TOP-SKILLS

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

bg-szy/TOP-SKILLS

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

bg-szy/TOP-SKILLS

Account assets, equity and fund positions, P&L, cash flow records, account statements, margin ratios, buy-power estimates, order management, and DCA recurring investments via Longbridge (most require Trade permission). Frameworks: portfolio diagnosis, rebalancing, asset allocation, risk analysis (VaR/CVaR), performance attribution, and tax-loss harvesting. Triggers: "持仓", "账户", "盈亏", "资产", "对账单", "下单", "买入", "卖出", "撤单", "定投", "组合诊断", "再平衡", "资产配置", "风险分析", "绩效归因", "税损收割", "持倉", "賬戶", "盈虧", "對賬單", "下單", "買入", "賣出", "組合診斷", "再平衡", "稅損收割", "positions", "portfolio", "P&L", "order", "buy", "sell", "DCA", "statement", "risk analysis", "rebalancing", "tax harvesting", "我的风险", "持仓风险", "风险敞口", "資產", "資產配置", "風險分析", "績效歸因", "撤單

bg-szy/TOP-SKILLS

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

bg-szy/TOP-SKILLS

Process video files with audio extraction, format conversion (mp4, webm), and Whisper transcription. Use when user mentions video conversion, audio extraction, transcription, mp4, webm, ffmpeg, or whisper transcription.

相关技能