Communitygithub.com

hankunpeng/skills

Google Antigravity 및 오픈 에이전트 스킬 생태계를 위한 맞춤형 AI 에이전트 스킬 모음입니다.

skills란 무엇인가요?

이 스킬은 AI 에이전트(Claude Code, Cursor, Codex 등)가 .docx 파일을 생성, 편집 및 분석할 수 있는 포괄적인 가이드입니다. .docx 파일이 ZIP 아카이브에 XML 파일이 포함된 구조임을 설명하고, markitdown을 사용한 텍스트 추출, docx-js(Node.js 라이브러리)를 사용한 새 문서 생성, XML을 직접 편집하여 기존 문서를 수정하는 세 가지 주요 작업 흐름을 제공합니다. 상세한 코드 예제를 통해 페이지 크기 설정(A4 기본값을 US Letter로 재정의), 스타일 정의, 글머리 기호 목록(유니코드 문자 대신 LevelFormat.BULLET 사용), 표 생성(이중 너비 설정 필수), 이미지 삽입, 하이퍼링크, 각주, 다단 레이아웃, 목차, 머리글/바닥글 등을 구현하는 방법을 제시합니다. 또한 기존 문서 편집을 위해 unpack → XML 편집 → pack의 3단계 프로세스와 함께 스마트 따옴표 사용, 변경 내용 추적 수락, 댓글 추가(comment.py 스크립트 활용) 등에 대한 모범 사례와 함께 자동 검증 스크립트(validate.py)도 포함되어 있어, 다양한 플랫폼에서 호환되는 고품질의 전문 문서를 제작할 수 있도록 지원합니다.

지원 대상✓Claude Code~Codex CLI~Cursor✓Antigravity
npx skills add hankunpeng/skills

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

DOCX 생성, 편집 및 분석

개요

.docx 파일은 XML 파일을 포함하는 ZIP 아카이브입니다.

빠른 참조

작업접근 방식
콘텐츠 읽기/분석markitdown 또는 압축 풀어 원시 XML 접근
새 문서 생성docx-js 사용 - 아래 '새 문서 만들기' 참조
기존 문서 편집압축 풀기 → XML 편집 → 다시 압축 - 아래 '기존 문서 편집' 참조

콘텐츠 읽기

# 텍스트 추출
markitdown document.docx > output.md

# 원시 XML 접근
python scripts/office/unpack.py document.docx unpacked/

변경 내용 수락

모든 변경 내용이 수락된 정리된 문서를 생성하려면:

python scripts/accept_changes.py input.docx output.docx

새 문서 만들기

JavaScript로 .docx 파일을 생성한 후 검증합니다. 설치: npm install -g docx

설정

const { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, ImageRun,
        Header, Footer, AlignmentType, PageOrientation, LevelFormat, ExternalHyperlink,
        InternalHyperlink, Bookmark, FootnoteReferenceRun, PositionalTab,
        PositionalTabAlignment, PositionalTabRelativeTo, PositionalTabLeader,
        TabStopType, TabStopPosition, Column, SectionType,
        TableOfContents, HeadingLevel, BorderStyle, WidthType, ShadingType,
        VerticalAlign, PageNumber, PageBreak } = require('docx');

const doc = new Document({ sections: [{ children: [/* 콘텐츠 */] }] });
Packer.toBuffer(doc).then(buffer => fs.writeFileSync("doc.docx", buffer));

검증

파일을 생성한 후 검증합니다. 검증이 실패하면 압축을 풀고 XML을 수정한 후 다시 압축합니다.

python scripts/office/validate.py doc.docx

페이지 크기

// 중요: docx-js는 기본값이 A4이며 US Letter가 아닙니다.
// 일관된 결과를 위해 항상 페이지 크기를 명시적으로 설정하세요.
sections: [{
  properties: {
    page: {
      size: {
        width: 12240,   // DXA 단위로 8.5인치
        height: 15840   // DXA 단위로 11인치
      },
      margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } // 1인치 여백
    }
  },
  children: [/* 콘텐츠 */]
}]

일반적인 페이지 크기 (DXA 단위, 1440 DXA = 1인치):

