Communitygithub.com

bg-szy/TOP-SKILLS

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 é TOP-SKILLS?

Esta habilidade fornece um guia completo para processamento de PDFs usando bibliotecas Python e ferramentas de linha de comando. Ela abrange operações essenciais como leitura, extração de texto e tabelas, mesclagem e divisão de PDFs, rotação de páginas, criação de novos PDFs, adição de marcas d'água, extração de imagens, OCR para PDFs escaneados e proteção por senha. As plataformas suportadas incluem Python (pypdf, pdfplumber, reportlab, pytesseract, pdf2image) e ferramentas de linha de comando (pdftotext, qpdf, pdftk). O guia é útil para desenvolvedores e agentes de IA que precisam automatizar tarefas de manipulação de PDF de forma eficiente, com exemplos práticos e 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/bg-szy/TOP-SKILLS/tree/HEAD/skills/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 pagina in reader.pages:
    texto += pagina.extract_text()

Bibliotecas Python

pypdf - Operações Básicas

Mesclar PDFs

from pypdf import PdfWriter, PdfReader

writer = PdfWriter()
for arquivo_pdf in ["doc1.pdf", "doc2.pdf", "doc3.pdf"]:
    reader = PdfReader(arquivo_pdf)
    for pagina in reader.pages:
        writer.add_page(pagina)

with open("mesclado.pdf", "wb") as saida:
    writer.write(saida)

Dividir PDF

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

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

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

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

pdfplumber - Extração de Texto e Tabelas

Extrair Texto com Layout

import pdfplumber

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

Extrair Tabelas

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

Extração Avançada de Tabelas

import pandas as pd

with pdfplumber.open("documento.pdf") as pdf:
    todas_tabelas = []
    for pagina in pdf.pages:
        tabelas = pagina.extract_tables()
        for tabela in tabelas:
            if tabela:  # Verifica 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:
    df_combinado = pd.concat(todas_tabelas, ignore_index=True)
    df_combinado.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 Várias 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()
historia = []

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

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

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

# Construir PDF
doc.build(historia)

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

estilos = getSampleStyleSheet()

# Subscritos: use a tag <sub>
quimica = 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 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
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 pagina in reader.pages:
    pagina.merge_page(marca)
    writer.add_page(pagina)

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

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 pagina in reader.pages:
    writer.add_page(pagina)

# Adicionar senha
writer.encrypt("senhausuario", "senhadono")

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

Referência Rápida

TarefaMelhor FerramentaComando/Código
Mesclar PDFspypdfwriter.add_page(pagina)
Dividir PDFspypdfUma página por arquivo
Extrair textopdfplumberpagina.extract_text()
Extrair tabelaspdfplumberpagina.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 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

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

bg-szy/TOP-SKILLS

Brand-first landing page designer — runs a brand-identity interview (colors, typography, shape language), then generates and iterates on a polished landing page via Stitch with deployment-ready HTML. Use when the user asks to create, design, or build a landing page, homepage, or marketing page and has no established visual direction. Skip when they have a design mockup, need a dashboard or app UI, are working at component level, building a multi-page app, or restyling with known design tokens — use frontend-design instead.

bg-szy/TOP-SKILLS

Fill out Microsoft Azure Landing Zone (ALZ) Accelerator checklists by interviewing the user, mapping their Azure subscriptions, integrating IP addressing documentation, and applying Microsoft Cloud Adoption Framework best practices. Produces a completed Excel checklist (.xlsx) ready for ALZ deployment. Use this skill whenever the user mentions Azure Landing Zone, ALZ checklist, landing zone accelerator, platform landing zone configuration, ALZ bootstrap, hub-and-spoke setup, Azure network topology planning, or wants to fill out any ALZ-related checklist or configuration file. Also trigger when the user uploads an Excel file that contains tabs like "Accelerator - Bootstrap", "Accelerator - Bicep", or "Accelerator - Terraform".

bg-szy/TOP-SKILLS

Compose a premium, animated landing page section by section in Next.js + Tailwind + Motion (Framer Motion) — built on a real design system, with editorial copy and motion that feels human-crafted, not template-generated. Use when building or rebuilding a landing page, marketing site, or hero/feature/pricing/CTA sections that need to look production-ready and bespoke from day one.

bg-szy/TOP-SKILLS

Write high-converting landing page copy using proven frameworks like PAS (Problem-Agitate-Solution), AIDA, and StoryBrand. Creates headlines, value propositions, CTAs, and full page sections optimized for conversion. Use when users need landing page copy, sales page content, or marketing website text.

