PDF

Use esta habilidade sempre que o usuário quiser fazer qualquer coisa com arquivos PDF. Isso inclui ler ou extrair texto/tabelas de PDFs, combinar ou mesclar vários PDFs em um, dividir PDFs, girar páginas, adicionar marcas d'água, criar novos PDFs, preencher formulários PDF, criptografar/descriptografar PDFs, extrair imagens e OCR em PDFs escaneados para torná-los pesquisáveis. Se o usuário mencionar um arquivo .pdf ou pedir para produzir um, use esta habilidade.

O que é PDF?

Esta habilidade oferece um guia abrangente para processamento de arquivos PDF usando bibliotecas Python e ferramentas de linha de comando. Ela cobre operações essenciais como leitura, extração de texto e tabelas, mesclagem, divisão, rotação de páginas, criação de PDFs, preenchimento de formulários, criptografia/descriptografia, extração de imagens e OCR para PDFs escaneados. As bibliotecas Python suportadas incluem pypdf para operações básicas e manipulação de metadados, pdfplumber para extração avançada de layout e tabelas, e reportlab para criação de PDFs com subscritos/sobrescritos (com a importante observação de evitar caracteres Unicode de subscrito/sobrescrito). Ferramentas de linha de comando como pdftotext, qpdf e pdftk também são abordadas para tarefas rápidas, como extração de texto, mesclagem, divisão e rotação. A habilidade é útil para desenvolvedores e usuários que precisam automatizar tarefas de processamento de PDF, e inclui referências a documentos complementares (REFERENCE.md e FORMS.md) para recursos avançados e preenchimento de formulários. O guia enfatiza práticas recomendadas, como usar tags XML do ReportLab para subscritos/sobrescritos em vez de caracteres Unicode problemáticos.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/anthropics/skills/tree/main/skills/pdf

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

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 funcionalidades avançadas, bibliotecas JavaScript e exemplos detalhados, consulte REFERENCE.md. Se você 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):
        tables = page.extract_tables()
        for j, table in enumerate(tables):
            print(f"Tabela {j+1} na página {i+1}:")
            for row in table:
                print(row)

Extração Avançada de Tabelas

import pandas as pd

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

# Combinar todas as tabelas
if all_tables:
    combined_df = pd.concat(all_tables, ignore_index=True)
    combined_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)
width, height = letter

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

# Adicionar uma linha
c.line(100, height - 140, 400, height - 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)
styles = getSampleStyleSheet()
story = []

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

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

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

# Construir PDF
doc.build(story)

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 caixas pretas sólidas.

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

styles = getSampleStyleSheet()

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

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

Para texto desenhado em 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
images = convert_from_path('escaneado.pdf')

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

print(texto)

Adicionar Marca d'Água

from pypdf import PdfReader, PdfWriter

# Criar marca d'água (ou carregar existente)
watermark = 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(watermark)
    writer.add_page(page)

with open("com_marca_dagua.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 com 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_dono")

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

Referência Rápida

TarefaMelhor FerramentaComando/Código
Mesclar PDFspypdfwriter.add_page(page)
Dividir PDFspypdfUma página por arquivo
Extrair textopdfplumberpage.extract_text()
Extrair tabelaspdfplumberpage.extract_tables()
Criar PDFsreportlabCanvas ou Platypus
Mesclar via 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 do 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

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 \

Habilidades Relacionadas