Communitygithub.com

pdf

Use esta habilidade sempre que o usuário quiser fazer qualquer coisa com arquivos PDF, como ler ou extrair texto/tabelas, combinar vários PDFs, dividir, girar páginas, adicionar marcas d'água, criar novos PDFs, preencher formulários, criptografar/descriptografar, extrair imagens e fazer OCR em PDFs escaneados.

O que é pdf?

Esta habilidade fornece um guia completo para operações de processamento de PDF usando bibliotecas Python (pypdf, pdfplumber, reportlab) e ferramentas de linha de comando (pdftotext, qpdf, pdftk). Ela cobre tarefas comuns como mesclar, dividir, girar páginas, extrair texto e tabelas, criar PDFs do zero, adicionar marcas d'água, proteger com senha e extrair imagens. Inclui também OCR para PDFs escaneados com pytesseract e orientações específicas para preenchimento de formulários. A habilidade suporta plataformas como Claude Code e é útil para desenvolvedores que precisam automatizar manipulações de PDF, garantindo boas práticas como evitar caracteres Unicode subscritos/sobrescritos em PDFs criados com ReportLab. Ela oferece exemplos práticos de código e comandos, além de uma tabela de referência rápida para escolher a melhor ferramenta para cada tarefa.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Guia de Processamento de PDF

Visão Geral

Este guia cobre operações essenciais de processamento de PDF usando bibliotecas Python e ferramentas de linha de comando. Para recursos avançados, bibliotecas JavaScript e exemplos detalhados, consulte reference.md. Se precisar preencher um formulário PDF, leia forms.md e siga suas instruções.

Início Rápido

from pypdf import PdfReader, PdfWriter

# Ler um PDF
reader = PdfReader("documento.pdf")
print(f"Páginas: {len(reader.pages)}")

# Extrair texto
texto = ""
for page in reader.pages:
    texto += page.extract_text()

Bibliotecas Python

pypdf - Operações Básicas

Mesclar PDFs

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("mesclado.pdf", "wb") as output:
    writer.write(output)

Dividir PDF

reader = PdfReader("entrada.pdf")
for i, page in enumerate(reader.pages):
    writer = PdfWriter()
    writer.add_page(page)
    with open(f"pagina_{i+1}.pdf", "wb") as output:
        writer.write(output)

Extrair Metadados

reader = PdfReader("documento.pdf")
meta = reader.metadata
print(f"Título: {meta.title}")
print(f"Autor: {meta.author}")
print(f"Assunto: {meta.subject}")
print(f"Criador: {meta.creator}")

Girar Páginas

reader = PdfReader("entrada.pdf")
writer = PdfWriter()

page = reader.pages[0]
page.rotate(90)  # Girar 90 graus no sentido horário
writer.add_page(page)

with open("girado.pdf", "wb") as output:
    writer.write(output)

pdfplumber - Extração de Texto e Tabelas

Extrair Texto com Layout

import pdfplumber

with pdfplumber.open("documento.pdf") as pdf:
    for page in pdf.pages:
        texto = page.extract_text()
        print(texto)

Extrair Tabelas

with pdfplumber.open("documento.pdf") as pdf:
    for i, page in enumerate(pdf.pages):
        tabelas = page.extract_tables()
        for j, tabela in enumerate(tabelas):
            print(f"Tabela {j+1} na página {i+1}:")
            for row in tabela:
                print(row)

Extração Avançada de Tabelas

import pandas as pd

with pdfplumber.open("documento.pdf") as pdf:
    todas_tabelas = []
    for page in pdf.pages:
        tabelas = page.extract_tables()
        for tabela in tabelas:
            if tabela:  # Verificar se a tabela não está vazia
                df = pd.DataFrame(tabela[1:], columns=tabela[0])
                todas_tabelas.append(df)

# Combinar todas as tabelas
if todas_tabelas:
    combinado_df = pd.concat(todas_tabelas, ignore_index=True)
    combinado_df.to_excel("tabelas_extraidas.xlsx", index=False)

reportlab - Criar PDFs

Criação Básica de PDF

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

c = canvas.Canvas("ola.pdf", pagesize=letter)
largura, altura = letter

# Adicionar texto
c.drawString(100, altura - 100, "Olá Mundo!")
c.drawString(100, altura - 120, "Este é um PDF criado com reportlab")

# Adicionar uma linha
c.line(100, altura - 140, 400, altura - 140)

# Salvar
c.save()

Criar PDF com Múltiplas Páginas

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet

doc = SimpleDocTemplate("relatorio.pdf", pagesize=letter)
estilos = getSampleStyleSheet()
historias = []

# Adicionar conteúdo
titulo = Paragraph("Título do Relatório", estilos['Title'])
historias.append(titulo)
historias.append(Spacer(1, 12))

corpo = Paragraph("Este é o corpo do relatório. " * 20, estilos['Normal'])
historias.append(corpo)
historias.append(PageBreak())

