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レターではありません
// 一貫した結果を得るために、常にページサイズを明示的に設定してください
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レター | 12,240 | 15,840 | 9,360 |
| A4(デフォルト) | 11,906 | 16,838 | 9,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: "見出し 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: "見出し 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: "箇条書き",
levels: [{ level: 0, format: LevelFormat.BULLET, text: "•", alignment: AlignmentType.LEFT,
style: { paragraph: { indent: { left: 720, hanging: 360 } } } }] },
{ reference: "番号",
levels: [{ level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.LEFT,
style: { paragraph: { indent: { left: 720, hanging: 360 } } } }] },
]
},
sections: [{
children: [
new Paragraph({ numbering: { reference: "箇条書き", level: 0 },
children: [new TextRun("箇条書き項目")] }),
new Paragraph({ numbering: { reference: "番号", level: 0 },
children: [new TextRun("番号付き項目")] }),
]
}]
});
// ⚠️ 各referenceはINDEPENDENT(独立した)番号を作成します
// 同じreference = 継続 (1,2,3 → 4,5,6)
// 異なるreference = リセット (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ドキュメントで壊れます)
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ドキュメントで壊れます。
// テーブル幅 = columnWidthsの合計 = コンテンツ幅
// 1インチ余白のUSレター: 12240 - 2880 = 9360 DXA
width: { size: 9360, type: WidthType.DXA },
columnWidths: [7000, 2360] // テーブル幅に合計する必要があります
幅のルール:
- 常に
WidthType.DXAを使用 -WidthType.PERCENTAGEは決して使用しない(Googleドキュメントと互換性がありません) - テーブル幅は
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: "名前" } // 3つすべて必須
})]
})
改ページ
// 重要: 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 }],
})
// ドットリーダー(例:目次スタイル)
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レター(12240 x 15840 DXA)を使用
- 横向き: 縦向きの寸法を渡す - docx-jsは内部で幅/高さを入れ替える。短い辺を
width、長い辺をheightとして渡し、orientation: PageOrientation.LANDSCAPEを設定 \nは絶対に使用しない - 代わりに個別のParagraph要素を使用- ユニコード箇条書きは絶対に使用しない - 番号設定で
LevelFormat.BULLETを使用 - PageBreakはParagraph内に配置する必要がある - 単独では無効なXMLになる
- ImageRunには
typeが必要 - 常にpng/jpgなどを指定 - テーブル
widthは常にDXAで設定 -WidthType.PERCENTAGEは決して使用しない(Googleドキュメントで壊れる) - 表には二重の幅設定が必要 -
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 } }を使用。2段組フッターの場合は、表ではなくタブストップを使用(タブストップセクションを参照) - 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>これは’引用です: “こんにちは”</w:t>
| エンティティ | 文字 |
|---|---|
‘ | ' (左シングル) |
’ | ' (右シングル / アポストロフィ) |
“ | " (左ダブル) |
” | " (右ダブル) |
コメントの追加: comment.py を使用して、複数のXMLファイルにわたる定型文を処理します(テキストは事前にエスケープされたXMLである必要があります):
python scripts/comment.py unpacked/ 0 "& や ’ を含むコメントテキスト"
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を圧縮し、作成...
[翻訳のため省略]