Community程式設計與開發github.com

PDF 處理技能

當使用者需要處理 PDF 檔案時使用此技能,包括讀取、擷取文字/表格、合併、拆分、旋轉頁面、添加浮水印、建立新 PDF、填寫表格、加密/解密、擷取圖片以及對掃描檔案進行 OCR。

PDF 處理技能 是什麼?

這個技能是一個綜合性的 PDF 處理指南,支援 Python 函式庫(如 pypdf、pdfplumber、reportlab)和命令列工具(如 qpdf、pdftotext、pdftk)。它能處理從基本操作(讀取、合併、拆分)到進階功能(表格擷取、OCR、浮水印、密碼保護)的所有任務。主要支援 Claude Code 等 AI 代理,透過清晰的程式碼範例和快速參考表,讓開發者輕鬆處理 PDF 檔案。技能文件也詳細說明了 Unicode 下標/上標字元在 ReportLab 中的限制,並提供替代的 XML 標記方法。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/anthropics/skills/tree/main/skills/pdf

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 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, "哈囉,世界!")
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())

# 第 2 頁
story.append(Paragraph("第 2 頁", styles['Heading1']))
story.append(Paragraph("第 2 頁的內容", styles['Normal']))

# 建立 PDF
doc.build(story)

下標與上標

重要:永遠不要在 ReportLab PDF 中使用 Unicode 下標/上標字元(₀₁₂₃₄₅₆₇₈₉、⁰¹²³⁴⁵⁶⁷⁸⁹)。內建字型不包含這些字符,這會導致它們顯示為實心黑色方塊。

改用 ReportLab 的 XML 標記標籤在 Paragraph 物件中:

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("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 ...
掃描 PDF 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 19 individual skills — each has its own dedicated page.

academy-guide

Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.

algorithmic-art

Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists

anthropics/template-skill

Replace with description of the skill and when Claude should use it.

brand-guidelines

Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.

canvas-design

Create beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists

claude-api

|-

discernment-nudge

After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.

doc-coauthoring

Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.

docx

Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation.

frontend-design

Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.

internal-comms

A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).

mcp-builder

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

pptx

Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.

skill-creator

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill

slack-gif-creator

Knowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like

theme-factory

Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors/fonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.

webapp-testing

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

web-artifacts-builder

Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts.

xlsx

Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.

相關技能