# Página 2
historias.append(Paragraph("Página 2", estilos['Heading1']))
historias.append(Paragraph("Conteúdo para a página 2", estilos['Normal']))

# Construir PDF
doc.build(historias)

Subscritos e Sobrescritos

IMPORTANTE: Nunca use caracteres Unicode de subscrito/sobrescrito (₀₁₂₃₄₅₆₇₈₉, ⁰¹²³⁴⁵⁶⁷⁸⁹) em PDFs do ReportLab. As fontes internas não incluem esses glifos, fazendo com que sejam renderizados como blocos pretos sólidos.

Em vez disso, use as tags de marcação XML do ReportLab em objetos Paragraph:

from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet

estilos = getSampleStyleSheet()

# Subscritos: use a tag <sub>
quimico = Paragraph("H<sub>2</sub>O", estilos['Normal'])

# Sobrescritos: use a tag <super>
quadrado = Paragraph("x<super>2</super> + y<super>2</super>", estilos['Normal'])

Para texto desenhado com canvas (não objetos Paragraph), ajuste manualmente o tamanho e a posição da fonte em vez de usar subscritos/sobrescritos Unicode.

Ferramentas de Linha de Comando

pdftotext (poppler-utils)

# Extrair texto
pdftotext entrada.pdf saida.txt

# Extrair texto preservando layout
pdftotext -layout entrada.pdf saida.txt

# Extrair páginas específicas
pdftotext -f 1 -l 5 entrada.pdf saida.txt  # Páginas 1-5

qpdf

# Mesclar PDFs
qpdf --empty --pages arquivo1.pdf arquivo2.pdf -- mesclado.pdf

# Dividir páginas
qpdf entrada.pdf --pages . 1-5 -- paginas1-5.pdf
qpdf entrada.pdf --pages . 6-10 -- paginas6-10.pdf

# Girar páginas
qpdf entrada.pdf saida.pdf --rotate=+90:1  # Girar página 1 em 90 graus

# Remover senha
qpdf --password=minhasenha --decrypt criptografado.pdf descriptografado.pdf

pdftk (se disponível)

# Mesclar
pdftk arquivo1.pdf arquivo2.pdf cat output mesclado.pdf

# Dividir
pdftk entrada.pdf burst

# Girar
pdftk entrada.pdf rotate 1east output girado.pdf

Tarefas Comuns

Extrair Texto de PDFs Escaneados

# Requer: pip install pytesseract pdf2image
import pytesseract
from pdf2image import convert_from_path

# Converter PDF para imagens
imagens = convert_from_path('escaneado.pdf')

# OCR em cada página
texto = ""
for i, imagem in enumerate(imagens):
    texto += f"Página {i+1}:\n"
    texto += pytesseract.image_to_string(imagem)
    texto += "\n\n"

print(texto)

Adicionar Marca D'Água

from pypdf import PdfReader, PdfWriter

# Criar marca d'água (ou carregar existente)
marca = PdfReader("marca_dagua.pdf").pages[0]

# Aplicar a todas as páginas
reader = PdfReader("documento.pdf")
writer = PdfWriter()

for page in reader.pages:
    page.merge_page(marca)
    writer.add_page(page)

with open("com_marca.pdf", "wb") as output:
    writer.write(output)

Extrair Imagens

# Usando pdfimages (poppler-utils)
pdfimages -j entrada.pdf prefixo_saida

# Isso extrai todas as imagens como prefixo_saida-000.jpg, prefixo_saida-001.jpg, etc.

Proteção por Senha

from pypdf import PdfReader, PdfWriter

reader = PdfReader("entrada.pdf")
writer = PdfWriter()

for page in reader.pages:
    writer.add_page(page)

# Adicionar senha
writer.encrypt("senha_usuario", "senha_proprietario")

with open("criptografado.pdf", "wb") as output:
    writer.write(output)

Referência Rápida

TarefaMelhor FerramentaComando/Código
Mesclar PDFspypdfwriter.add_page(page)
Dividir PDFspypdfUm arquivo por página
Extrair textopdfplumberpage.extract_text()
Extrair tabelaspdfplumberpage.extract_tables()
Criar PDFsreportlabCanvas ou Platypus
Mesclar por linha de comandoqpdfqpdf --empty --pages ...
OCR em PDFs escaneadospytesseractConverter para imagem primeiro
Preencher formulários PDFpdf-lib ou pypdf (veja forms.md)Veja forms.md

Próximos Passos

  • Para uso avançado de pypdfium2, consulte reference.md
  • Para bibliotecas JavaScript (pdf-lib), consulte reference.md
  • Se precisar preencher um formulário PDF, siga as instruções em forms.md
  • Para guias de solução de problemas, consulte reference.md

Esta habilidade é criada e mantida por Anthropic. Vendida aqui sem modificações, exceto pelos metadados do frontmatter e pela capitalização dos links reference.md/forms.md, que a montante escreve em maiúsculas; veja LICENSE.txt para os termos.

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.

Habilidades Relacionadas