docx

Use esta habilidade sempre que o usuário quiser criar, ler, editar ou manipular documentos do Word (.docx) ou modelos do Word (.dotx). Os gatilhos incluem: qualquer menção a 'documento Word', 'arquivo .docx', '.dotx', ou solicitações para produzir documentos profissionais com formatação como sumário, títulos, numeração de páginas ou timbres. Use também ao extrair ou reorganizar conteúdo de arquivos .docx ou .dotx, inserir ou substituir imagens em documentos, realizar localizar e substituir em arquivos do Word, trabalhar com controle de alterações ou comentários, ou converter conteúdo em um documento Word polido. Se o usuário pedir um 'relatório', 'memorando', 'carta', 'modelo' ou similar como arquivo Word ou .docx, use esta habilidade. NÃO use para PDFs, planilhas, Google Docs ou tarefas gerais de codificação não relacionadas à geração de documentos.

O que é docx?

A habilidade **docx** capacita agentes de IA a criar, editar e analisar documentos do Microsoft Word (.docx e .dotx) programaticamente. Ela cobre três abordagens principais: (1) criação de novos documentos com a biblioteca Node.js `docx`, que já vem pré-instalada, mas requer cuidado com configurações como tamanho de página (padrão A4), larguras de tabela, sombreamento, listas, quebras de página, sumários e alinhamento com pontos; (2) edição de documentos existentes descompactando o .docx, editando o XML diretamente e recompactando, com scripts auxiliares para mesclar execuções de texto fragmentado e validar contra o esquema XSD; e (3) leitura de conteúdo via `pandoc` para Markdown. A habilidade também gerencia controle de alterações (tracked changes) e comentários, oferecendo scripts Python para aceitar alterações e inserir comentários corretamente, incluindo a marcação de parágrafos excluídos. É útil para automatizar a geração de relatórios, contratos, memorandos e outros documentos com formatação complexa, suportando fluxos de trabalho de revisão e colaboração. As plataformas suportadas incluem ambientes com Node.js, Python, Pandoc, LibreOffice e Poppler (pdftoppm).

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

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

Criação, edição e análise de DOCX

Um .docx é um arquivo ZIP contendo arquivos XML. Escolha sua abordagem conforme a tarefa:

TarefaAbordagem
Criar um novo documentoEscreva um script docx (npm) — veja as pegadinhas abaixo
Editar um documento existenteunzip → edite word/document.xml → zip (docx-js não consegue abrir arquivos existentes)
Ler conteúdopandoc -t markdown file.docx

Os caminhos de script abaixo são relativos ao diretório desta habilidade.

Criando com docx-js — pegadinhas

docx está pré-instalado — não execute npm install primeiro; escreva o script e use require('docx') diretamente. Apenas se esse require falhar: npm install docx. O modelo conhece a API; estas são as armadilhas:

  • O tamanho da página padrão é A4. Para Carta (EUA), defina page: { size: { width: 12240, height: 15840 } } (DXA; 1440 = 1″).
  • Paisagem: passe as dimensões retrato e orientation: PageOrientation.LANDSCAPE — o docx-js troca largura/altura internamente.
  • Tabelas precisam de larguras duplas: defina columnWidths na tabela E width em cada célula, ambos em WidthType.DXA (PERCENTAGE quebra no Google Docs). As larguras das colunas devem somar a largura da tabela.
  • Sombreamento de tabela: use ShadingType.CLEAR, nunca SOLID (renderiza preto).
  • Listas: nunca insira • literalmente; use uma configuração numbering com LevelFormat.BULLET.
  • ImageRun requer type: ("png", "jpg", …).
  • PageBreak deve estar dentro de um Paragraph.
  • Nunca use \n — use elementos Paragraph separados.
  • SUMÁRIO (TOC): os títulos devem usar HeadingLevel.* embutidos; estilos de título personalizados precisam de outlineLevel definido ou não aparecerão.
  • Não use uma tabela como linha horizontal — use uma borda inferior de parágrafo.
  • Pontilhado / alinhado à direita na mesma linha: use PositionalTab (alignment: PositionalTabAlignment.RIGHT, leader: PositionalTabLeader.DOT) dentro de um TextRun, não pontos . literais ou espaçamento.

Verifique a saída

Após escrever um .docx, renderize-o e veja-o:

python scripts/office/soffice.py --headless --convert-to pdf output.docx
pdftoppm -jpeg -r 100 output.pdf page
ls page-*.jpg   # em seguida, Leia as imagens

