Communitygithub.com

Procesamiento de PDF

Usa esta habilidad siempre que el usuario quiera hacer algo con archivos PDF. Esto incluye leer o extraer texto/tablas de PDFs, combinar o fusionar varios PDFs en uno, dividir PDFs, rotar páginas, añadir marcas de agua, crear nuevos PDFs, rellenar formularios PDF, cifrar/descifrar PDFs, extraer imágenes y OCR en PDFs escaneados para hacerlos buscables. Si el usuario menciona un archivo .pdf o pide producir uno, usa esta habilidad.

¿Qué es Procesamiento de PDF?

Esta habilidad proporciona una guía completa para el procesamiento de archivos PDF utilizando bibliotecas de Python y herramientas de línea de comandos. Es útil para cualquier desarrollador o agente de IA que necesite manipular documentos PDF de manera eficiente, cubriendo tareas comunes como extraer texto y tablas, fusionar, dividir, rotar páginas, añadir marcas de agua, crear PDFs desde cero, realizar OCR en documentos escaneados y proteger con contraseña los archivos. La guía se basa en bibliotecas populares como pypdf, pdfplumber, reportlab, así como herramientas CLI como qpdf y pdftotext. Está diseñada para entornos Python en plataformas como Claude Code, Cursor o Codex, y ofrece ejemplos de código listos para usar junto con notas importantes, como evitar caracteres Unicode de subíndice/superíndice en reportlab. Para formularios o características avanzadas, remite a archivos complementarios (FORMS.md, REFERENCE.md).

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/LiChangZheng10086/doyin_ai_video/tree/HEAD/.agents/skills/pdf

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 las operaciones esenciales de procesamiento de PDF utilizando bibliotecas de Python y herramientas de línea de comandos. Para funciones avanzadas, bibliotecas de 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("document.pdf")
print(f"Páginas: {len(reader.pages)}")

# Extraer texto
text = ""
for page in reader.pages:
    text += 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("merged.pdf", "wb") as output:
    writer.write(output)

Dividir 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)

Extraer metadatos

reader = PdfReader("document.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("input.pdf")
writer = PdfWriter()

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

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

pdfplumber - Extracción de texto y tablas

Extraer texto con diseño

import pdfplumber

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

Extraer tablas

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

Extracción avanzada de tablas

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:  # Verificar si 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("extracted_tables.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("hello.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("report.pdf", pagesize=letter)
styles = getSampleStyleSheet()
story = []

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

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

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

# Construir PDF
doc.build(story)

Subíndices y superíndices

IMPORTANTE: Nunca uses caracteres Unicode de subíndice/superíndice (₀₁₂₃₄₅₆₇₈₉, ⁰¹²³⁴⁵⁶⁷⁸⁹) en PDFs de ReportLab. Las fuentes integradas 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: usar etiqueta <sub>
chemical = Paragraph("H<sub>2</sub>O", styles['Normal'])

# Superíndices: usar etiqueta <super>
squared = 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 input.pdf output.txt

# Extraer texto conservando el diseño
pdftotext -layout input.pdf output.txt

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

qpdf

# Fusionar PDFs
qpdf --empty --pages file1.pdf file2.pdf -- merged.pdf

# Dividir páginas
qpdf input.pdf --pages . 1-5 -- pages1-5.pdf
qpdf input.pdf --pages . 6-10 -- pages6-10.pdf

# Rotar páginas
qpdf input.pdf output.pdf --rotate=+90:1  # Rotar página 1 90 grados

# Eliminar contraseña
qpdf --password=mypassword --decrypt encrypted.pdf decrypted.pdf

pdftk (si está disponible)

# Fusionar
pdftk file1.pdf file2.pdf cat output merged.pdf

# Dividir
pdftk input.pdf burst

# Rotar
pdftk input.pdf rotate 1east output rotated.pdf

Tareas comunes

Extraer texto de PDFs escaneados

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

# Convertir PDF a imágenes
images = convert_from_path('scanned.pdf')

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

print(text)

Añadir marca de agua

from pypdf import PdfReader, PdfWriter

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

# Aplicar a todas las páginas
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)

Extraer imágenes

# Usando pdfimages (poppler-utils)
pdfimages -j input.pdf output_prefix

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

Protección con contraseña

from pypdf import PdfReader, PdfWriter

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

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

# Añadir contraseña
writer.encrypt("userpassword", "ownerpassword")

with open("encrypted.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 en línea de comandosqpdfqpdf --empty --pages ...
OCR en PDFs escaneadospytesseractConvertir a imagen primero
Rellenar formularios PDFpdf-lib o pypdf (ver FORMS.md)Consulta 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 12 individual skills — each has its own dedicated page.

LiChangZheng10086/doyin_ai_video

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction.

LiChangZheng10086/doyin_ai_video

Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIR...

LiChangZheng10086/doyin_ai_video

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.

LiChangZheng10086/doyin_ai_video

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.

LiChangZheng10086/doyin_ai_video

Grill me about specs for the workflows I want to build, within this workspace.

LiChangZheng10086/doyin_ai_video

智能 PPT 生成器。支持 7 种视觉风格(乐高/波普/黏土/黑白/商务/学术/科技),具备根据内容自动推荐风格、生成大纲、绘制配图并组装成片的全自动能力。

LiChangZheng10086/doyin_ai_video

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.

LiChangZheng10086/doyin_ai_video

Diagnose and fix React codebase health issues. Use when reviewing React code, fixing performance problems, auditing security, or improving code quality.

LiChangZheng10086/doyin_ai_video

Sentry error monitoring and performance tracing patterns for Next.js applications.

LiChangZheng10086/doyin_ai_video

Simplify and refine recently modified code for clarity and consistency. Use after writing code to improve readability without changing functionality.

LiChangZheng10086/doyin_ai_video

✅ "你知道今天所有大模型能读懂你的话,全靠一个叫Transformer的架构吗?"

LiChangZheng10086/doyin_ai_video

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