Communitygithub.com

PDF 處理指南

每當使用者想要對 PDF 檔案執行任何操作時,請使用此技能。包括讀取或擷取文字/表格、合併、分割、旋轉頁面、添加浮水印、建立新 PDF、填寫 PDF 表單、加密/解密、擷取圖片以及對掃描的 PDF 進行 OCR。

PDF 處理指南 是什麼?

這是一份全面的 PDF 處理指南技能,旨在協助開發者或 AI 代理完成各種 PDF 操作任務。此技能涵蓋了從基本讀取、文字擷取、合併、分割、旋轉頁面,到進階的表格擷取、掃描文件 OCR、建立新 PDF、添加浮水印、圖片擷取以及密碼保護等功能。該指南根據實際任務推薦使用特定 Python 程式庫(如 `pypdf` 用於基本操作,`pdfplumber` 用於精確的文字與表格擷取,`reportlab` 用於建立 PDF)和命令列工具(如 `qpdf`、`pdftk` 和 `pdftotext`),並提供可直接複製的程式碼範例和命令。它通用於任何支援 Python 或命令列的 AI 代理平台(例如 Claude Code、Coder、Codex)。此外,技能文件還引用了同目錄下的額外參考文件 `reference.md`(用於進階功能和 JavaScript 庫)和 `forms.md`(專門用於填寫 PDF 表單),確保使用者在遇到複雜或特定需求時有更詳細的指引。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/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())

# 第 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 中擷取文字

# 需要:uv 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

此技能由 Anthropic 建立與維護。除前端中繼資料以及上游以大寫字母書寫的 reference.md/forms.md 連結(此處改為小寫)外,原封不動地在此紀錄;請參閱 LICENSE.txt 以了解條款。

Individual skills in this repo

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

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相關技能