pdftoppm preenche com zeros os números de página até a largura da contagem de páginas (page-01.jpg…page-12.jpg).

Editando documentos existentes

Documentos .doc legados devem ser convertidos primeiro: python scripts/office/soffice.py --headless --convert-to docx file.doc.

unzip -q doc.docx -d unpacked/
find unpacked -type l -delete   # remove entradas de link simbólico — docx de fontes externas não é confiável
python scripts/merge_runs.py unpacked/   # coalesce execuções fragmentadas para que o texto seja encontrável
# edite unpacked/word/document.xml no local — NÃO reformate ou prettifique
(cd unpacked && rm -f ../out.docx && zip -Xr ../out.docx .)
python scripts/office/validate.py out.docx --original doc.docx   # verificações XSD; --auto-repair corrige problemas comuns
# redlining? adicione --author "<o nome sob o qual você fez o redline>" para verificar se cada edição está rastreada

O Word divide o texto em muitas execuções <w:r> (IDs de revisão, marcadores de verificação ortográfica), então uma frase que você vê no documento muitas vezes não existe como uma string contígua no XML. merge_runs.py mescla execuções adjacentes com formatação idêntica em word/document.xml sem alterar conteúdo ou renderização; ele também aceita um .docx diretamente (python scripts/merge_runs.py doc.docx -o merged.docx).

Controle de alterações: ao fazer redlining, valide com --author "<o nome sob o qual você fez o redline>" (precisa de --original) — ele relata qualquer texto que você alterou sem um <w:ins>/<w:del> ao redor, o que é fácil de acontecer acidentalmente e invisível na visualização de aceitação. Envolva as execuções em <w:ins>/<w:del> com atributos w:id, w:author, w:date. Dentro de <w:del>, o elemento de texto é <w:delText>, não <w:t>. Uma marca de parágrafo deletada (<w:pPr><w:rPr><w:del w:id=".." w:author=".." w:date=".."/></w:rPr></w:pPr>) significa "mesclar este parágrafo no próximo" — então deletar um parágrafo por completo é isso mais um <w:del> em torno de cada execução. O <w:del/> deve vir antes dos outros filhos do rPr; sua ordem é imposta pelo esquema.

Para produzir uma cópia limpa com todas as alterações aceitas: python scripts/accept_changes.py in.docx out.docx.

Aceitar uma marca de parágrafo deletada deve juntar esse parágrafo ao abaixo dele, então um parágrafo cujas execuções são todas deletadas desaparece. O Word faz isso; accept_changes.py e pandoc --track-changes=accept nem sempre. Ambos falham da mesma forma — eles removem o texto deletado, mas deixam o parágrafo vazio, que aparece como um marcador vazio perdido quando era numerado automaticamente:

  • pandoc --track-changes=accept nunca junta os parágrafos.
  • accept_changes.py (LibreOffice) os junta corretamente, exceto quando o parágrafo deletado é seguido por um parágrafo espaçador vazio.

Um marcador vazio em qualquer visualização é um artefato dessa visualização, não um defeito no documento. Verifique as exclusões de parágrafo no XML.

Comentários

Comentários exigem seis arquivos vinculados entre si. Use o helper — modo diretório quando você também for editar document.xml (economiza um ciclo de unzip/rezip), modo .docx direto caso contrário:

# Contra um diretório já descompactado (preferido ao também colocar marcadores)
python scripts/comment.py unpacked/ "O limite de taxas e despesas é muito baixo"
python scripts/comment.py unpacked/ "Concordo" --parent 0

# Contra um .docx diretamente
python scripts/comment.py contract.docx "Este limite é muito baixo" -o annotated.docx

O script escreve comments.xml, commentsExtended.xml, commentsIds.xml, commentsExtensible.xml, os relacionamentos e as substituições de tipo de conteúdo. Os IDs de comentários são atribuídos automaticamente. Em seguida, ele imprime o trecho <w:commentRangeStart>/<w:commentRangeEnd>/<w:commentReference> a ser adicionado em word/document.xml para que o comentário ancore em texto específico — até que você coloque esses marcadores, o comentário existe mas não fica visível.

Dependências

docx (npm, pré-instalado — instale apenas se require('docx') falhar) · pandoc · LibreOffice (soffice) · pdftoppm (Poppler)

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.

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

pdf

Use this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.

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.

Habilidades Relacionadas