Communitygithub.com

PDF

PDF 파일과 관련된 모든 작업(읽기, 텍스트/표 추출, 병합, 분할, 회전, 워터마크 추가, 생성, 양식 채우기, 암호화/복호화, 이미지 추출, OCR)에 사용합니다.

PDF란 무엇인가요?

이 스킬은 Python 라이브러리(pypdf, pdfplumber, reportlab)와 명령줄 도구(pdftotext, qpdf, pdftk)를 사용하여 PDF 파일을 처리하는 포괄적인 가이드를 제공합니다. 사용자가 PDF 파일을 언급하거나 생성 요청을 할 때 활성화되며, 텍스트 및 표 추출, 여러 PDF 병합, 페이지 분할, 페이지 회전, 워터마크 추가, 새로운 PDF 생성, 양식 채우기, 암호화/복호화, 이미지 추출, 스캔된 PDF의 OCR 등 다양한 작업을 지원합니다. 각 작업에 대해 최적의 도구와 코드 예제를 제공하며, 고급 기능(예: pdf-lib 사용)은 별도 참조 문서에서 다룹니다. 이 스킬은 Claude Code, Cursor, Codex 등 AI 에이전트 환경에서 사용할 수 있도록 설계되었습니다.

지원 대상✓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를 읽고 지침을 따르세요.

빠른 시작

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에서 유니코드 아래 첨자/위 첨자 문자(₀₁₂₃₄₅₆₇₈₉, ⁰¹²³⁴⁵⁶⁷⁸⁹)를 절대 사용하지 마세요. 기본 글꼴에 이러한 글리프가 포함되어 있지 않아 검은색 채워진 사각형으로 렌더링됩니다.

대신 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'])

canvas로 그려진 텍스트(Paragraph 객체가 아닌 경우)의 경우 유니코드 아래 첨자/위 첨자를 사용하는 대신 글꼴 크기와 위치를 수동으로 조정하세요.

명령줄 도구

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페이지당 파일 하나
텍스트 추출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.

관련 스킬