CommunityProgramación y desarrollogithub.com

pdf

Usa esta habilidad cada vez que el usuario quiera hacer algo con archivos PDF, como leer o extraer texto/tablas, combinar o dividir PDFs, rotar páginas, añadir marcas de agua, crear nuevos PDFs, llenar formularios, cifrar/descifrar, extraer imágenes y realizar OCR en PDFs escaneados.

¿Qué es pdf?

Esta habilidad de PDF proporciona un conjunto completo de guías y ejemplos de código para procesar archivos PDF utilizando bibliotecas de Python y herramientas de línea de comandos. Está diseñada para ayudar a desarrolladores y agentes de IA a realizar operaciones como extraer texto y tablas, fusionar y dividir documentos, rotar páginas, añadir marcas de agua, crear PDFs desde cero, llenar formularios, proteger con contraseña y realizar OCR en documentos escaneados. La habilidad soporta las bibliotecas Python `pypdf`, `pdfplumber` y `reportlab`, así como herramientas CLI como `pdftotext`, `qpdf` y `pdftk`. Además, incluye advertencias importantes para evitar errores comunes (como el uso incorrecto de subíndices/superíndices Unicode en ReportLab) y referencias a documentación complementaria (REFERENCE.md, FORMS.md) para casos de uso avanzados o específicos.

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

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Guía de Procesamiento de PDF

Descripción General

Esta guía cubre operaciones esenciales de procesamiento de PDF utilizando bibliotecas de Python y herramientas de línea de comandos. Para funciones avanzadas, bibliotecas JavaScript y ejemplos detallados, consulta REFERENCE.md. Si necesitas rellenar un formulario PDF, lee FORMS.md y sigue sus instrucciones.

Inicio Rápido

from pypdf import PdfReader, PdfWriter

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

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

Bibliotecas de Python

pypdf - Operaciones Básicas

Fusionar 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("fusionado.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)

Extraer Metadatos

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

Rotar Páginas

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

page = reader.pages[0]
page.rotate(90)  # Rotar 90 grados en sentido horario
writer.add_page(page)

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

pdfplumber - Extracción de Texto y Tablas

Extraer Texto con Diseño

import pdfplumber

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

Extraer Tablas

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"Tabla {j+1} en la página {i+1}:")
            for row in table:
                print(row)

Extracción Avanzada de Tablas

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 que la tabla no esté vacía
                df = pd.DataFrame(table[1:], columns=table[0])
                all_tables.append(df)

# Combinar todas las tablas
if all_tables:
    combined_df = pd.concat(all_tables, ignore_index=True)
    combined_df.to_excel("tablas_extraidas.xlsx", index=False)

reportlab - Crear PDFs

Creación Básica de PDF

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

c = canvas.Canvas("hola.pdf", pagesize=letter)
width, height = letter

# Añadir texto
c.drawString(100, height - 100, "¡Hola Mundo!")
c.drawString(100, height - 120, "Este es un PDF creado con reportlab")

# Añadir una línea
c.line(100, height - 140, 400, height - 140)

# Guardar
c.save()

Crear PDF con Múltiples Páginas

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

doc = SimpleDocTemplate("informe.pdf", pagesize=letter)
styles = getSampleStyleSheet()
historia = []

# Añadir contenido
titulo = Paragraph("Título del Informe", styles['Title'])
historia.append(titulo)
historia.append(Spacer(1, 12))

cuerpo = Paragraph("Este es el cuerpo del informe. " * 20, styles['Normal'])
historia.append(cuerpo)
historia.append(PageBreak())

# Página 2
historia.append(Paragraph("Página 2", styles['Heading1']))
historia.append(Paragraph("Contenido para la página 2", styles['Normal']))

# Construir PDF
doc.build(historia)

Subíndices y Superíndices

IMPORTANTE: Nunca uses caracteres Unicode de subíndice/superíndice (₀₁₂₃₄₅₆₇₈₉, ⁰¹²³⁴⁵⁶⁷⁸⁹) en PDFs de ReportLab. Las fuentes incorporadas no incluyen estos glifos, lo que hace que se rendericen como cuadros negros sólidos.

En su lugar, usa las etiquetas XML de ReportLab en objetos Paragraph:

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

styles = getSampleStyleSheet()

# Subíndices: usa la etiqueta <sub>
quimica = Paragraph("H<sub>2</sub>O", styles['Normal'])

# Superíndices: usa la etiqueta <super>
cuadrado = Paragraph("x<super>2</super> + y<super>2</super>", styles['Normal'])

Para texto dibujado en canvas (no objetos Paragraph), ajusta manualmente el tamaño y la posición de la fuente en lugar de usar subíndices/superíndices Unicode.

Herramientas de Línea de Comandos

pdftotext (poppler-utils)

# Extraer texto
pdftotext entrada.pdf salida.txt

# Extraer texto conservando el diseño
pdftotext -layout entrada.pdf salida.txt

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

qpdf

# Fusionar PDFs
qpdf --empty --pages archivo1.pdf archivo2.pdf -- fusionado.pdf

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

# Rotar páginas
qpdf entrada.pdf salida.pdf --rotate=+90:1  # Rotar página 1 en 90 grados

# Eliminar contraseña
qpdf --password=micontraseña --decrypt cifrado.pdf descifrado.pdf

pdftk (si está disponible)

# Fusionar
pdftk archivo1.pdf archivo2.pdf cat output fusionado.pdf

# Dividir
pdftk entrada.pdf burst

# Rotar
pdftk entrada.pdf rotate 1east output rotado.pdf

Tareas Comunes

Extraer Texto de PDF Escaneados

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

# Convertir PDF a imágenes
imagenes = convert_from_path('escaneado.pdf')

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

print(texto)

Añadir Marca de Agua

from pypdf import PdfReader, PdfWriter

# Crear marca de agua (o cargar una existente)
marca_agua = PdfReader("marca_agua.pdf").pages[0]

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

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

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

Extraer Imágenes

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

# Esto extrae todas las imágenes como prefijo_salida-000.jpg, prefijo_salida-001.jpg, etc.

Protección con Contraseña

from pypdf import PdfReader, PdfWriter

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

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

# Añadir contraseña
writer.encrypt("contraseñausuario", "contraseñapropietario")

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

Referencia Rápida

TareaMejor HerramientaComando/Código
Fusionar PDFspypdfwriter.add_page(page)
Dividir PDFspypdfUna página por archivo
Extraer textopdfplumberpage.extract_text()
Extraer tablaspdfplumberpage.extract_tables()
Crear PDFsreportlabCanvas o Platypus
Fusión desde línea de comandosqpdfqpdf --empty --pages ...
OCR en PDF escaneadospytesseractConvertir a imagen primero
Rellenar formularios PDFpdf-lib o pypdf (ver FORMS.md)Ver FORMS.md

Próximos Pasos

  • Para uso avanzado de pypdfium2, consulta REFERENCE.md
  • Para bibliotecas JavaScript (pdf-lib), consulta REFERENCE.md
  • Si necesitas rellenar un formulario PDF, sigue las instrucciones en FORMS.md
  • Para guías de solución de problemas, consulta 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 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation.

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 "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.

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 "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.

Skills relacionados