Communitygithub.com

PDF

ユーザーがPDFファイルに関する操作(テキスト抽出、結合、分割、回転、ウォーターマーク追加、新規作成、フォーム入力、暗号化、OCRなど)を必要とする場合に使用するスキルです。

PDF とは?

このスキルは、Pythonライブラリ(pypdf、pdfplumber、reportlab)およびコマンドラインツール(pdftotext、qpdf、pdftk)を使用して、あらゆるPDF処理を実行するための包括的なガイドです。ユーザーがPDFの読み取り、テキストや表の抽出、複数PDFの結合・分割、ページ回転、ウォーターマーク追加、新しいPDFの作成、フォーム入力、暗号化・復号化、画像抽出、スキャンPDFのOCR処理などを要求した際に起動されます。特に、ReportLabでの添字・上付き文字はUnicode文字ではなくXMLマークアップタグを使用する必要がある点や、スキャンPDFのOCRにはpytesseractとpdf2imageが必要である点などの重要な注意事項も含まれています。また、高度な機能やJavaScriptライブラリを使用したフォーム入力については、別のドキュメント(reference.md、forms.md)を参照するよう指示しています。

対応✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/pdf

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

# PDF処理ガイド

## 概要

このガイドでは、Pythonライブラリとコマンドラインツールを使用した基本的なPDF処理操作について説明します。高度な機能、JavaScriptライブラリ、詳細な例については、reference.mdを参照してください。PDFフォームの入力が必要な場合は、forms.mdを読み、その指示に従ってください。

## クイックスタート

```python
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の下付き/上付き文字(₀₁₂₃₄₅₆₇₈₉、⁰¹²³⁴⁵⁶⁷⁸⁹)を決して使用しないでください。組み込みフォントにはこれらのグリフが含まれていないため、黒い塗りつぶしのボックスとして表示されます。

代わりに、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'])

キャンバスで描画するテキスト(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)

クイックリファレンス

タスク最適なツールコマンド/コード
PDFの結合pypdfwriter.add_page(page)
PDFの分割pypdfファイルごとに1ページ
テキスト抽出pdfplumberpage.extract_text()
表の抽出pdfplumberpage.extract_tables()
PDF作成reportlabCanvasまたは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.

関連スキル