Communityコーディング&開発github.com

PDF

PDFファイルの読み取り、テキスト/表抽出、結合、分割、回転、透かし追加、新規作成、フォーム入力、暗号化/復号、画像抽出、OCRなど、PDFに関するあらゆる操作を行うためのスキルです。

PDF とは?

このスキルは、Pythonライブラリ(pypdf、pdfplumber、reportlab、pytesseractなど)とコマンドラインツール(pdftotext、qpdf、pdftk)を使用して、あらゆるPDF処理を実行するための包括的なガイドです。元のドキュメント(SKILL.md)は、アシスタント向けに設計されており、PDFの読み取り、結合、分割、テキスト/表抽出、新規作成、回転、透かし追加、画像抽出、OCR、パスワード保護、フォーム入力などの一般的なタスクを効率的に実行できます。特に、reportlabでPDFを作成する際にUnicodeの下付き/上付き文字を使用しないように注意するなど、プラットフォーム固有の注意点も詳述されています。複数のツールを状況に応じて切り替えることで、ユーザーの要求に柔軟かつ正確に応えることができます。

対応~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に質問する

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

ドキュメント

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

代わりに、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からのテキスト抽出

# 必要なパッケージ: 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を参照してください

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

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 \

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 \

関連スキル