용지너비높이콘텐츠 너비 (1" 여백)
US Letter12,24015,8409,360
A4 (기본값)11,90616,8389,026

가로 방향: docx-js는 내부적으로 너비/높이를 바꾸므로 세로 방향 치수를 전달하고 라이브러리가 처리하도록 합니다:

size: {
  width: 12240,   // 짧은 쪽을 너비로 전달
  height: 15840,  // 긴 쪽을 높이로 전달
  orientation: PageOrientation.LANDSCAPE  // docx-js가 XML에서 너비/높이를 바꿉니다.
},
// 콘텐츠 너비 = 15840 - 왼쪽 여백 - 오른쪽 여백 (긴 쪽 사용)

스타일 (내장 제목 재정의)

기본 글꼴로 Arial(보편적으로 지원됨)을 사용합니다. 가독성을 위해 제목은 검은색으로 유지합니다.

const doc = new Document({
  styles: {
    default: { document: { run: { font: "Arial", size: 24 } } }, // 12pt 기본값
    paragraphStyles: [
      // 중요: 내장 스타일을 재정의하려면 정확한 ID를 사용하세요.
      { id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 32, bold: true, font: "Arial" },
        paragraph: { spacing: { before: 240, after: 240 }, outlineLevel: 0 } }, // TOC에 outlineLevel 필요
      { id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 28, bold: true, font: "Arial" },
        paragraph: { spacing: { before: 180, after: 180 }, outlineLevel: 1 } },
    ]
  },
  sections: [{
    children: [
      new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("제목")] }),
    ]
  }]
});

목록 (절대 유니코드 글머리 기호를 사용하지 마세요)

// ❌ 잘못된 방법 - 수동으로 글머리 기호 문자 삽입 금지
new Paragraph({ children: [new TextRun("• 항목")] })  // 나쁜 예
new Paragraph({ children: [new TextRun("\u2022 항목")] })  // 나쁜 예

// ✅ 올바른 방법 - LevelFormat.BULLET과 함께 번호 매기기 구성 사용
const doc = new Document({
  numbering: {
    config: [
      { reference: "bullets",
        levels: [{ level: 0, format: LevelFormat.BULLET, text: "•", alignment: AlignmentType.LEFT,
          style: { paragraph: { indent: { left: 720, hanging: 360 } } } }] },
      { reference: "numbers",
        levels: [{ level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.LEFT,
          style: { paragraph: { indent: { left: 720, hanging: 360 } } } }] },
    ]
  },
  sections: [{
    children: [
      new Paragraph({ numbering: { reference: "bullets", level: 0 },
        children: [new TextRun("글머리 항목")] }),
      new Paragraph({ numbering: { reference: "numbers", level: 0 },
        children: [new TextRun("번호 항목")] }),
    ]
  }]
});

// ⚠️ 각 참조는 독립적인 번호 매기기를 생성합니다.
// 동일한 참조 = 계속 (1,2,3 다음 4,5,6)
// 다른 참조 = 재시작 (1,2,3 다음 1,2,3)

표

중요: 표에는 이중 너비가 필요합니다. 표에 columnWidths를 설정하고 각 셀에 width를 모두 설정해야 합니다. 둘 다 없으면 일부 플랫폼에서 표가 잘못 렌더링됩니다.

