レシピ

よくある作業のための、動作するコード集です。各スニペットは site/src/lib/examples/ 以下にある実際のファイルで、ビルドのたびにライブラリに対して型チェックされます。そのため API の名前が変わると、公開される前にこのページのビルドが失敗します。個々の関数については API リファレンスを参照してください。

パッケージ内のすべてのパーツを対象に差し込み印刷を行う

replaceTextEverywhere は本文、ヘッダー、フッター、脚注、文末脚注、コメントを走査するため、ヘッダー内のプレースホルダーも本文と同じように埋められます。

site/src/lib/examples/recipe-mail-merge.ts
// Mail-merge across every text-bearing part of the package — body,
// headers, footers, footnotes, endnotes, comments. replaceTextEverywhere
// follows the same regex/callback contract as replaceText but walks the
// whole document, so a {{name}} hidden in a header is filled the same
// way one in the body is.

import { openDocx, replaceTextEverywhere, toUint8Array } from "@office-kit/docx";

declare const templateBytes: Uint8Array;
declare const values: Record<string, string>;

const doc = openDocx(templateBytes);

// Regex captures land in `m.captures`; everything else (`m.match`,
// `m.index`) mirrors RegExp.exec semantics. Run-spanning matches are
// joined before the regex sees them, so `{{name}}` split across
// multiple runs still substitutes cleanly.
const replaced: number = replaceTextEverywhere(
  doc,
  /\{\{(\w+)\}\}/g,
  (m) => values[m.captures[0] ?? ""] ?? "",
);

console.log(`replaced ${replaced} placeholders`);

const filled: Uint8Array = toUint8Array(doc);
void filled;

pnpm sample を実行すると、samples/21-mailmerge-cross-part-template.docx と -filled.docx が出力されます。

デザイン済みのベースから始める

手作業でデザインした .docx を開き、mergeStylesFromTemplate でそのスタイル定義を作成中のドキュメントに取り込んでから、内容を追加していきます。カスタムスタイルは setParagraphStyle で名前を指定して適用します。

site/src/lib/examples/recipe-styled-base.ts
// PowerPoint-style "designed base": open a hand-designed .docx, lift
// only its style table into your authoring graph, then keep appending
// body content. The visual identity (fonts, colours, custom paragraph
// styles) carries over without any placeholder-substitution dance.

import {
  appendHeading,
  appendParagraph,
  createDocx,
  findStyleIdByName,
  mergeStylesFromTemplate,
  setParagraphStyle,
  toUint8Array,
} from "@office-kit/docx";

declare const templateBytes: Uint8Array;

const doc = createDocx({ paragraphs: [] });

// Merge styles from the hand-designed template into the empty doc.
// `overwrite: false` (default) means built-in heading styles in the
// authoring graph win if both define them; pass `overwrite: true` to
// take the template's flavour.
const merged: number = mergeStylesFromTemplate(doc, templateBytes);
console.log(`merged ${merged} styles from template`);

appendHeading(doc, "Quarterly review", 1);

// Apply a custom paragraph style by *name* (as it appears in Word's UI)
// rather than the raw `w:styleId`. Returns the underlying styleId so
// downstream code can re-use it.
const calloutId: string | undefined = findStyleIdByName(doc, "Callout");
const callout = appendParagraph(doc, "Heads-up: this is the executive summary.");
if (calloutId) setParagraphStyle(callout, calloutId);

const bytes: Uint8Array = toUint8Array(doc);
void bytes;

pnpm sample を実行すると、samples/30-styled-base-template.docx と -filled.docx が出力されます。

変更履歴を一括で承諾・却下する

acceptAllRevisions は提案された挿入を本文に取り込み、削除を確定します。rejectAllRevisions はその逆を行います。校閲済みの 1 つの文書から「最終版」と「元の版」の両方を作りたいときに便利です。

site/src/lib/examples/recipe-tracked-changes.ts
// Resolve tracked changes (Word's "Accept / Reject all changes") in
// bulk. The library walks every w:ins / w:del marker in the document
// body and either bakes it in or removes it.
//
// `acceptAllRevisions` inlines the inserted ranges and deletes the
// deleted ones. `rejectAllRevisions` does the reverse: keeps deletions
// (= drops the suggested insertions) and restores deleted ranges.

import { acceptAllRevisions, openDocx, rejectAllRevisions, toUint8Array } from "@office-kit/docx";

declare const reviewedBytes: Uint8Array;

// Final draft: accept everything the editor suggested.
const accepted = openDocx(reviewedBytes);
const acceptedCount: number = acceptAllRevisions(accepted);
console.log(`accepted ${acceptedCount} revisions`);
const finalBytes: Uint8Array = toUint8Array(accepted);

// Sometimes you want the opposite — revert all proposed changes.
const reverted = openDocx(reviewedBytes);
const rejectedCount: number = rejectAllRevisions(reverted);
console.log(`rejected ${rejectedCount} revisions`);
const originalBytes: Uint8Array = toUint8Array(reverted);

void finalBytes;
void originalBytes;

pnpm sample を実行すると、samples/09-tracked-changes.docx が出力されます。

@office-kit/docx-preview でブラウザーに表示する

previewToDOM は、任意の Docx の読み取り専用レンダリングを DOM コンテナにマウントします。戻り値の破棄用ハンドルは、何度呼び出しても安全です。

site/src/lib/examples/preview-embed.ts
// Render any Docx — built from scratch or opened from bytes — into a
// DOM container using @office-kit/docx-preview. The wrap is intentional: we
// share the renderer with docx-preview upstream but pin the contract
// behind a stable function-API surface.

import { openDocx } from "@office-kit/docx";
import { previewToDOM } from "@office-kit/docx-preview";

declare const bytes: Uint8Array;
declare const container: HTMLElement;

const doc = openDocx(bytes);
const handle = await previewToDOM(doc, container, {
  classPrefix: "wk-",
  inWrapper: true,
  breakPages: true,
  renderFonts: true,
});

// when you're done, detach + release internal references:
handle.dispose();

このサイトのプレイグラウンドでは、このコードが実際に動いています。

ドキュメントを作成する一連の流れははじめにで確認し、描画結果はプレイグラウンドで確認してください。