bg-szy/TOP-SKILLS

Optimize landing pages for conversions, performance, and SEO. Use when improving landing pages, increasing conversions, or optimizing page performance.

bg-szy/TOP-SKILLS

Review investment portfolios for risk, diversification, fees. Asset allocation recommendations, tax-loss harvesting, rebalancing.

bg-szy/TOP-SKILLS

Beads Viewer - Graph-aware triage engine for Beads projects. Computes PageRank, betweenness, critical path, and cycles. Use --robot-* flags for AI agents.

bg-szy/TOP-SKILLS

CI red? Call us. Pipeline fire brigade deploys. Use when user mentions CI failures, build errors, test failures, or pipeline issues. Do NOT load for: local builds, standard implementation work, reviews, or setup.

bg-szy/TOP-SKILLS

CASS Memory System - procedural memory for AI coding agents. Three-layer cognitive architecture with confidence decay, anti-pattern learning, cross-agent knowledge transfer, trauma guard safety system. Bun/TypeScript CLI.

bg-szy/TOP-SKILLS

Mandatory entry point: read this first for any request to make, create, edit, animate, or render a video, animation, or motion graphic, including a promo, explainer, captioned clip, title card, overlay, slideshow or interactive deck, Remotion port, or any HyperFrames HTML composition. Also use it to inspect, diagnose, validate, preview, publish, or batch-render an existing HyperFrames project. Inputs may be a website URL, GitHub PR, Figma design or URL, text or brief, existing footage, or music. It resumes project state, captures intent when applicable, selects and installs the owning workflow, and routes domain capabilities. HyperFrames is the default output framework unless the user explicitly chooses another framework for the deliverable or asks only to record a browser session.

bg-szy/TOP-SKILLS

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

bg-szy/TOP-SKILLS

Use when the user asks to "pre-launch check the landing page", "run a Quality-Score preflight", or "verify ad-to-page message match before launch"; produces an ad↔page continuity report — message-match gaps, above-the-fold check, page-speed read, form-friction count, mobile-render flags — as a pass/fix punch list. Not for redesigning or rewriting the page — use landing-optimizer; not for scoring the account or the RQS — use ad-account-auditor. 落地页体验预检/广告落地页一致性检查

bg-szy/TOP-SKILLS

Use when the user asks to "optimize our landing page for influencer traffic", "fix our promo-code landing page", or "improve conversion from a creator campaign"; produces a message-match audit, page-structure and social-proof recommendations, a promo-code/CTA conversion plan, and an A/B test roadmap. Not for measuring campaign results after launch — use performance-analyzer.

bg-szy/TOP-SKILLS

Audit a landing page, sales page or checkout page for conversion leaks and return a fix list ordered by expected revenue impact. Use when asked to review, critique or improve a landing page, sales page, opt-in page, product page or checkout flow, when conversion rate is low, when paid traffic is not converting, or when someone asks "why isn't this page converting" or wants a CRO / landing page review.

bg-szy/TOP-SKILLS

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

bg-szy/TOP-SKILLS

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

bg-szy/TOP-SKILLS

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

bg-szy/TOP-SKILLS

Account assets, equity and fund positions, P&L, cash flow records, account statements, margin ratios, buy-power estimates, order management, and DCA recurring investments via Longbridge (most require Trade permission). Frameworks: portfolio diagnosis, rebalancing, asset allocation, risk analysis (VaR/CVaR), performance attribution, and tax-loss harvesting. Triggers: "持仓", "账户", "盈亏", "资产", "对账单", "下单", "买入", "卖出", "撤单", "定投", "组合诊断", "再平衡", "资产配置", "风险分析", "绩效归因", "税损收割", "持倉", "賬戶", "盈虧", "對賬單", "下單", "買入", "賣出", "組合診斷", "再平衡", "稅損收割", "positions", "portfolio", "P&L", "order", "buy", "sell", "DCA", "statement", "risk analysis", "rebalancing", "tax harvesting", "我的风险", "持仓风险", "风险敞口", "資產", "資產配置", "風險分析", "績效歸因", "撤單

bg-szy/TOP-SKILLS

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

bg-szy/TOP-SKILLS

Process video files with audio extraction, format conversion (mp4, webm), and Whisper transcription. Use when user mentions video conversion, audio extraction, transcription, mp4, webm, ffmpeg, or whisper transcription.

Habilidades Relacionadas