// 중요: 일관된 렌더링을 위해 항상 표 너비를 설정하세요.
// 중요: 검정색 배경을 방지하려면 ShadingType.CLEAR를 사용하고 SOLID를 사용하지 마세요.
const border = { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" };
const borders = { top: border, bottom: border, left: border, right: border };

new Table({
  width: { size: 9360, type: WidthType.DXA }, // 항상 DXA 사용 (백분율은 Google Docs에서 깨짐)
  columnWidths: [4680, 4680], // 표 너비와 합이 일치해야 함 (DXA: 1440 = 1인치)
  rows: [
    new TableRow({
      children: [
        new TableCell({
          borders,
          width: { size: 4680, type: WidthType.DXA }, // 각 셀에도 설정
          shading: { fill: "D5E8F0", type: ShadingType.CLEAR }, // CLEAR 사용, SOLID 사용 금지
          margins: { top: 80, bottom: 80, left: 120, right: 120 }, // 셀 안쪽 여백 (내부적이며 너비에 추가되지 않음)
          children: [new Paragraph({ children: [new TextRun("셀")] })]
        })
      ]
    })
  ]
})

표 너비 계산:

항상 WidthType.DXA를 사용하세요. WidthType.PERCENTAGE는 Google Docs에서 깨집니다.

// 표 너비 = columnWidths의 합 = 콘텐츠 너비
// 1인치 여백이 있는 US Letter: 12240 - 2880 = 9360 DXA
width: { size: 9360, type: WidthType.DXA },
columnWidths: [7000, 2360]  // 표 너비와 합이 일치해야 함

너비 규칙:

  • 항상 WidthType.DXA 사용 — 절대 WidthType.PERCENTAGE 사용 금지 (Google Docs와 호환되지 않음)
  • 표 너비는 columnWidths의 합과 같아야 함
  • 셀 width는 해당 columnWidth와 일치해야 함
  • 셀 margins는 내부 안쪽 여백입니다. 콘텐츠 영역을 줄이며 셀 너비에 추가되지 않음
  • 전체 너비 표의 경우: 콘텐츠 너비 사용 (페이지 너비에서 왼쪽 및 오른쪽 여백을 뺀 값)

이미지

// 중요: type 매개변수는 필수입니다.
new Paragraph({
  children: [new ImageRun({
    type: "png", // 필수: png, jpg, jpeg, gif, bmp, svg
    data: fs.readFileSync("image.png"),
    transformation: { width: 200, height: 150 },
    altText: { title: "제목", description: "설명", name: "이름" } // 세 가지 모두 필요
  })]
})

페이지 나누기

// 중요: PageBreak는 Paragraph 안에 있어야 합니다.
new Paragraph({ children: [new PageBreak()] })

// 또는 pageBreakBefore 사용
new Paragraph({ pageBreakBefore: true, children: [new TextRun("새 페이지")] })

하이퍼링크

// 외부 링크
new Paragraph({
  children: [new ExternalHyperlink({
    children: [new TextRun({ text: "여기를 클릭", style: "Hyperlink" })],
    link: "https://example.com",
  })]
})

// 내부 링크 (책갈피 + 참조)
// 1. 대상에 책갈피 생성
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [
  new Bookmark({ id: "chapter1", children: [new TextRun("1장")] }),
]})
// 2. 연결
new Paragraph({ children: [new InternalHyperlink({
  children: [new TextRun({ text: "1장 보기", style: "Hyperlink" })],
  anchor: "chapter1",
})]})

각주

const doc = new Document({
  footnotes: {
    1: { children: [new Paragraph("출처: 2024 연례 보고서")] },
    2: { children: [new Paragraph("방법론은 부록 참조")] },
  },
  sections: [{
    children: [new Paragraph({
      children: [
        new TextRun("수익 15% 증가"),
        new FootnoteReferenceRun(1),
        new TextRun(" 조정 지표 사용"),
        new FootnoteReferenceRun(2),
      ],
    })]
  }]
});

탭 정지

// 같은 줄에 텍스트 오른쪽 정렬 (예: 제목 반대편에 날짜)
new Paragraph({
  children: [
    new TextRun("회사명"),
    new TextRun("\t2025년 1월"),
  ],
  tabStops: [{ type: TabStopType.RIGHT, position: TabStopPosition.MAX }],
})

// 점선 지시선 (예: TOC 스타일)
new Paragraph({
  children: [
    new TextRun("서론"),
    new TextRun({ children: [
      new PositionalTab({
        alignment: PositionalTabAlignment.RIGHT,
        relativeTo: PositionalTabRelativeTo.MARGIN,
        leader: PositionalTabLeader.DOT,
      }),
      "3",
    ]}),
  ],
})

다단 레이아웃

// 동일 너비 단
sections: [{
  properties: {
    column: {
      count: 2,          // 단 개수
      space: 720,        // 단 사이 간격 (DXA) (720 = 0.5인치)
      equalWidth: true,
      separate: true,    // 단 사이 세로선
    },
  },
  children: [/* 콘텐츠는 단 사이에 자연스럽게 흐릅니다 */]
}]

// 사용자 정의 너비 단 (equalWidth는 false여야 함)
sections: [{
  properties: {
    column: {
      equalWidth: false,
      children: [
        new Column({ width: 5400, space: 720 }),
        new Column({ width: 3240 }),
      ],
    },
  },
  children: [/* 콘텐츠 */]
}]

type: SectionType.NEXT_COLUMN을 사용하는 새 섹션으로 단 나누기를 강제합니다.

목차

// 중요: 제목은 HeadingLevel만 사용해야 합니다. 사용자 정의 스타일 사용 금지
new TableOfContents("목차", { hyperlink: true, headingStyleRange: "1-3" })

머리글/바닥글

sections: [{
  properties: {
    page: { margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } } // 1440 = 1인치
  },
  headers: {
    default: new Header({ children: [new Paragraph({ children: [new TextRun("머리글")] })] })
  },
  footers: {
    default: new Footer({ children: [new Paragraph({
      children: [new TextRun("페이지 "), new TextRun({ children: [PageNumber.CURRENT] })]
    })] })
  },
  children: [/* 콘텐츠 */]
}]

