Skip to content
Back to skills

Pdf

ASecurity

用户提及 .pdf 文件或需要生成、处理 PDF 时使用。适用于阅读和提取文本或表格、合并和拆分文件、旋转页面、添加水印、创建 PDF、填写表单、加密或解密、导出图片,以及用 OCR 将扫描件转换为可搜索的文档。

  • 626 stars
  • 0 votes
  • 5 copies
  • 49 views
  • Added February 10, 2026
toolsjavascriptpythonjavabashaws

Security analysis

A96/100
  • mediumInstalls packages at runtime which could introduce malicious dependencies

Pro scans all 12 files and shows the line behind each finding

Scanned December 2, 2026

npx -y skills add LeastBit/Claude_skills_zh-CN --skill pdf --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Pdf?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Pdf
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/leastbit-pdf/badge)](https://www.skillsdirectory.com/skills/leastbit-pdf)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: pdf
description: 用户提及 .pdf 文件或需要生成、处理 PDF 时使用。适用于阅读和提取文本或表格、合并和拆分文件、旋转页面、添加水印、创建 PDF、填写表单、加密或解密、导出图片,以及用 OCR 将扫描件转换为可搜索的文档。
license: 完整条款见 LICENSE.txt
---

# PDF 处理指南

## 概述

本指南介绍常见的 Python 库与命令行工具。高级用法、JavaScript 库和完整示例见 [REFERENCE.md](REFERENCE.md)。填写 PDF 表单时,按 [FORMS.md](FORMS.md) 的流程操作。

## 快速开始

```python
from pypdf import PdfReader, PdfWriter

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

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

## Python 库

### pypdf 基础操作

#### 合并 PDF

```python
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

```python
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)
```

#### 读取元数据

```python
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}")
```

#### 旋转页面

```python
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 提取文本与表格

#### 保留布局地提取文本

```python
import pdfplumber

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

#### 提取表格

```python
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} 在页面上 {i+1}:")
            for row in table:
                print(row)
```

#### 合并提取出的多张表

```python
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

```python
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()
```

#### 生成多页文档

```python
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("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())

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

# 生成 PDF
doc.build(story)
```

#### 渲染上下标

ReportLab 内置字体通常没有 Unicode 上下标字形。字符如 `₀₁₂` 和 `⁰¹²` 会显示成黑色方块。`Paragraph` 对象应使用 ReportLab 的 XML 标记。

```python
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 上绘制文字时,调整字号和基线位置来实现上标和下标。

## 命令行工具

<a id="pdftotextpoppler-utils"></a>

### pdftotext(poppler-utils)

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

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

# 提取指定页的文本
pdftotext -f 1 -l 5 input.pdf output.txt  # 第 1–5 页
```

<a id="qpdf"></a>

### qpdf

```bash
# 合并 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(环境已安装时)

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

# 拆分
pdftk input.pdf burst

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

## 常见任务

### 对扫描版 PDF 进行 OCR

```python
# 安装依赖: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"Page {i+1}:\n"
    text += pytesseract.image_to_string(image)
    text += "\n\n"

print(text)
```

### 添加水印

```python
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)
```

### 批量提取图片

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

# 这会将所有图片提取为 output_prefix-000.jpg、output_prefix-001.jpg 等。
```

### 设置密码

```python
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)
```

## 快速查阅

| 任务 | 工具 | 命令或方法 |
|---|---|---|
| 合并文件 | pypdf | `writer.add_page(page)` |
| 按页拆分 | pypdf | 每页写入一个单独的文件 |
| 提取文本 | pdfplumber | `page.extract_text()` |
| 提取表格 | pdfplumber | `page.extract_tables()` |
| 创建 PDF | ReportLab | Canvas 或 Platypus |
| 在命令行合并 | qpdf | `qpdf --empty --pages ...` |
| 对扫描件做 OCR | pytesseract | 先将各页转换为图片 |
| 填写表单 | pdf-lib 或 pypdf | 见 [FORMS.md](FORMS.md) |

## 延伸阅读

- pypdfium2 高级功能、JavaScript 的 pdf-lib 以及问题排查见 [REFERENCE.md](REFERENCE.md)。
- 填写 PDF 表单见 [FORMS.md](FORMS.md)。

<!-- 本文件基于 Anthropic Skills 进行简体中文翻译及适配。 -->

<!-- 本文件基于 Anthropic Skills 进行简体中文本地化。 -->

Files in this skill

  • LICENSE.txt1.4 KB
  • SKILL.md6.9 KB
  • forms.md8.5 KB
  • reference.md15.8 KB
  • scripts/check_bounding_boxes.py3 KB
  • scripts/check_bounding_boxes_test.py8.3 KB
  • scripts/check_fillable_fields.py365 B
  • scripts/convert_pdf_to_images.py1.1 KB
  • scripts/create_validation_image.py1.5 KB
  • scripts/extract_form_field_info.py5.9 KB
  • scripts/fill_fillable_fields.py4.7 KB
  • scripts/fill_pdf_form_with_annotations.py3.4 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in tools →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.