docx-js의 중요 규칙

  • 페이지 크기를 명시적으로 설정하세요 - docx-js는 기본값이 A4입니다. 미국 문서의 경우 US Letter(12240 x 15840 DXA)를 사용하세요.
  • 가로: 세로 방향 치수를 전달하세요 - docx-js는 내부적으로 너비/높이를 바꿉니다. 짧은 쪽을 width로, 긴 쪽을 height로 전달하고 orientation: PageOrientation.LANDSCAPE를 설정하세요.
  • 절대 \n을 사용하지 마세요 - 별도의 Paragraph 요소를 사용하세요.
  • 절대 유니코드 글머리 기호를 사용하지 마세요 - 번호 매기기 구성과 함께 LevelFormat.BULLET을 사용하세요.
  • PageBreak는 Paragraph 안에 있어야 합니다 - 단독으로 사용하면 잘못된 XML이 생성됩니다.
  • ImageRun에는 type이 필요합니다 - 항상 png/jpg 등을 지정하세요.
  • 항상 DXA로 표 width를 설정하세요 - 절대 WidthType.PERCENTAGE를 사용하지 마세요 (Google Docs에서 깨짐).
  • 표에는 이중 너비가 필요합니다 - columnWidths 배열과 셀 width 모두 일치해야 합니다.
  • 표 너비 = columnWidths의 합 - DXA의 경우 정확히 합산되는지 확인하세요.
  • 항상 셀 여백을 추가하세요 - 가독성 있는 안쪽 여백을 위해 margins: { top: 80, bottom: 80, left: 120, right: 120 }을 사용하세요.
  • ShadingType.CLEAR를 사용하세요 - 표 음영에 SOLID를 절대 사용하지 마세요.
  • 표를 구분선/선으로 절대 사용하지 마세요 - 셀은 최소 높이를 가지며 빈 상자로 렌더링됩니다(머리글/바닥글 포함). Paragraph에서 border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: "2E75B6", space: 1 } }을 대신 사용하세요. 두 열 바닥글의 경우 표 대신 탭 정지를 사용하세요('탭 정지' 섹션 참조).
  • TOC는 HeadingLevel만 필요합니다 - 제목 단락에 사용자 정의 스타일을 사용하지 마세요.
  • 내장 스타일 재정의 - 정확한 ID("Heading1", "Heading2" 등)를 사용하세요.
  • outlineLevel 포함 - TOC에 필요합니다 (H1의 경우 0, H2의 경우 1 등).

기존 문서 편집

모든 3단계를 순서대로 따르세요.

1단계: 압축 풀기

python scripts/office/unpack.py document.docx unpacked/

XML을 추출하고, 예쁘게 출력하며, 인접한 실행을 병합하고, 스마트 따옴표를 XML 엔티티(“ 등)로 변환하여 편집 중에도 유지되도록 합니다. --merge-runs false를 사용하여 실행 병합을 건너뛸 수 있습니다.

2단계: XML 편집

unpacked/word/에 있는 파일을 편집합니다. 패턴은 아래 XML 참조를 참조하세요.

변경 내용 추적 및 주석의 작성자로 "Claude"를 사용하세요. 사용자가 명시적으로 다른 이름을 요청하는 경우는 예외입니다.

문자열 교체에는 Edit 도구를 직접 사용하세요. Python 스크립트를 작성하지 마세요. 스크립트는 불필요한 복잡성을 초래합니다. Edit 도구는 무엇이 교체되고 있는지 정확히 보여줍니다.

중요: 새 콘텐츠에는 스마트 따옴표를 사용하세요. 아포스트로피나 따옴표가 있는 텍스트를 추가할 때는 XML 엔티티를 사용하여 스마트 따옴표를 생성하세요:

<!-- 전문적인 타이포그래피를 위해 다음 엔티티를 사용하세요 -->
<w:t>여기에&#x2019;s a quote: &#x201C;안녕하세요&#x201D;</w:t>
엔티티문자
&#x2018;' (왼쪽 작은따옴표)
&#x2019;' (오른쪽 작은따옴표 / 아포스트로피)
&#x201C;" (왼쪽 큰따옴표)
&#x201D;" (오른쪽 큰따옴표)

주석 추가: 여러 XML 파일에 걸쳐 상용구를 처리하려면 comment.py를 사용하세요(텍스트는 미리 이스케이프된 XML이어야 함):

python scripts/comment.py unpacked/ 0 "주석 텍스트 with &amp; and &#x2019;"
python scripts/comment.py unpacked/ 1 "답변 텍스트" --parent 0  # 주석 0에 답변
python scripts/comment.py unpacked/ 0 "텍스트" --author "사용자 정의 작성자"  # 사용자 정의 작성자 이름

그런 다음 document.xml에 마커를 추가합니다('XML 참조'의 주석 참조).

3단계: 압축

python scripts/office/pack.py unpacked/ output.docx --original document.docx

자동 복구로 검증하고, XML을 압축하며, 원본 관계를 유지하고, 익숙하지 않은 네임스페이스를 보존합니다.


XML 참조

네임스페이스

<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
            xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">

공통 패턴

굵게: <w:r><w:rPr><w:b w:val="true"/></w:rPr><w:t>텍스트</w:t></w:r>

기울임꼴: <w:r><w:rPr><w:i w:val="true"/></w:rPr><w:t>텍스트</w:t></w:r>

글꼴 크기(2분의 1포인트): <w:rPr><w:sz w:val="32"/></w:rPr> (32 = 16pt)

색상: <w:rPr><w:color w:val="2E75B6"/></w:rPr>

밑줄: <w:rPr><w:u w:val="single"/></w:rPr>

가로 눈금자 (단락 테두리)

중요: 표를 구분선으로 사용하지 마세요. 대신 단락 테두리를 사용하세요:

<w:p>
  <w:pPr>
    <w:pBdr>
      <w:bottom w:val="single" w:sz="6" w:space="1" w:color="2E75B6"/>
    </w:pBdr>
    <w:spacing w:before="0" w:after="0"/>
  </w:pPr>
</w:p>

동일한 효과를 위해 코드에서:

new Paragraph({
  spacing: { before: 0, after: 0 },
  border: {
    bottom: { style: BorderStyle.SINGLE, size: 6, color: "2E75B6", space: 1 }
  }
})

셀 병합

수평 병합은 gridSpan을 사용합니다. 이는 표시되는 셀에만 필요하며 중간 셀은 건너뛰어야 합니다.

<w:tc>
  <w:tcPr>
    <w:gridSpan w:val="2"/>  <!-- 2개 열에 걸쳐 있음 -->
    <w:vAlign w:val="center"/>
  </w:tcPr>
  <w:p><w:r><w:t>병합된 셀</w:t></w:r></w:p>
</w:tc>

수직 병합:

<!-- 첫 번째 셀 (병합 시작) -->
<w:tc>
  <w:tcPr>
    <w:vMerge w:val="restart"/>
  </w:tcPr>
  <w:p><w:r><w:t>병합된 텍스트</w:t></w:r></w:p>
</w:tc>

<!-- 후속 셀 (계속) -->
<w:tc>
  <w:tcPr>
    <w:vMerge w:val="continue"/>
  </w:tcPr>
</w:tc>

주석

  1. comment.py를 사용하여 주석 XML 파일을 생성합니다 (word/comments.xml, word/commentsExtended.xml, word/commentIds.xml 및 관계를 처리).
  2. word/document.xml에서 주석을 달 단락에 앵커를 추가합니다:
<w:commentRangeStart w:id="0"/>
<w:r><w:t>주석 달린 텍스트</w:t></w:r>
<w:commentRangeEnd w:id="0"/>
<w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:commentReference w:id="0"/></w:r>

표 속성 (셀 너비 문제 디버깅)

잘못된 표 너비는 종종 다음 중 하나로 인해 발생합니다:

  1. w:tcW 누락 - 각 w:tc에는 w:tcW 요소가 있어야 함
  2. 너비 불일치 - 셀 w:w 값은 columnWidths 배열과 일치해야 함
  3. 잘못된 유형 - w:type은 "dxa"여야 하며 "pct"가 아니어야 함 (Google Docs와의 호환성을 위해)
<w:tcPr>
  <w:tcW w:w="4680" w:type="dxa"/>  <!-- 올바름 -->
  <w:tcW w:w="4680" w:type="pct"/>  <!-- Google Docs에서 깨짐 -->
</w:tcPr>

[Content_Types].xml에 누락된 콘텐츠 유형 추가

미디어나 스타일과 같은 새 파일을 추가할 때 이 파일을 업데이트해야 합니다:

<Override PartName="/word/media/image1.png" ContentType="image/png"/>

관련 스킬