mirror of
https://github.com/dolanmiu/docx.git
synced 2026-11-30 16:47:55 +01:00
feat: live examples in the docs, which run, draw the document next to the code, and can be edited and downloaded (#3556)
* feat: live examples in the docs, which run, draw the document next to the code, and can be edited and downloaded The docs' code examples were plain snippets, often fragments that couldn't run. A code block marked ```ts live is now an example readers can see and change: the page runs it with docx, draws the document it makes next to the code with docx-preview, and offers the .docx to download. Clicking the code opens an editor (Monaco) that knows docx's types, the pages are drawn again as the code changes, and View closes the editor. Split, Code and Preview show the code and the pages side by side, or one of them. The demos a page includes are live too. Every example in the docs that builds or patches a document is now live: 443 of them, each a whole file with its imports, so it runs as written. Code about other things, such as installing, bundlers or servers, stays plain. Running them showed docs that were wrong, fixed here: - Landscape: docx swaps a landscape page's width and height itself, so the docs' swapped sizes made a tall page marked as landscape - Comments: `comments.children` takes plain objects, not `new Comment(...)` - Custom properties are text only - APIs that no longer exist: MathText, Row, `.then` on Packer.toStream, patchDocument(buffer, ...), createParagraph().heading1(), a border's `value`, TextRun's `.break()` - The templates and patcher examples read files that aren't in the repository. They now patch the templates in demo/assets, or make their own `npm run build.docs` copies docx's browser builds into docs/live-examples/lib, so the docs use the docx they describe, and the Pages workflow runs it. The folder is gitignored, and cspell and ESLint skip it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TmyffPd5QMJYjXiMBQ3EnZ * docs: the bullet examples draw a bullet, and the patcher's usage writes the patched document "ὠ" is U+1F60, a Greek omega, since \u takes four hex digits, so the two live bullet examples on the numbering page drew it as each item's bullet. They use "•" now. The patcher's usage example now awaits patchDocument and writes the document it makes, as the example after it does. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TmyffPd5QMJYjXiMBQ3EnZ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -91,6 +91,7 @@
|
||||
"ignorePaths": [
|
||||
"package.json",
|
||||
"docs/api",
|
||||
"docs/live-examples/lib",
|
||||
"*.docx",
|
||||
"build"
|
||||
],
|
||||
|
||||
@@ -16,6 +16,7 @@ jobs:
|
||||
- name: Build 🔧
|
||||
run: |
|
||||
npm run typedoc
|
||||
npm run build.docs
|
||||
echo "docx.js.org" > docs/.nojekyll
|
||||
echo "docx.js.org" > docs/CNAME
|
||||
- name: Archive Production Artifact
|
||||
|
||||
@@ -39,6 +39,7 @@ build
|
||||
# Documentation
|
||||
docs/api/
|
||||
docs/.nojekyll
|
||||
docs/live-examples/lib/
|
||||
|
||||
# VSCode
|
||||
.vscode/*
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ import { ChartRun } from "docx/charts";
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph, TextRun } from "docx";
|
||||
|
||||
|
||||
@@ -302,3 +302,28 @@ describe("ClassName", () => {
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Live examples in the docs
|
||||
|
||||
The code examples in the docs are live: the page runs each one, draws the document it makes next to the code, and lets readers edit the code and download the `.docx`. Write an example that makes a document as a whole file with its imports, and mark the code block `ts live`:
|
||||
|
||||
````md
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [{ children: [new Paragraph("Hello World")] }],
|
||||
});
|
||||
```
|
||||
````
|
||||
|
||||
The last `Document` the example makes is the one shown, so it doesn't need `Packer`. It can still end with `Packer.toBuffer` and `fs.writeFileSync` as in Node, and read files in the `demo` folder with `fs.readFileSync`, such as `./demo/assets/images/pizza.gif`. The demos a page includes from the `demo` folder are live without being marked. Code that isn't about the document, such as a server handler or bundler setup, stays a plain `ts` block.
|
||||
|
||||
The preview is drawn by [docx-preview](https://github.com/VolodymyrBaydalka/docxjs), which leaves out shapes, charts and watermarks, so check those in Word.
|
||||
|
||||
To see the live examples locally, build docx for the docs, then serve them:
|
||||
|
||||
```terminal
|
||||
npm run build.docs
|
||||
npm run serve.docs
|
||||
```
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
title="docsify-darklight-theme"
|
||||
type="text/css"
|
||||
/>
|
||||
<link rel="stylesheet" href="live-examples/live-examples.css" type="text/css" />
|
||||
<style>
|
||||
/* The cover page (.cover-main) and the GitHub corner share z-index: 1 in the theme,
|
||||
and the cover is rendered later in the DOM, so it overlaps the corner once the
|
||||
@@ -57,5 +58,6 @@
|
||||
<script src="https://unpkg.com/docsify-sign-off-sheet@1.0.2/dist/index.iife.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/docsify-terminal-block@1.0.3"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify-darklight-theme@latest/dist/index.min.js" type="text/javascript"></script>
|
||||
<script src="live-examples/live-examples.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/* Live examples: see live-examples.js. The colours are the docs theme's, so they follow it between light and dark */
|
||||
|
||||
.markdown-section .live-example {
|
||||
margin: 1em 0;
|
||||
border: 1px solid var(--borderColor);
|
||||
border-radius: 4px;
|
||||
/* Clipped rather than hidden, which would stop the pages sticking to the top of the window in the split view */
|
||||
overflow: clip;
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.live-example__panes {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
background: var(--codeBackgroundColor);
|
||||
}
|
||||
|
||||
.markdown-section .live-example pre {
|
||||
margin: 0;
|
||||
border-radius: 0;
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
.markdown-section .live-example pre:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.live-example__editor {
|
||||
min-height: 60px;
|
||||
}
|
||||
|
||||
.live-example__bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--borderColor);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.live-example__status {
|
||||
flex: 1;
|
||||
color: var(--blockQuoteColor);
|
||||
}
|
||||
|
||||
.live-example__status--error {
|
||||
color: var(--highlightColor);
|
||||
font-family: var(--codeFontFamily);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.live-example__bar button {
|
||||
padding: 4px 12px;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
color: var(--accent);
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.live-example__bar button:hover:not(:disabled),
|
||||
.live-example__bar button[aria-pressed="true"] {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.live-example__bar button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.live-example__views {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.live-example__bar .live-example__views button {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.live-example__bar .live-example__views button + button {
|
||||
margin-left: -1px;
|
||||
}
|
||||
|
||||
.live-example__bar .live-example__views button:first-child {
|
||||
border-radius: 4px 0 0 4px;
|
||||
}
|
||||
|
||||
.live-example__bar .live-example__views button:last-child {
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
|
||||
.live-example__preview {
|
||||
max-height: 70vh;
|
||||
min-height: 80px;
|
||||
overflow: auto;
|
||||
border-top: 1px solid var(--borderColor);
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.live-example[data-view="code"] .live-example__preview,
|
||||
.live-example[data-view="preview"] .live-example__code {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Only the pages are shown, so all of them are */
|
||||
.live-example[data-view="preview"] .live-example__preview {
|
||||
max-height: none;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
/* Side by side when there's room, with the pages kept in sight as the code scrolls past. Otherwise the pages are under the code */
|
||||
@container (min-width: 720px) {
|
||||
.live-example[data-view="split"] .live-example__panes {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.live-example[data-view="split"] .live-example__code {
|
||||
border-right: 1px solid var(--borderColor);
|
||||
}
|
||||
|
||||
.live-example[data-view="split"] .live-example__preview {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
align-self: start;
|
||||
max-height: 100vh;
|
||||
border-top: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* The code doesn't run, so the pages are what it last drew */
|
||||
.live-example__preview--stale {
|
||||
opacity: 0.5;
|
||||
}
|
||||
@@ -0,0 +1,637 @@
|
||||
/*
|
||||
* Live examples for the docs.
|
||||
*
|
||||
* A code block written as ```ts live, and each demo a page includes from the repository's demo folder, is an example
|
||||
* people can change and see: the page runs it with docx, draws the document it makes next to the code with docx-preview,
|
||||
* and offers the .docx to download. The code and the pages can each be shown on their own too. Clicking the code turns
|
||||
* it into an editor (Monaco) that knows docx's types, and the document is drawn again as the code changes. View turns
|
||||
* the editor back into the code, as changed.
|
||||
*
|
||||
* An example is a whole file, like a demo. It imports what it uses from "docx", or from an entry such as "docx/shapes",
|
||||
* and can use fs and Buffer as it would in Node, to read files in the demo folder and to write the .docx. The page shows
|
||||
* the .docx it writes, or else the last Document it makes, so an example doesn't have to write one.
|
||||
*
|
||||
* docx is loaded from live-examples/lib, which `npm run build.docs` fills from dist, so the examples use the docx the docs
|
||||
* describe rather than the last release.
|
||||
*/
|
||||
(() => {
|
||||
const MONACO = "https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min";
|
||||
// jsDelivr builds 3.35.1 against a version of a dependency without the export it needs
|
||||
const SUCRASE = "https://cdn.jsdelivr.net/npm/sucrase@3.35.0/+esm";
|
||||
const DOCX_PREVIEW = "https://cdn.jsdelivr.net/npm/docx-preview@0.4.1/+esm";
|
||||
// Where fs.readFileSync("./demo/assets/images/pizza.gif") reads from
|
||||
const REPOSITORY = "https://raw.githubusercontent.com/dolanmiu/docx/master/";
|
||||
const LIB = "live-examples/lib/";
|
||||
|
||||
// The modules an example can import, with the file in LIB that defines each one and the global it defines
|
||||
const MODULES = {
|
||||
docx: { file: "index", global: "docx" },
|
||||
"docx/shapes": { file: "shapes", global: "docxShapes" },
|
||||
"docx/watermarks": { file: "watermarks", global: "docxWatermarks" },
|
||||
"docx/charts": { file: "charts", global: "docxCharts" },
|
||||
"docx/math": { file: "math", global: "docxMath" },
|
||||
};
|
||||
|
||||
// docx-preview draws these as empty space
|
||||
const NOT_DRAWN = { "docx/shapes": "shapes", "docx/charts": "charts", "docx/watermarks": "watermarks" };
|
||||
|
||||
// The editor's types for what docx's types use from Node, and for the parts of Node an example can use
|
||||
const NODE_TYPES = `
|
||||
declare class Buffer extends Uint8Array {
|
||||
static from(data: string | ArrayBuffer | ArrayLike<number>, encoding?: "base64" | "utf8" | "utf-8"): Buffer;
|
||||
toString(encoding?: "base64" | "utf8" | "utf-8"): string;
|
||||
}
|
||||
declare module "fs" {
|
||||
export function readFileSync(path: string): Buffer;
|
||||
export function readFileSync(path: string, encoding: "base64" | "utf8" | "utf-8" | { encoding: "base64" | "utf8" | "utf-8" }): string;
|
||||
export function writeFileSync(path: string, data: string | Uint8Array, encoding?: "base64" | "utf8" | "utf-8"): void;
|
||||
export function createWriteStream(path: string): object;
|
||||
}
|
||||
declare module "stream" {
|
||||
export class Stream {
|
||||
pipe<T>(destination: T): T;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const PREVIEW_OPTIONS = {
|
||||
className: "docx",
|
||||
inWrapper: true,
|
||||
// A page is as tall as what's on it, so a short example isn't a mostly empty A4 page
|
||||
ignoreHeight: true,
|
||||
ignoreLastRenderedPageBreak: true,
|
||||
experimental: true,
|
||||
renderHeaders: true,
|
||||
renderFooters: true,
|
||||
renderFootnotes: true,
|
||||
renderEndnotes: true,
|
||||
renderComments: true,
|
||||
renderChanges: true,
|
||||
// Blob URLs would have to be revoked each time the document is drawn again
|
||||
useBase64URL: true,
|
||||
};
|
||||
|
||||
// The pages are drawn in a shadow root, so the docs' styles for paragraphs and tables don't change them
|
||||
const PREVIEW_STYLE = `
|
||||
:host { all: initial; display: block; position: relative; }
|
||||
.docx-wrapper { background: transparent !important; padding: 16px !important; }
|
||||
.docx-wrapper > section.docx { margin-bottom: 16px !important; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25) !important; }
|
||||
.pages.drawing { visibility: hidden; position: absolute; inset: 0 auto auto 0; width: 100%; }
|
||||
`;
|
||||
|
||||
/** Runs `load` the first time it's needed, and again after it fails */
|
||||
const once = (load) => {
|
||||
let promise;
|
||||
return () =>
|
||||
(promise ??= load().catch((error) => {
|
||||
promise = undefined;
|
||||
throw error;
|
||||
}));
|
||||
};
|
||||
|
||||
const loadScript = (src) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
script.src = src;
|
||||
script.onload = resolve;
|
||||
script.onerror = () => reject(new Error(`Couldn't load ${src}`));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
|
||||
const loadSucrase = once(() => import(SUCRASE));
|
||||
const loadDocxPreview = once(() => import(DOCX_PREVIEW));
|
||||
const loadDocx = once(() => loadScript(`${LIB}index.iife.js`));
|
||||
// docx's entries, such as docx/shapes, use the docx global, so they're loaded after it
|
||||
const entryLoaders = Object.fromEntries(
|
||||
Object.entries(MODULES)
|
||||
.filter(([name]) => name !== "docx")
|
||||
.map(([name, { file }]) => [name, once(() => loadDocx().then(() => loadScript(`${LIB}${file}.iife.js`)))]),
|
||||
);
|
||||
const loadModule = (name) => (name === "docx" ? loadDocx() : entryLoaders[name]());
|
||||
|
||||
const importsOf = (source) => [...source.matchAll(/from\s+["']([^"']+)["']/g)].map(([, name]) => name);
|
||||
|
||||
/** A file's bytes, which turn into text as a Node Buffer's do, since some examples use them that way */
|
||||
class FileBuffer extends Uint8Array {
|
||||
toString(encoding) {
|
||||
if (encoding !== "base64") {
|
||||
return new TextDecoder().decode(this);
|
||||
}
|
||||
let binary = "";
|
||||
for (let start = 0; start < this.length; start += 0x8000) {
|
||||
binary += String.fromCharCode(...this.subarray(start, start + 0x8000));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
}
|
||||
|
||||
/** Node's Buffer.from, for the encodings examples use */
|
||||
const bytesOf = (data, encoding) => {
|
||||
if (typeof data !== "string") {
|
||||
return new FileBuffer(data);
|
||||
}
|
||||
if (encoding === "base64") {
|
||||
return new FileBuffer(Array.from(atob(data), (character) => character.charCodeAt(0)));
|
||||
}
|
||||
return new FileBuffer(new TextEncoder().encode(data));
|
||||
};
|
||||
|
||||
// Examples read files in the demo folder as the demos do, with or without "./" in front
|
||||
const repositoryPath = (path) => path.replace(/^\.\//, "");
|
||||
const repositoryFiles = new Map();
|
||||
/** Reads the files in the repository's demo folder that the example names, so fs.readFileSync has them straight away */
|
||||
const readRepositoryFiles = async (source) => {
|
||||
const paths = [...source.matchAll(/["'](?:\.\/)?(demo\/[^"'\s]+\.\w+)["']/g)].map(([, path]) => path);
|
||||
for (const path of paths) {
|
||||
if (!repositoryFiles.has(path)) {
|
||||
repositoryFiles.set(
|
||||
path,
|
||||
fetch(REPOSITORY + path).then(async (response) => {
|
||||
if (!response.ok) {
|
||||
repositoryFiles.delete(path);
|
||||
throw new Error(`Couldn't read ${path}`);
|
||||
}
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
return new Map(await Promise.all(paths.map(async (path) => [path, await repositoryFiles.get(path)])));
|
||||
};
|
||||
|
||||
const AsyncFunction = (async () => {}).constructor;
|
||||
|
||||
/** Runs an example, and returns the .docx it makes: the one it writes with fs.writeFileSync, or else its last Document */
|
||||
const make = async (source) => {
|
||||
const imports = importsOf(source).filter((name) => name in MODULES);
|
||||
const [{ transform }, files] = await Promise.all([
|
||||
loadSucrase(),
|
||||
readRepositoryFiles(source),
|
||||
loadDocx(),
|
||||
...imports.map(loadModule),
|
||||
]);
|
||||
const { code } = transform(source, { transforms: ["typescript", "imports"] });
|
||||
|
||||
const docx = window.docx;
|
||||
let lastDocument;
|
||||
let written;
|
||||
// What the example starts without waiting for, such as Packer.toBuffer(doc).then(...), which may write its file
|
||||
const started = [];
|
||||
const track = (promise) => {
|
||||
started.push(promise);
|
||||
return promise;
|
||||
};
|
||||
|
||||
class Document extends docx.Document {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
lastDocument = this;
|
||||
}
|
||||
}
|
||||
class Packer extends docx.Packer {
|
||||
// Browsers don't have Node's Buffer
|
||||
static toBuffer(...args) {
|
||||
return track(docx.Packer.toArrayBuffer(...args).then((buffer) => new FileBuffer(buffer)));
|
||||
}
|
||||
// Nor its streams, so what's shown is the Document rather than what the stream writes
|
||||
static toStream() {
|
||||
return { pipe: (destination) => destination };
|
||||
}
|
||||
}
|
||||
const patchDocument = (options) =>
|
||||
track(docx.patchDocument({ ...options, outputType: options.outputType === "nodebuffer" ? "uint8array" : options.outputType }));
|
||||
const fs = {
|
||||
readFileSync: (path, options) => {
|
||||
const bytes = files.get(repositoryPath(path));
|
||||
if (!bytes) {
|
||||
throw new Error(`Examples can only read files in the repository's demo folder, such as ./demo/assets/images/pizza.gif`);
|
||||
}
|
||||
const encoding = typeof options === "string" ? options : options?.encoding;
|
||||
return encoding ? new FileBuffer(bytes).toString(encoding) : new FileBuffer(bytes);
|
||||
},
|
||||
writeFileSync: (path, data, encoding) => {
|
||||
if (/\.docx$/i.test(path)) {
|
||||
written = bytesOf(data, encoding);
|
||||
}
|
||||
},
|
||||
createWriteStream: () => ({}),
|
||||
};
|
||||
const require = (name) => {
|
||||
if (name === "docx") {
|
||||
return { ...docx, Document, File: Document, Packer, patchDocument };
|
||||
}
|
||||
if (name === "fs") {
|
||||
return fs;
|
||||
}
|
||||
if (name in MODULES) {
|
||||
return window[MODULES[name].global];
|
||||
}
|
||||
throw new Error(`Examples can import docx, its entries such as docx/shapes, and fs, but not ${name}`);
|
||||
};
|
||||
|
||||
await new AsyncFunction("require", "exports", "module", "Buffer", code)(require, {}, { exports: {} }, { from: bytesOf });
|
||||
const results = await Promise.allSettled(started);
|
||||
// The example's own .then(...) callbacks, which write the file, run before this
|
||||
await new Promise((resolve) => setTimeout(resolve));
|
||||
|
||||
if (written) {
|
||||
return new Blob([written]);
|
||||
}
|
||||
const failure = results.find((result) => result.status === "rejected");
|
||||
if (failure) {
|
||||
throw failure.reason;
|
||||
}
|
||||
if (lastDocument) {
|
||||
return docx.Packer.toBlob(lastDocument);
|
||||
}
|
||||
throw new Error("Make a new Document(...) to see it here");
|
||||
};
|
||||
|
||||
const loadMonaco = once(async () => {
|
||||
// The editor's workers come from the CDN too, which a worker can only load through a script of the page's own
|
||||
window.MonacoEnvironment = {
|
||||
getWorkerUrl: () =>
|
||||
`data:text/javascript;charset=utf-8,${encodeURIComponent(
|
||||
`self.MonacoEnvironment = { baseUrl: "${MONACO}/" }; importScripts("${MONACO}/vs/base/worker/workerMain.js");`,
|
||||
)}`,
|
||||
};
|
||||
await loadScript(`${MONACO}/vs/loader.js`);
|
||||
window.require.config({ paths: { vs: `${MONACO}/vs` } });
|
||||
await new Promise((resolve, reject) => window.require(["vs/editor/editor.main"], resolve, reject));
|
||||
|
||||
const { typescript } = window.monaco.languages;
|
||||
typescript.typescriptDefaults.setCompilerOptions({
|
||||
target: typescript.ScriptTarget.ES2020,
|
||||
module: typescript.ModuleKind.ESNext,
|
||||
moduleResolution: typescript.ModuleResolutionKind.NodeJs,
|
||||
strict: true,
|
||||
allowNonTsExtensions: true,
|
||||
// Each example is its own module, even one without imports, so two can both have a const doc
|
||||
moduleDetection: 3,
|
||||
});
|
||||
// "docx" and "docx/shapes" resolve to these as they would in node_modules
|
||||
const types = await Promise.all(
|
||||
Object.values(MODULES).map(async ({ file }) => [file, await fetch(`${LIB}${file}.d.ts`).then((response) => response.text())]),
|
||||
);
|
||||
for (const [file, text] of types) {
|
||||
typescript.typescriptDefaults.addExtraLib(text, `file:///node_modules/docx/${file}.d.ts`);
|
||||
}
|
||||
typescript.typescriptDefaults.addExtraLib(NODE_TYPES, "file:///node-types.d.ts");
|
||||
|
||||
themeEditors();
|
||||
new MutationObserver(themeEditors).observe(document.documentElement, { attributes: true, attributeFilter: ["style"] });
|
||||
return window.monaco;
|
||||
});
|
||||
|
||||
/** Gives the editors the docs theme's code colours, and follows it between light and dark */
|
||||
const themeEditors = () => {
|
||||
const style = document.documentElement.style;
|
||||
const dark = style.getPropertyValue("color-scheme") === "dark";
|
||||
const background = style.getPropertyValue("--codeBackgroundColor").trim();
|
||||
window.monaco.editor.defineTheme("docs", {
|
||||
base: dark ? "vs-dark" : "vs",
|
||||
inherit: true,
|
||||
rules: [],
|
||||
colors: /^#[0-9a-f]{6}$/i.test(background) ? { "editor.background": background } : {},
|
||||
});
|
||||
window.monaco.editor.setTheme("docs");
|
||||
};
|
||||
|
||||
// The examples on the page that's open, dropped when another page is opened
|
||||
let examples = [];
|
||||
let modelCount = 0;
|
||||
|
||||
const button = (text, onClick) => {
|
||||
const element = document.createElement("button");
|
||||
element.type = "button";
|
||||
element.textContent = text;
|
||||
element.addEventListener("click", onClick);
|
||||
return element;
|
||||
};
|
||||
|
||||
/** Where in the code a click landed, as a character offset, so the editor can put its cursor there */
|
||||
const offsetAt = (code, event) => {
|
||||
const caret = document.caretPositionFromPoint?.(event.clientX, event.clientY);
|
||||
const range = caret ? { node: caret.offsetNode, offset: caret.offset } : undefined;
|
||||
const fallback = document.caretRangeFromPoint?.(event.clientX, event.clientY);
|
||||
const { node, offset } = range ?? (fallback ? { node: fallback.startContainer, offset: fallback.startOffset } : {});
|
||||
if (!node || !code.contains(node)) {
|
||||
return 0;
|
||||
}
|
||||
const before = document.createRange();
|
||||
before.setStart(code, 0);
|
||||
before.setEnd(node, offset);
|
||||
return before.toString().length;
|
||||
};
|
||||
|
||||
// What an example shows: the code and pages side by side, or one of them
|
||||
const VIEWS = { split: "Split", code: "Code", preview: "Preview" };
|
||||
|
||||
const createExample = (element) => {
|
||||
const original = decodeURIComponent(element.dataset.source);
|
||||
const pre = element.querySelector("pre");
|
||||
pre.classList.add("live-example__code");
|
||||
const status = document.createElement("span");
|
||||
status.className = "live-example__status";
|
||||
const preview = document.createElement("div");
|
||||
preview.className = "live-example__preview";
|
||||
const root = preview.attachShadow({ mode: "open" });
|
||||
const style = document.createElement("style");
|
||||
style.textContent = PREVIEW_STYLE;
|
||||
root.appendChild(style);
|
||||
|
||||
const example = { element, editor: undefined, model: undefined, editing: false, blob: undefined, runs: 0, observers: [] };
|
||||
|
||||
const edit = button("Edit", () => (example.editing ? stopEditing() : startEditing(0)));
|
||||
const reset = button("Reset", () => {
|
||||
example.model.setValue(original);
|
||||
reset.hidden = true;
|
||||
});
|
||||
reset.hidden = true;
|
||||
const download = button("Download .docx", () => {
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(example.blob);
|
||||
link.download = "example.docx";
|
||||
link.click();
|
||||
// Some browsers start the download after click() returns
|
||||
setTimeout(() => URL.revokeObjectURL(link.href), 60_000);
|
||||
});
|
||||
download.disabled = true;
|
||||
|
||||
const views = document.createElement("div");
|
||||
views.className = "live-example__views";
|
||||
views.setAttribute("role", "group");
|
||||
views.setAttribute("aria-label", "View");
|
||||
const show = (view) => {
|
||||
element.dataset.view = view;
|
||||
for (const viewButton of views.children) {
|
||||
viewButton.setAttribute("aria-pressed", String(viewButton.dataset.view === view));
|
||||
}
|
||||
// There's no code to edit in the preview
|
||||
edit.hidden = view === "preview";
|
||||
};
|
||||
for (const [view, label] of Object.entries(VIEWS)) {
|
||||
const viewButton = button(label, () => show(view));
|
||||
viewButton.dataset.view = view;
|
||||
views.appendChild(viewButton);
|
||||
}
|
||||
|
||||
const bar = document.createElement("div");
|
||||
bar.className = "live-example__bar";
|
||||
bar.append(views, status, edit, reset, download);
|
||||
const panes = document.createElement("div");
|
||||
panes.className = "live-example__panes";
|
||||
panes.append(pre, preview);
|
||||
element.append(bar, panes);
|
||||
show("split");
|
||||
|
||||
const setStatus = (text, error = false) => {
|
||||
status.textContent = text;
|
||||
status.classList.toggle("live-example__status--error", error);
|
||||
};
|
||||
|
||||
/** Scales the pages down to fit, so a whole page is seen without scrolling sideways */
|
||||
const fit = () => {
|
||||
const wrapper = root.querySelector(".pages:not(.drawing) > .docx-wrapper");
|
||||
// The pages aren't in sight in the code view
|
||||
if (!wrapper || preview.clientWidth === 0) {
|
||||
return;
|
||||
}
|
||||
wrapper.style.zoom = "";
|
||||
const widest = Math.max(...[...wrapper.children].map((page) => page.offsetWidth));
|
||||
wrapper.style.zoom = String(Math.min(1, preview.clientWidth / (widest + 32)));
|
||||
};
|
||||
|
||||
const draw = async (source) => {
|
||||
const runNumber = ++example.runs;
|
||||
try {
|
||||
const blob = await make(source);
|
||||
const { renderAsync } = await loadDocxPreview();
|
||||
if (runNumber !== example.runs) {
|
||||
return;
|
||||
}
|
||||
// Drawn out of sight first, so the pages being replaced stay until the new ones are ready
|
||||
const pages = document.createElement("div");
|
||||
pages.className = "pages drawing";
|
||||
root.appendChild(pages);
|
||||
await renderAsync(blob, pages, pages, PREVIEW_OPTIONS);
|
||||
if (runNumber !== example.runs) {
|
||||
pages.remove();
|
||||
return;
|
||||
}
|
||||
root.querySelectorAll(".pages:not(.drawing)").forEach((old) => old.remove());
|
||||
pages.classList.remove("drawing");
|
||||
fit();
|
||||
example.blob = blob;
|
||||
download.disabled = false;
|
||||
preview.classList.remove("live-example__preview--stale");
|
||||
const notDrawn = importsOf(source)
|
||||
.filter((name) => name in NOT_DRAWN)
|
||||
.map((name) => NOT_DRAWN[name]);
|
||||
setStatus(
|
||||
notDrawn.length > 0 ? `The preview can't draw ${notDrawn.join(" or ")}. Download the file to see them in Word.` : "",
|
||||
);
|
||||
} catch (error) {
|
||||
if (runNumber === example.runs) {
|
||||
preview.classList.add("live-example__preview--stale");
|
||||
setStatus(error instanceof Error ? error.message : String(error), true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// The code the block shows, which is the editor's when the editor is closed
|
||||
let shown = original;
|
||||
const showCode = (source) => {
|
||||
if (source === shown) {
|
||||
return;
|
||||
}
|
||||
shown = source;
|
||||
const code = pre.querySelector("code");
|
||||
const grammar = window.Prism?.languages.ts;
|
||||
if (grammar) {
|
||||
code.innerHTML = window.Prism.highlight(source, grammar, "ts");
|
||||
} else {
|
||||
code.textContent = source;
|
||||
}
|
||||
};
|
||||
|
||||
const setEditing = (editing) => {
|
||||
example.editing = editing;
|
||||
edit.textContent = editing ? "View" : "Edit";
|
||||
};
|
||||
|
||||
const stopEditing = () => {
|
||||
showCode(example.model.getValue());
|
||||
example.editor.getContainerDomNode().replaceWith(pre);
|
||||
setEditing(false);
|
||||
};
|
||||
|
||||
const startEditing = async (offset) => {
|
||||
// The editor is still loading
|
||||
if (edit.disabled) {
|
||||
return;
|
||||
}
|
||||
if (example.editor) {
|
||||
if (!example.editing) {
|
||||
pre.replaceWith(example.editor.getContainerDomNode());
|
||||
setEditing(true);
|
||||
example.editor.setPosition(example.model.getPositionAt(offset));
|
||||
}
|
||||
example.editor.focus();
|
||||
return;
|
||||
}
|
||||
edit.disabled = true;
|
||||
setStatus("Loading the editor…");
|
||||
try {
|
||||
const monaco = await loadMonaco();
|
||||
if (!examples.includes(example)) {
|
||||
return;
|
||||
}
|
||||
// The editor's text is where the code's was, so nothing moves when it opens
|
||||
const code = pre.querySelector("code");
|
||||
const style = getComputedStyle(code);
|
||||
const text = {
|
||||
lineDecorationsWidth:
|
||||
code.getBoundingClientRect().left - pre.getBoundingClientRect().left + parseFloat(style.paddingLeft),
|
||||
padding: { top: parseFloat(style.paddingTop), bottom: parseFloat(style.paddingBottom) },
|
||||
fontFamily: style.fontFamily,
|
||||
fontSize: parseFloat(style.fontSize),
|
||||
lineHeight: parseFloat(style.lineHeight) || undefined,
|
||||
};
|
||||
const container = document.createElement("div");
|
||||
container.className = "live-example__code live-example__editor";
|
||||
container.style.height = `${pre.offsetHeight}px`;
|
||||
pre.replaceWith(container);
|
||||
|
||||
example.model = monaco.editor.createModel(original, "typescript", monaco.Uri.parse(`file:///example-${++modelCount}.ts`));
|
||||
example.editor = monaco.editor.create(container, {
|
||||
model: example.model,
|
||||
automaticLayout: true,
|
||||
minimap: { enabled: false },
|
||||
scrollBeyondLastLine: false,
|
||||
// The page scrolls when the wheel is used over the editor, as it does over the code before it's edited
|
||||
scrollbar: { alwaysConsumeMouseWheel: false },
|
||||
overviewRulerLanes: 0,
|
||||
lineNumbers: "off",
|
||||
folding: false,
|
||||
glyphMargin: false,
|
||||
...text,
|
||||
tabSize: 4,
|
||||
fixedOverflowWidgets: true,
|
||||
});
|
||||
const grow = () => {
|
||||
container.style.height = `${example.editor.getContentHeight()}px`;
|
||||
};
|
||||
example.editor.onDidContentSizeChange(grow);
|
||||
grow();
|
||||
|
||||
let timer;
|
||||
example.model.onDidChangeContent(() => {
|
||||
reset.hidden = example.model.getValue() === original;
|
||||
// Reset changes the code while the editor is closed
|
||||
if (!example.editing) {
|
||||
showCode(example.model.getValue());
|
||||
}
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => draw(example.model.getValue()), 300);
|
||||
});
|
||||
|
||||
edit.disabled = false;
|
||||
setEditing(true);
|
||||
setStatus("");
|
||||
example.editor.setPosition(example.model.getPositionAt(offset));
|
||||
example.editor.focus();
|
||||
} catch (error) {
|
||||
edit.disabled = false;
|
||||
setStatus(error instanceof Error ? error.message : String(error), true);
|
||||
}
|
||||
};
|
||||
|
||||
pre.tabIndex = 0;
|
||||
pre.title = "Click to edit";
|
||||
pre.addEventListener("click", (event) => {
|
||||
// The copy button in the code block copies it
|
||||
if (event.target.closest("button") || window.getSelection()?.toString()) {
|
||||
return;
|
||||
}
|
||||
startEditing(offsetAt(pre.querySelector("code"), event));
|
||||
});
|
||||
pre.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter" && event.target === pre) {
|
||||
event.preventDefault();
|
||||
startEditing(0);
|
||||
}
|
||||
});
|
||||
|
||||
// docx and docx-preview are only loaded once an example is about to be seen
|
||||
const visible = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
visible.disconnect();
|
||||
setStatus("Drawing…");
|
||||
draw(original);
|
||||
}
|
||||
},
|
||||
{ rootMargin: "200px" },
|
||||
);
|
||||
visible.observe(element);
|
||||
const resized = new ResizeObserver(fit);
|
||||
resized.observe(preview);
|
||||
example.observers.push(visible, resized);
|
||||
return example;
|
||||
};
|
||||
|
||||
const dispose = (example) => {
|
||||
example.runs++;
|
||||
example.observers.forEach((observer) => observer.disconnect());
|
||||
example.editor?.dispose();
|
||||
example.model?.dispose();
|
||||
};
|
||||
|
||||
window.$docsify = window.$docsify || {};
|
||||
const markdownOptions = (window.$docsify.markdown = window.$docsify.markdown || {});
|
||||
markdownOptions.renderer = markdownOptions.renderer || {};
|
||||
const renderCode = markdownOptions.renderer.code;
|
||||
markdownOptions.renderer.code = function (code, lang) {
|
||||
if (/^ts\s+live$/.test(lang ?? "")) {
|
||||
// docsify writes backticks in code as @DOCSIFY_QM@ until it's highlighted
|
||||
const source = code.replace(/@DOCSIFY_QM@/g, "`");
|
||||
return `<div class="live-example" data-source="${encodeURIComponent(source)}">${this.origin.code.call(this, code, "ts")}</div>`;
|
||||
}
|
||||
return (renderCode ?? this.origin.code).apply(this, arguments);
|
||||
};
|
||||
|
||||
// A demo a page includes, as in [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/tables/basic-table.ts ":include")
|
||||
const DEMO_INCLUDE =
|
||||
/\[[^\]]*\]\((https:\/\/raw\.githubusercontent\.com\/dolanmiu\/docx\/master\/demo\/[^\s)]+\.ts) ":include[^"]*"\)/g;
|
||||
|
||||
/** Writes the demos a page includes into it as live examples */
|
||||
const includeDemos = async (markdown) => {
|
||||
const urls = [...new Set([...markdown.matchAll(DEMO_INCLUDE)].map(([, url]) => url))];
|
||||
const sources = new Map(
|
||||
await Promise.all(
|
||||
urls.map(async (url) => {
|
||||
const response = await fetch(url).catch(() => undefined);
|
||||
return [url, response?.ok ? await response.text() : undefined];
|
||||
}),
|
||||
),
|
||||
);
|
||||
// A demo that can't be fetched is left for docsify to include as code
|
||||
return markdown.replace(DEMO_INCLUDE, (link, url) =>
|
||||
sources.get(url) === undefined ? link : `\`\`\`ts live\n${sources.get(url).trimEnd()}\n\`\`\``,
|
||||
);
|
||||
};
|
||||
|
||||
window.$docsify.plugins = [
|
||||
(hook) => {
|
||||
hook.beforeEach((markdown, next) => {
|
||||
includeDemos(markdown).then(next, () => next(markdown));
|
||||
});
|
||||
hook.doneEach(() => {
|
||||
examples.forEach(dispose);
|
||||
examples = [...document.querySelectorAll(".markdown-section .live-example")].map(createExample);
|
||||
});
|
||||
},
|
||||
...(window.$docsify.plugins || []),
|
||||
];
|
||||
})();
|
||||
+99
-52
@@ -19,7 +19,7 @@ npm install --save docx
|
||||
|
||||
Create a "Hello World" document in just a few lines:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Packer, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
@@ -47,18 +47,28 @@ That's it! Run this code to create your first Word document.
|
||||
|
||||
### Bold and Styled Text
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Normal text, "),
|
||||
new TextRun({
|
||||
text: "bold text, ",
|
||||
bold: true,
|
||||
}),
|
||||
new TextRun({
|
||||
text: "italic text",
|
||||
italics: true,
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Normal text, "),
|
||||
new TextRun({
|
||||
text: "bold text, ",
|
||||
bold: true,
|
||||
}),
|
||||
new TextRun({
|
||||
text: "italic text",
|
||||
italics: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -67,46 +77,74 @@ See the [Text guide](usage/text.md) for all formatting options.
|
||||
|
||||
### Headings
|
||||
|
||||
```ts
|
||||
import { HeadingLevel } from "docx";
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph } from "docx";
|
||||
|
||||
new Paragraph({
|
||||
text: "My Heading",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "My Heading",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
}),
|
||||
new Paragraph("Some text under the heading."),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Bullet Points
|
||||
|
||||
```ts
|
||||
[
|
||||
new Paragraph({
|
||||
text: "First item",
|
||||
bullet: { level: 0 },
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Second item",
|
||||
bullet: { level: 0 },
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Nested item",
|
||||
bullet: { level: 1 },
|
||||
}),
|
||||
];
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "First item",
|
||||
bullet: { level: 0 },
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Second item",
|
||||
bullet: { level: 0 },
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Nested item",
|
||||
bullet: { level: 1 },
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
See the [Bullet Points guide](usage/bullet-points.md) for more options.
|
||||
|
||||
### Tables
|
||||
|
||||
```ts
|
||||
import { Table, TableRow, TableCell } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [new TableCell({ children: [new Paragraph("Cell 1")] }), new TableCell({ children: [new Paragraph("Cell 2")] })],
|
||||
}),
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Cell 1")] }),
|
||||
new TableCell({ children: [new Paragraph("Cell 2")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -115,19 +153,28 @@ See the [Tables guide](usage/tables.md) for advanced table features.
|
||||
|
||||
### Images
|
||||
|
||||
```ts
|
||||
import { ImageRun } from "docx";
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./image.png"),
|
||||
transformation: {
|
||||
width: 200,
|
||||
height: 200,
|
||||
},
|
||||
}),
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./demo/assets/images/dog.png"),
|
||||
transformation: {
|
||||
width: 200,
|
||||
height: 200,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
+227
-89
@@ -67,20 +67,48 @@ app.get("/download", async (req, res) => {
|
||||
|
||||
1. Check for invalid characters in text content:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const text = "Text pasted from somewhere else,\x07 with a control character in it";
|
||||
|
||||
// Remove control characters
|
||||
const cleanText = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "");
|
||||
new TextRun(cleanText);
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph({ children: [new TextRun(cleanText)] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
2. Ensure all required properties are provided:
|
||||
|
||||
```ts
|
||||
// ImageRun requires type, data, and transformation
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: buffer,
|
||||
transformation: { width: 100, height: 100 }, // Required!
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const buffer = fs.readFileSync("./demo/assets/images/dog.png");
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
// ImageRun requires type, data, and transformation
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: buffer,
|
||||
transformation: { width: 100, height: 100 }, // Required!
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -94,12 +122,27 @@ new ImageRun({
|
||||
|
||||
1. Verify the image type matches the file:
|
||||
|
||||
```ts
|
||||
// Match type to actual file format
|
||||
new ImageRun({
|
||||
type: "png", // Must match the actual image format
|
||||
data: fs.readFileSync("image.png"),
|
||||
transformation: { width: 100, height: 100 },
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
// Match type to actual file format
|
||||
new ImageRun({
|
||||
type: "gif", // Must match the actual image format
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
transformation: { width: 100, height: 100 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -169,22 +212,32 @@ Packer.toBlob(doc).then((blob) => {
|
||||
|
||||
**Solution:**
|
||||
|
||||
```ts
|
||||
new Table({
|
||||
width: { size: 100, type: WidthType.PERCENTAGE },
|
||||
rows: [
|
||||
new TableRow({
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new TableCell({
|
||||
width: { size: 50, type: WidthType.PERCENTAGE },
|
||||
children: [new Paragraph("Cell 1")],
|
||||
}),
|
||||
new TableCell({
|
||||
width: { size: 50, type: WidthType.PERCENTAGE },
|
||||
children: [new Paragraph("Cell 2")],
|
||||
new Table({
|
||||
width: { size: 100, type: WidthType.PERCENTAGE },
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({
|
||||
width: { size: 50, type: WidthType.PERCENTAGE },
|
||||
children: [new Paragraph("Cell 1")],
|
||||
}),
|
||||
new TableCell({
|
||||
width: { size: 50, type: WidthType.PERCENTAGE },
|
||||
children: [new Paragraph("Cell 2")],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -195,18 +248,44 @@ new Table({
|
||||
|
||||
**Solution:**
|
||||
|
||||
```ts
|
||||
// Horizontal merge
|
||||
new TableCell({
|
||||
columnSpan: 2, // Span 2 columns
|
||||
children: [new Paragraph("Merged horizontally")],
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
// Vertical merge
|
||||
new TableCell({
|
||||
rowSpan: 2, // Span 2 rows
|
||||
children: [new Paragraph("Merged vertically")],
|
||||
}),
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
// Horizontal merge
|
||||
new TableCell({
|
||||
columnSpan: 2, // Span 2 columns
|
||||
children: [new Paragraph("Merged horizontally")],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new TableRow({
|
||||
children: [
|
||||
// Vertical merge
|
||||
new TableCell({
|
||||
rowSpan: 2, // Span 2 rows
|
||||
children: [new Paragraph("Merged vertically")],
|
||||
}),
|
||||
new TableCell({ children: [new Paragraph("Row 2")] }),
|
||||
],
|
||||
}),
|
||||
new TableRow({
|
||||
// The first column of this row is the merged cell above
|
||||
children: [new TableCell({ children: [new Paragraph("Row 3")] })],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Styling Issues
|
||||
@@ -217,7 +296,9 @@ new TableCell({
|
||||
|
||||
**Solution:**
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
styles: {
|
||||
paragraphStyles: [
|
||||
@@ -252,18 +333,27 @@ const doc = new Document({
|
||||
|
||||
**Solution:** Embed the font:
|
||||
|
||||
```ts
|
||||
import { CharacterSet, Document } from "docx";
|
||||
```ts live
|
||||
import { CharacterSet, Document, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const doc = new Document({
|
||||
fonts: [
|
||||
{
|
||||
name: "CustomFont",
|
||||
data: fs.readFileSync("./font.ttf"),
|
||||
name: "Pacifico",
|
||||
data: fs.readFileSync("./demo/assets/Pacifico.ttf"),
|
||||
characterSet: CharacterSet.ANSI,
|
||||
},
|
||||
],
|
||||
// ...
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun({ text: "Written in the embedded font", font: "Pacifico" })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -296,21 +386,28 @@ const doc = new Document({
|
||||
|
||||
**Solution:**
|
||||
|
||||
```ts
|
||||
// Apply headers to each section
|
||||
sections: [
|
||||
{
|
||||
headers: { default: myHeader },
|
||||
footers: { default: myFooter },
|
||||
children: [/* ... */],
|
||||
},
|
||||
{
|
||||
// New section inherits headers unless overridden
|
||||
headers: { default: myHeader }, // Repeat if needed
|
||||
footers: { default: myFooter },
|
||||
children: [/* ... */],
|
||||
},
|
||||
];
|
||||
```ts live
|
||||
import { Document, Footer, Header, Paragraph } from "docx";
|
||||
|
||||
const myHeader = new Header({ children: [new Paragraph("My header")] });
|
||||
const myFooter = new Footer({ children: [new Paragraph("My footer")] });
|
||||
|
||||
const doc = new Document({
|
||||
// Apply headers to each section
|
||||
sections: [
|
||||
{
|
||||
headers: { default: myHeader },
|
||||
footers: { default: myFooter },
|
||||
children: [new Paragraph("The first section")],
|
||||
},
|
||||
{
|
||||
// New section inherits headers unless overridden
|
||||
headers: { default: myHeader }, // Repeat if needed
|
||||
footers: { default: myFooter },
|
||||
children: [new Paragraph("The second section")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Different first page header not working
|
||||
@@ -319,19 +416,26 @@ sections: [
|
||||
|
||||
**Solution:**
|
||||
|
||||
```ts
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
titlePage: true, // Required for different first page
|
||||
```ts live
|
||||
import { Document, Header, PageBreak, Paragraph, TextRun } from "docx";
|
||||
|
||||
const normalHeader = new Header({ children: [new Paragraph("The header of every other page")] });
|
||||
const firstPageHeader = new Header({ children: [new Paragraph("The header of the first page")] });
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
titlePage: true, // Required for different first page
|
||||
},
|
||||
headers: {
|
||||
default: normalHeader,
|
||||
first: firstPageHeader, // Only shows with titlePage: true
|
||||
},
|
||||
children: [new Paragraph({ children: [new TextRun("The first page"), new PageBreak(), new TextRun("The second page")] })],
|
||||
},
|
||||
headers: {
|
||||
default: normalHeader,
|
||||
first: firstPageHeader, // Only shows with titlePage: true
|
||||
},
|
||||
children: [/* ... */],
|
||||
},
|
||||
];
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Page Numbers
|
||||
@@ -346,19 +450,32 @@ sections: [
|
||||
|
||||
**Solution:**
|
||||
|
||||
```ts
|
||||
import { PageNumber, NumberFormat } from "docx";
|
||||
```ts live
|
||||
import { Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Page "),
|
||||
new TextRun({
|
||||
children: [PageNumber.CURRENT],
|
||||
}),
|
||||
new TextRun(" of "),
|
||||
new TextRun({
|
||||
children: [PageNumber.TOTAL_PAGES],
|
||||
}),
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Page "),
|
||||
new TextRun({
|
||||
children: [PageNumber.CURRENT],
|
||||
}),
|
||||
new TextRun(" of "),
|
||||
new TextRun({
|
||||
children: [PageNumber.TOTAL_PAGES],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("The footer has the page number")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -373,12 +490,22 @@ new Paragraph({
|
||||
|
||||
1. Set `updateFields: true` in document features:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph, TableOfContents } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
features: {
|
||||
updateFields: true,
|
||||
},
|
||||
// ...
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new TableOfContents("Contents", { hyperlink: true, headingStyleRange: "1-3" }),
|
||||
new Paragraph({ text: "Introduction", heading: HeadingLevel.HEADING_1 }),
|
||||
new Paragraph({ text: "Getting started", heading: HeadingLevel.HEADING_2 }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -416,10 +543,21 @@ const resized = await sharp(imagePath).resize(800, 600).toBuffer();
|
||||
|
||||
**Solution:** Check the API documentation or TypeScript definitions:
|
||||
|
||||
```ts
|
||||
// Use IntelliSense to see available options
|
||||
new Paragraph({
|
||||
// Ctrl+Space in VS Code to see options
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
// Use IntelliSense to see available options
|
||||
new Paragraph({
|
||||
// Ctrl+Space in VS Code, or here once you click the code, to see options
|
||||
text: "A paragraph",
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+93
-23
@@ -8,8 +8,8 @@ Bookmarks allow you to create anchors within a document that can be referenced b
|
||||
|
||||
A bookmark is an anchor point in your document with a unique identifier. Create one using the `Bookmark` component:
|
||||
|
||||
```ts
|
||||
import { Bookmark, Paragraph, TextRun, HeadingLevel } from "docx";
|
||||
```ts live
|
||||
import { Bookmark, Document, Paragraph, TextRun, HeadingLevel } from "docx";
|
||||
|
||||
const bookmarkedHeading = new Paragraph({
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
@@ -20,6 +20,14 @@ const bookmarkedHeading = new Paragraph({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [bookmarkedHeading],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Bookmark Options
|
||||
@@ -33,8 +41,8 @@ const bookmarkedHeading = new Paragraph({
|
||||
|
||||
Use `InternalHyperlink` to create clickable links that navigate to bookmarks:
|
||||
|
||||
```ts
|
||||
import { InternalHyperlink, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { Bookmark, Document, HeadingLevel, InternalHyperlink, Paragraph, TextRun } from "docx";
|
||||
|
||||
const linkToChapter = new Paragraph({
|
||||
children: [
|
||||
@@ -49,6 +57,21 @@ const linkToChapter = new Paragraph({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
linkToChapter,
|
||||
new Paragraph({
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
pageBreakBefore: true,
|
||||
children: [new Bookmark({ id: "chapter1", children: [new TextRun("Chapter 1: Introduction")] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
?> Use `style: "Hyperlink"` on your TextRun to apply the default hyperlink styling (blue text, underlined).
|
||||
@@ -57,12 +80,27 @@ const linkToChapter = new Paragraph({
|
||||
|
||||
Get the page number where a bookmark appears using `PageReference`:
|
||||
|
||||
```ts
|
||||
import { PageReference, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { Bookmark, Document, HeadingLevel, PageReference, Paragraph, TextRun } from "docx";
|
||||
|
||||
const pageRef = new Paragraph({
|
||||
children: [new TextRun("See Chapter 1 on page "), new PageReference("chapter1")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
pageRef,
|
||||
new Paragraph({
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
pageBreakBefore: true,
|
||||
children: [new Bookmark({ id: "chapter1", children: [new TextRun("Chapter 1: Introduction")] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
This creates dynamic text like "See Chapter 1 on page 5" that updates automatically.
|
||||
@@ -71,8 +109,8 @@ This creates dynamic text like "See Chapter 1 on page 5" that updates automatica
|
||||
|
||||
Here's a full example with a table of contents linking to bookmarked sections:
|
||||
|
||||
```ts
|
||||
import { Bookmark, Document, HeadingLevel, InternalHyperlink, Packer, PageBreak, PageReference, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { Bookmark, Document, HeadingLevel, InternalHyperlink, PageBreak, PageReference, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
@@ -143,8 +181,8 @@ const doc = new Document({
|
||||
|
||||
Bookmarks and internal hyperlinks work in headers and footers too:
|
||||
|
||||
```ts
|
||||
import { Footer, InternalHyperlink, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { Bookmark, Document, Footer, InternalHyperlink, Paragraph, TextRun } from "docx";
|
||||
|
||||
const footer = new Footer({
|
||||
children: [
|
||||
@@ -158,26 +196,58 @@ const footer = new Footer({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: { default: footer },
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new Bookmark({ id: "documentStart", children: [new TextRun("Start of the document")] })],
|
||||
}),
|
||||
new Paragraph({ text: "Second page", pageBreakBefore: true }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Styling Internal Hyperlinks
|
||||
|
||||
You can apply custom formatting to internal hyperlinks:
|
||||
|
||||
```ts
|
||||
new InternalHyperlink({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Bold ",
|
||||
bold: true,
|
||||
style: "Hyperlink",
|
||||
}),
|
||||
new TextRun({
|
||||
text: "Link",
|
||||
style: "Hyperlink",
|
||||
}),
|
||||
```ts live
|
||||
import { Bookmark, Document, InternalHyperlink, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new InternalHyperlink({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Bold ",
|
||||
bold: true,
|
||||
style: "Hyperlink",
|
||||
}),
|
||||
new TextRun({
|
||||
text: "Link",
|
||||
style: "Hyperlink",
|
||||
}),
|
||||
],
|
||||
anchor: "myBookmark",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
pageBreakBefore: true,
|
||||
children: [new Bookmark({ id: "myBookmark", children: [new TextRun("The bookmarked text")] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
anchor: "myBookmark",
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
|
||||
Create bullet points by adding the `bullet` property to paragraphs:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -45,7 +47,9 @@ const doc = new Document({
|
||||
|
||||
Create nested lists using different `level` values (0-9):
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -94,7 +98,9 @@ const doc = new Document({
|
||||
|
||||
Generate bullet lists from data:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const items = ["Apple", "Banana", "Cherry", "Date"];
|
||||
|
||||
const doc = new Document({
|
||||
@@ -116,7 +122,9 @@ const doc = new Document({
|
||||
|
||||
Create hierarchical lists from nested data:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
interface MenuItem {
|
||||
name: string;
|
||||
children?: MenuItem[];
|
||||
@@ -165,7 +173,9 @@ const doc = new Document({
|
||||
|
||||
Combine bullet points with regular paragraphs:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -198,10 +208,20 @@ const doc = new Document({
|
||||
|
||||
Apply text formatting to bullet items:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
bullet: { level: 0 },
|
||||
children: [new TextRun({ text: "Important: ", bold: true }), new TextRun("This item requires attention")],
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
bullet: { level: 0 },
|
||||
children: [new TextRun({ text: "Important: ", bold: true }), new TextRun("This item requires attention")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+179
-41
@@ -2,8 +2,8 @@
|
||||
|
||||
> Instead of adding a `TextRun` into a `Paragraph`, you can also add an `InsertedTextRun` or `DeletedTextRun` where you need to supply an `id`, `author` and `date` for the change.
|
||||
|
||||
```ts
|
||||
import { Paragraph, TextRun, InsertedTextRun, DeletedTextRun } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun, InsertedTextRun, DeletedTextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [
|
||||
@@ -25,12 +25,20 @@ const paragraph = new Paragraph({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Note that for a `InsertedTextRun` and `DeletedTextRun`, it is not possible to simply call it with only a text as in `new TextRun("some text")`, since the additional fields for change tracking need to be provided. Similar to a normal `TextRun` you can add additional text properties.
|
||||
|
||||
```ts
|
||||
import { Paragraph, TextRun, InsertedTextRun, DeletedTextRun } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun, DeletedTextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [
|
||||
@@ -46,41 +54,68 @@ const paragraph = new Paragraph({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
In addition to marking text as inserted or deleted, change tracking can also be added via the document settings. This will enable new changes to be tracked as well.
|
||||
|
||||
```ts
|
||||
import { Document } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
features: {
|
||||
trackRevisions: true,
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Changes made to this document in Word are tracked.")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
If you want to express a style changes, you can add a `revision` to a `TextRun` which need to include all previous style attributes.
|
||||
|
||||
```ts
|
||||
new TextRun({
|
||||
bold: true,
|
||||
text: "This text is now bold and was previously not",
|
||||
revision: {
|
||||
id: 1,
|
||||
author: "Firstname Lastname",
|
||||
date: "2020-10-06T09:05:00Z",
|
||||
bold: false,
|
||||
},
|
||||
}).break();
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
bold: true,
|
||||
text: "This text is now bold and was previously not",
|
||||
revision: {
|
||||
id: 1,
|
||||
author: "Firstname Lastname",
|
||||
date: "2020-10-06T09:05:00Z",
|
||||
bold: false,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Paragraph Properties Revisions
|
||||
|
||||
You can track changes to paragraph properties (such as alignment, spacing, indentation, borders, heading level, etc.) by adding a `revision` property directly to the `Paragraph` options. The revision must include all previous property values.
|
||||
|
||||
```ts
|
||||
import { Paragraph, AlignmentType, HeadingLevel } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, AlignmentType, HeadingLevel } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
text: "This paragraph has changed alignment and heading",
|
||||
@@ -100,13 +135,21 @@ const paragraph = new Paragraph({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Section Properties Revisions
|
||||
|
||||
You can track changes to section properties (such as page size, margins, text direction, columns, vertical alignment, title page, etc.) by adding a `revision` property to the section `properties` object. The revision must include all previous property values.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun, PageTextDirectionType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -153,8 +196,8 @@ const doc = new Document({
|
||||
|
||||
You can track changes to table properties (such as alignment, borders, width, etc.) by adding a `revision` property to the `Table` options. The revision must include all previous property values.
|
||||
|
||||
```ts
|
||||
import { Table, TableRow, TableCell, Paragraph, AlignmentType } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph, AlignmentType } from "docx";
|
||||
|
||||
const table = new Table({
|
||||
rows: [
|
||||
@@ -174,14 +217,22 @@ const table = new Table({
|
||||
alignment: AlignmentType.RIGHT,
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [table],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Table Column Widths Revisions
|
||||
|
||||
You can track changes to table column widths by providing a `columnWidthsRevision` property. This tracks changes to the grid column widths.
|
||||
|
||||
```ts
|
||||
import { Table, TableRow, TableCell, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph } from "docx";
|
||||
|
||||
const table = new Table({
|
||||
rows: [
|
||||
@@ -202,6 +253,14 @@ const table = new Table({
|
||||
columnWidths: [1000, 555],
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [table],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Table Row Revisions
|
||||
@@ -210,8 +269,8 @@ const table = new Table({
|
||||
|
||||
To mark a table row as inserted, use the `insertion` property in the `TableRow` options. In addition, the text content within the row must also be marked as inserted using the paragraph `run.insertion` property (or by using `InsertedTextRun`). Both are required for Microsoft Word to display the insertion correctly.
|
||||
|
||||
```ts
|
||||
import { TableRow, TableCell, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph, TextRun } from "docx";
|
||||
|
||||
const row = new TableRow({
|
||||
children: [
|
||||
@@ -236,14 +295,26 @@ const row = new TableRow({
|
||||
date: "2020-10-06T09:00:00Z",
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph("Existing row")] })] }), row],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Deleted Table Rows
|
||||
|
||||
To mark a table row as deleted, use the `deletion` property in the `TableRow` options. In addition, the text content within the row must also be marked as deleted using the paragraph `run.deletion` property (or by using `DeletedTextRun`). Both are required for Microsoft Word to display the deletion correctly.
|
||||
|
||||
```ts
|
||||
import { TableRow, TableCell, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph, TextRun } from "docx";
|
||||
|
||||
const row = new TableRow({
|
||||
children: [
|
||||
@@ -268,14 +339,26 @@ const row = new TableRow({
|
||||
date: "2020-10-06T09:00:00Z",
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph("Existing row")] })] }), row],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Table Row Properties Revisions
|
||||
|
||||
You can track changes to table row properties (such as height, table header, cant split, etc.) by adding a `revision` property. The revision must include all previous property values.
|
||||
|
||||
```ts
|
||||
import { TableRow, TableCell, Paragraph, HeightRule, CellSpacingType } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph, HeightRule } from "docx";
|
||||
|
||||
const row = new TableRow({
|
||||
children: [
|
||||
@@ -299,6 +382,14 @@ const row = new TableRow({
|
||||
tableHeader: true,
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [row] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Table Cell Revisions
|
||||
@@ -307,8 +398,8 @@ const row = new TableRow({
|
||||
|
||||
To mark a table cell as inserted, use the `insertion` property in the `TableCell` options. As with table rows, the text content within the cell must also be marked as inserted using the paragraph `run.insertion` property (or by using `InsertedTextRun`). Both are required for Microsoft Word to display the insertion correctly.
|
||||
|
||||
```ts
|
||||
import { TableCell, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph, TextRun } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
children: [
|
||||
@@ -329,14 +420,26 @@ const cell = new TableCell({
|
||||
date: "2020-10-06T09:00:00Z",
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph("Existing cell")] }), cell] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Deleted Table Cells
|
||||
|
||||
To mark a table cell as deleted, use the `deletion` property in the `TableCell` options. As with table rows, the text content within the cell must also be marked as deleted using the paragraph `run.deletion` property (or by using `DeletedTextRun`). Both are required for Microsoft Word to display the deletion correctly.
|
||||
|
||||
```ts
|
||||
import { TableCell, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph, TextRun } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
children: [
|
||||
@@ -357,14 +460,26 @@ const cell = new TableCell({
|
||||
date: "2020-10-06T09:00:00Z",
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph("Existing cell")] }), cell] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Table Cell Properties Revisions
|
||||
|
||||
You can track changes to table cell properties (such as vertical alignment, text direction, borders, shading, etc.) by adding a `revision` property. The revision must include all previous property values.
|
||||
|
||||
```ts
|
||||
import { TableCell, Paragraph, VerticalAlignTable, TextDirection } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph, VerticalAlignTable, TextDirection } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
children: [new Paragraph("Cell content")],
|
||||
@@ -378,14 +493,22 @@ const cell = new TableCell({
|
||||
textDirection: TextDirection.LEFT_TO_RIGHT_TOP_TO_BOTTOM,
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [new TableRow({ children: [cell] })] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Cell Merge Revisions
|
||||
|
||||
You can track changes to cell merging (vertical merge) by using the `cellMerge` property.
|
||||
|
||||
```ts
|
||||
import { TableCell, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Table, TableRow, TableCell, Paragraph } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
children: [new Paragraph("Merged cell")],
|
||||
@@ -396,13 +519,28 @@ const cell = new TableCell({
|
||||
verticalMerge: "cont", // or "restart"
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({ children: [new TableCell({ children: [new Paragraph("Cell above")] })] }),
|
||||
new TableRow({ children: [cell] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Image Revisions
|
||||
|
||||
You can mark an `ImageRun` as inserted or deleted by passing an `insertion` or `deletion` property. This wraps the image run in a `<w:ins>` or `<w:del>` element so that Word displays it as a tracked change.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
@@ -418,7 +556,7 @@ const doc = new Document({
|
||||
new TextRun("Inserted image: "),
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./image.png"),
|
||||
data: fs.readFileSync("./demo/assets/images/dog.png"),
|
||||
transformation: { width: 120, height: 120 },
|
||||
insertion: {
|
||||
id: 30,
|
||||
@@ -433,7 +571,7 @@ const doc = new Document({
|
||||
new TextRun("Deleted image: "),
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./image.png"),
|
||||
data: fs.readFileSync("./demo/assets/images/dog.png"),
|
||||
transformation: { width: 120, height: 120 },
|
||||
deletion: {
|
||||
id: 31,
|
||||
|
||||
+244
-34
@@ -18,13 +18,28 @@ A category axis shows the categories. A value axis shows numbers, and takes a ra
|
||||
|
||||
`title` names an axis. Axes have no titles by default.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
categoryAxis: { title: "Quarter" },
|
||||
valueAxis: { title: "Units" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
categoryAxis: { title: "Quarter" },
|
||||
valueAxis: { title: "Units" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -38,8 +53,28 @@ By default, the application chooses a value axis' range from the values. To choo
|
||||
- `maximum` is the highest;
|
||||
- `interval` is the step between its labels and gridlines.
|
||||
|
||||
```ts
|
||||
valueAxis: { minimum: 0, maximum: 200, interval: 50 },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
valueAxis: { minimum: 0, maximum: 200, interval: 50 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
This labels the axis 0, 50, 100, 150 and 200. Give any of the three, and the application chooses the others. The `minimum` has to be less than the `maximum`, and the `interval` more than 0.
|
||||
@@ -48,8 +83,28 @@ This labels the axis 0, 50, 100, 150 and 200. Give any of the three, and the app
|
||||
|
||||
`logarithmicBase` makes a value axis' scale logarithmic: each gridline is the one before it times the base. It suits values that grow many times over, such as 12, 95, 610 and 4,800:
|
||||
|
||||
```ts
|
||||
valueAxis: { logarithmicBase: 10, minimum: 1 },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: [2022, 2023, 2024, 2025],
|
||||
series: [{ name: "Users", values: [12, 95, 610, 4800] }],
|
||||
valueAxis: { logarithmicBase: 10, minimum: 1 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
With base 10, the axis is labelled 1, 10, 100, 1,000 and so on. The base goes from `2` to `1000`. Values of 0 or less can't be shown on a logarithmic scale, so its `minimum` and `maximum` have to be above 0.
|
||||
@@ -72,8 +127,28 @@ A percentage format multiplies by 100, as in Excel, so it suits values such as `
|
||||
|
||||
`displayUnits` writes a value axis' labels in thousands, millions and so on, and names the units beside the axis:
|
||||
|
||||
```ts
|
||||
valueAxis: { displayUnits: "thousands" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Revenue", values: [25000, 32000, 41000, 38000] }],
|
||||
valueAxis: { displayUnits: "thousands" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
This labels 25,000 as 25, and the axis "Thousands". The units are `"hundreds"`, `"thousands"`, `"tenThousands"`, `"hundredThousands"`, `"millions"`, `"tenMillions"`, `"hundredMillions"`, `"billions"` and `"trillions"`.
|
||||
@@ -82,11 +157,26 @@ This labels 25,000 as 25, and the axis "Thousands". The units are `"hundreds"`,
|
||||
|
||||
When the categories are all `Date`s, the category axis is a date axis, as in Excel: it spaces the dates by how far apart they are, so a missing month leaves a gap.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: [new Date("2025-01-01"), new Date("2025-02-01"), new Date("2025-05-01")],
|
||||
series: [{ name: "Sign-ups", values: [320, 410, 520] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: [new Date("2025-01-01"), new Date("2025-02-01"), new Date("2025-05-01")],
|
||||
series: [{ name: "Sign-ups", values: [320, 410, 520] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -108,9 +198,29 @@ Dates are read in UTC, as `docx` writes every date, so `new Date("2025-01-31")`
|
||||
|
||||
`reverseOrder: true` puts an axis' categories or values the other way round, as Word's "Categories in reverse order" does. A bar chart's first category is at the bottom, as in Word, so this puts it at the top:
|
||||
|
||||
```ts
|
||||
categoryAxis: { reverseOrder: true },
|
||||
valueAxis: { crossesAt: "maximum" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "bar",
|
||||
categories: ["Design", "Build", "Test"],
|
||||
series: [{ name: "Hours", values: [30, 80, 40] }],
|
||||
categoryAxis: { reverseOrder: true },
|
||||
valueAxis: { crossesAt: "maximum" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Reversing the categories moves the value axis to the other side too, as it crosses the category axis at its first category. `crossesAt: "maximum"` moves it back: see the next section.
|
||||
@@ -127,17 +237,57 @@ Each axis crosses the other one. By default, it crosses where the other axis is
|
||||
| A number | At that value, or on a value axis crossing categories, at that category's number, from 1 |
|
||||
| A `Date` | On a value axis crossing categories that are dates, at that date |
|
||||
|
||||
```ts
|
||||
valueAxis: { crossesAt: "maximum" }, // The value axis on the right
|
||||
categoryAxis: { crossesAt: 50 }, // The category axis at 50, so the bars grow up or down from 50
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Score", values: [40, 65, 55, 30] }],
|
||||
valueAxis: { crossesAt: "maximum" }, // The value axis on the right
|
||||
categoryAxis: { crossesAt: 50 }, // The category axis at 50, so the bars grow up or down from 50
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Label Rotation
|
||||
|
||||
`labelRotation` turns an axis' labels, in degrees clockwise, from `-90` to `90`. `-45` slants them up to the right, which suits long category names:
|
||||
|
||||
```ts
|
||||
categoryAxis: { labelRotation: -45 },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["North America", "South America", "Europe", "Middle East", "Asia Pacific"],
|
||||
series: [{ name: "Sales", values: [120, 60, 95, 40, 110] }],
|
||||
categoryAxis: { labelRotation: -45 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
By default, the application turns the labels when they don't fit.
|
||||
@@ -146,8 +296,28 @@ By default, the application turns the labels when they don't fit.
|
||||
|
||||
An axis' labels are 9 point text in dark grey, and its title 10 point. `font` changes the labels' font, and the title takes a font of its own:
|
||||
|
||||
```ts
|
||||
categoryAxis: { font: { size: 11, bold: true } },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
categoryAxis: { font: { size: 11, bold: true } },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
See [Chart Fonts and Fills](usage/chart-fonts-and-fills.md).
|
||||
@@ -156,18 +326,58 @@ See [Chart Fonts and Fills](usage/chart-fonts-and-fills.md).
|
||||
|
||||
Gridlines are the lines across the chart at each label of an axis. A value axis has them by default, and a category axis doesn't. `gridlines` turns them on or off:
|
||||
|
||||
```ts
|
||||
categoryAxis: { gridlines: true },
|
||||
valueAxis: { gridlines: false },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
categoryAxis: { gridlines: true },
|
||||
valueAxis: { gridlines: false },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Hiding an Axis
|
||||
|
||||
`visible: false` hides an axis and its labels. Its gridlines stay unless you turn them off too:
|
||||
|
||||
```ts
|
||||
categoryAxis: { visible: false },
|
||||
valueAxis: { visible: false, gridlines: false },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
categoryAxis: { visible: false },
|
||||
valueAxis: { visible: false, gridlines: false },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
A chart with no axes, legend or title can be as small as a word. See [Small Charts](usage/chart-size-and-position.md#small-charts).
|
||||
|
||||
+88
-17
@@ -6,22 +6,37 @@ A bubble chart is a scatter chart whose points are bubbles of different sizes, s
|
||||
|
||||
## A Bubble Chart
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "bubble",
|
||||
title: "Markets",
|
||||
series: [
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
name: "Europe",
|
||||
points: [
|
||||
{ x: 12, y: 4.5, size: 740 },
|
||||
{ x: 18, y: 3.1, size: 330 },
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "bubble",
|
||||
title: "Markets",
|
||||
series: [
|
||||
{
|
||||
name: "Europe",
|
||||
points: [
|
||||
{ x: 12, y: 4.5, size: 740 },
|
||||
{ x: 18, y: 3.1, size: 330 },
|
||||
],
|
||||
},
|
||||
{ name: "Asia", points: [{ x: 24, y: 6.8, size: 1400 }] },
|
||||
],
|
||||
xAxis: { title: "Market share (%)" },
|
||||
yAxis: { title: "Growth (%)" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
{ name: "Asia", points: [{ x: 24, y: 6.8, size: 1400 }] },
|
||||
],
|
||||
xAxis: { title: "Market share (%)" },
|
||||
yAxis: { title: "Growth (%)" },
|
||||
});
|
||||
```
|
||||
|
||||
@@ -34,17 +49,73 @@ new ChartRun({
|
||||
- `bubbleScale` makes every bubble bigger or smaller, as a percentage of Office's size, from `0` to `300`. The default is `100`.
|
||||
- `sizeRepresents` says whether a point's `size` is the bubble's area (`"area"`, the default) or its width (`"width"`). By area, a bubble of size 4 looks twice as wide as one of size 1; by width, four times as wide.
|
||||
|
||||
```ts
|
||||
bubbleScale: 60,
|
||||
sizeRepresents: "width",
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "bubble",
|
||||
series: [
|
||||
{
|
||||
name: "Europe",
|
||||
points: [
|
||||
{ x: 12, y: 4.5, size: 740 },
|
||||
{ x: 18, y: 3.1, size: 330 },
|
||||
],
|
||||
},
|
||||
{ name: "Asia", points: [{ x: 24, y: 6.8, size: 1400 }] },
|
||||
],
|
||||
bubbleScale: 60,
|
||||
sizeRepresents: "width",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Labels
|
||||
|
||||
A bubble's label can show its size, as well as what any label shows:
|
||||
|
||||
```ts
|
||||
dataLabels: { bubbleSize: true },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "bubble",
|
||||
series: [
|
||||
{
|
||||
name: "Europe",
|
||||
points: [
|
||||
{ x: 12, y: 4.5, size: 740 },
|
||||
{ x: 18, y: 3.1, size: 330 },
|
||||
],
|
||||
},
|
||||
{ name: "Asia", points: [{ x: 24, y: 6.8, size: 1400 }] },
|
||||
],
|
||||
dataLabels: { bubbleSize: true },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
See [Chart Data Labels](usage/chart-data-labels.md).
|
||||
|
||||
@@ -28,11 +28,30 @@ Give a series a `color` of its own:
|
||||
- a 6-digit hex colour, such as `"1F4E79"`;
|
||||
- or one of the theme's colours, lighter or darker if you like, as Word's colour menus offer them: `{ theme: "accent2", lighter: 40 }` is "Orange, Accent 2, Lighter 40%".
|
||||
|
||||
```ts
|
||||
series: [
|
||||
{ name: "Planned", values: [30, 80, 40], color: "1F4E79" },
|
||||
{ name: "Extra", values: [5, 20, 15], color: { theme: "accent2", lighter: 40 } },
|
||||
],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Jan", "Feb", "Mar"],
|
||||
series: [
|
||||
{ name: "Planned", values: [30, 80, 40], color: "1F4E79" },
|
||||
{ name: "Extra", values: [5, 20, 15], color: { theme: "accent2", lighter: 40 } },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
The colour is the colour of the series' bars, line, area, points or bubbles. Bubbles are drawn in it a quarter see-through, as Office draws them. A line can have a colour of its own too, apart from its markers: see [Lines](usage/chart-line-and-area.md#lines).
|
||||
@@ -41,8 +60,27 @@ The colour is the colour of the series' bars, line, area, points or bubbles. Bub
|
||||
|
||||
A series of bars takes `colors`, with a colour for single bars, in the order of the categories:
|
||||
|
||||
```ts
|
||||
series: [{ name: "Tickets", values: [42, 57, 38, 71], colors: [undefined, undefined, undefined, "70AD47"] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu"],
|
||||
series: [{ name: "Tickets", values: [42, 57, 38, 71], colors: [undefined, undefined, undefined, "70AD47"] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
A bar without a colour, or with `undefined`, keeps the series' colour. See [Column and Bar Charts](usage/chart-column-and-bar.md#bar-colours).
|
||||
@@ -51,8 +89,29 @@ A bar without a colour, or with `undefined`, keeps the series' colour. See [Colu
|
||||
|
||||
A pie or doughnut series takes `colors`, with a colour for each slice, in the order of the categories:
|
||||
|
||||
```ts
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15], colors: ["1F4E79", "2E75B6", undefined, { theme: "accent6" }] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
categories: ["North", "South", "East", "West"],
|
||||
series: [
|
||||
{ name: "Share", values: [40, 25, 20, 15], colors: ["1F4E79", "2E75B6", undefined, { theme: "accent6" }] },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
A slice without a colour, or with `undefined`, keeps the theme's colour. See [Pie and Doughnut Charts](usage/chart-pie-and-doughnut.md#slice-colours).
|
||||
|
||||
@@ -6,14 +6,29 @@ A column chart draws a vertical bar for each value, and a bar chart a horizontal
|
||||
|
||||
## A Column Chart
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales by quarter",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170] },
|
||||
{ name: "2025", values: [140, 150, 165, null] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales by quarter",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170] },
|
||||
{ name: "2025", values: [140, 150, 165, null] },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -24,11 +39,26 @@ Each category has a group of columns, one for each series, side by side. The fir
|
||||
|
||||
A bar chart takes the same options, with `type: "bar"`:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "bar",
|
||||
categories: ["Design", "Build", "Test"],
|
||||
series: [{ name: "Hours", values: [30, 80, 40] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "bar",
|
||||
categories: ["Design", "Build", "Test"],
|
||||
series: [{ name: "Hours", values: [30, 80, 40] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -44,16 +74,31 @@ The categories run up the left side, so the first category is at the bottom, as
|
||||
| `"stacked"` | The bars on top of each other, so each stack is as long as the category's total |
|
||||
| `"percent"` | The bars on top of each other, as percentages of the category's total, so each stack is 100% |
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "bar",
|
||||
title: "Hours by team",
|
||||
categories: ["Design", "Build", "Test"],
|
||||
series: [
|
||||
{ name: "Planned", values: [30, 80, 40] },
|
||||
{ name: "Extra", values: [5, 20, 15] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "bar",
|
||||
title: "Hours by team",
|
||||
categories: ["Design", "Build", "Test"],
|
||||
series: [
|
||||
{ name: "Planned", values: [30, 80, 40] },
|
||||
{ name: "Extra", values: [5, 20, 15] },
|
||||
],
|
||||
stacking: "stacked",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
stacking: "stacked",
|
||||
});
|
||||
```
|
||||
|
||||
@@ -66,16 +111,31 @@ On a 100% stacked chart, the value axis is labelled as percentages. See [Chart A
|
||||
- `gapWidth` goes from `0` (no space between groups) to `500` (five bars' width). A smaller gap makes the bars wider.
|
||||
- `overlap` goes from `-100` (a bar's width apart) to `100` (each bar on top of the one before). `0` puts them side by side, touching.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170] },
|
||||
{ name: "2025", values: [140, 150, 165, 180] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170] },
|
||||
{ name: "2025", values: [140, 150, 165, 180] },
|
||||
],
|
||||
gapWidth: 50,
|
||||
overlap: 0,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
gapWidth: 50,
|
||||
overlap: 0,
|
||||
});
|
||||
```
|
||||
|
||||
@@ -90,12 +150,27 @@ The defaults are Office's:
|
||||
|
||||
Each series' bars take its colour. `colors` gives single bars colours of their own, in the order of the categories, such as to pick out the best result:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Tickets closed",
|
||||
categories: ["Ana", "Ben", "Cai", "Dee"],
|
||||
series: [{ name: "Tickets", values: [42, 57, 38, 71], colors: [undefined, undefined, undefined, "70AD47"] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Tickets closed",
|
||||
categories: ["Ana", "Ben", "Cai", "Dee"],
|
||||
series: [{ name: "Tickets", values: [42, 57, 38, 71], colors: [undefined, undefined, undefined, "70AD47"] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+102
-33
@@ -8,14 +8,29 @@ A combo chart draws some series one way and some another, such as sales as colum
|
||||
|
||||
Give a series a `type` to draw it as `"column"`, `"line"` or `"area"`, whatever the chart's own `type`:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales and target",
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"],
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Target", values: [130, 140, 150, 160], type: "line" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales and target",
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"],
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Target", values: [130, 140, 150, 160], type: "line" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -30,17 +45,32 @@ The options of each way of drawing a series work as they do on its own chart. A
|
||||
|
||||
`axis: "secondary"` draws a series against a second value axis, on the right side of the chart:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales and growth",
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"],
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Growth", values: [4, 12.5, 11.1, 13.3], type: "line", axis: "secondary" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales and growth",
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"],
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Growth", values: [4, 12.5, 11.1, 13.3], type: "line", axis: "secondary" },
|
||||
],
|
||||
valueAxis: { title: "Units" },
|
||||
secondaryValueAxis: { title: "Growth (%)" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
valueAxis: { title: "Units" },
|
||||
secondaryValueAxis: { title: "Growth (%)" },
|
||||
});
|
||||
```
|
||||
|
||||
@@ -56,12 +86,36 @@ A series drawn as columns on the secondary axis is drawn in front of those on th
|
||||
|
||||
A chart's `dataLabels` are on every series, but their `position` is for the series drawn as the chart's `type`, as each way of drawing a series has positions of its own. The others keep Office's positions, unless their own `dataLabels` give one:
|
||||
|
||||
```ts
|
||||
dataLabels: { value: true, position: "insideEnd" },
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Target", values: [130, 140, 150, 160], type: "line", dataLabels: { value: true, position: "above" } },
|
||||
],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"],
|
||||
dataLabels: { value: true, position: "insideEnd" },
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{
|
||||
name: "Target",
|
||||
values: [130, 140, 150, 160],
|
||||
type: "line",
|
||||
dataLabels: { value: true, position: "above" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
See [Where the Labels Go](usage/chart-data-labels.md#where-the-labels-go).
|
||||
@@ -70,16 +124,31 @@ See [Where the Labels Go](usage/chart-data-labels.md#where-the-labels-go).
|
||||
|
||||
`stacking` stacks the series drawn as the chart's `type`. The others aren't stacked, so a line can show the total of stacked columns:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3"],
|
||||
series: [
|
||||
{ name: "North", values: [40, 45, 50] },
|
||||
{ name: "South", values: [30, 35, 30] },
|
||||
{ name: "Total", values: [70, 80, 80], type: "line" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3"],
|
||||
series: [
|
||||
{ name: "North", values: [40, 45, 50] },
|
||||
{ name: "South", values: [30, 35, 30] },
|
||||
{ name: "Total", values: [70, 80, 80], type: "line" },
|
||||
],
|
||||
stacking: "stacked",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
stacking: "stacked",
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+206
-36
@@ -2,12 +2,27 @@
|
||||
|
||||
Data labels write the numbers on a chart: a label on each bar, point or slice. There are no labels by default.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
dataLabels: { value: true },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
dataLabels: { value: true },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -27,16 +42,56 @@ Turn on what each label shows:
|
||||
|
||||
Turn on more than one to show them all in each label:
|
||||
|
||||
```ts
|
||||
dataLabels: { category: true, percentage: true },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
categories: ["North", "South", "East", "West"],
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15] }],
|
||||
dataLabels: { category: true, percentage: true },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Where the Labels Go
|
||||
|
||||
By default, the labels go where Office puts them. `position` puts them somewhere else:
|
||||
|
||||
```ts
|
||||
dataLabels: { value: true, position: "insideEnd" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
dataLabels: { value: true, position: "insideEnd" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Each type of chart has its own positions, and the first is where Office puts the labels:
|
||||
@@ -55,8 +110,28 @@ Word reports a document whose labels are somewhere their chart can't have them a
|
||||
|
||||
`numberFormat` is how the labels' values are written, as an Excel number format, as for an [axis](usage/chart-axes.md#number-format):
|
||||
|
||||
```ts
|
||||
dataLabels: { value: true, numberFormat: "#,##0" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [12000, 13500, 15000, 17000] }],
|
||||
dataLabels: { value: true, numberFormat: "#,##0" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
On a pie or doughnut chart, it is how the percentages are written too: `"0.0%"` writes 12.5%.
|
||||
@@ -65,8 +140,28 @@ On a pie or doughnut chart, it is how the percentages are written too: `"0.0%"`
|
||||
|
||||
Labels are 9 point text in dark grey. `font` changes it, such as white bold labels inside dark bars:
|
||||
|
||||
```ts
|
||||
dataLabels: { value: true, position: "insideEnd", font: { color: "FFFFFF", bold: true } },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
dataLabels: { value: true, position: "insideEnd", font: { color: "FFFFFF", bold: true } },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
See [Chart Fonts and Fills](usage/chart-fonts-and-fills.md).
|
||||
@@ -75,15 +170,30 @@ See [Chart Fonts and Fills](usage/chart-fonts-and-fills.md).
|
||||
|
||||
A series' own `dataLabels` replace the chart's for that series, and `dataLabels: false` gives it none:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170], dataLabels: false },
|
||||
{ name: "2025", values: [140, 150, 165, 180] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170], dataLabels: false },
|
||||
{ name: "2025", values: [140, 150, 165, 180] },
|
||||
],
|
||||
dataLabels: { value: true },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
dataLabels: { value: true },
|
||||
});
|
||||
```
|
||||
|
||||
@@ -93,15 +203,37 @@ Here only the 2025 columns have labels.
|
||||
|
||||
A series' `pointLabels` give single bars, points or slices labels of their own, such as to mark the highest point, in the order of the categories, or of a scatter or bubble chart's points:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
|
||||
series: [
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
name: "Visitors",
|
||||
values: [320, 410, 380, 380, 460, 610, 580],
|
||||
pointLabels: [undefined, undefined, undefined, undefined, undefined, { text: "Record", position: "above" }],
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
|
||||
series: [
|
||||
{
|
||||
name: "Visitors",
|
||||
values: [320, 410, 380, 380, 460, 610, 580],
|
||||
pointLabels: [
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ text: "Record", position: "above" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -115,13 +247,51 @@ Each point's label is one of:
|
||||
|
||||
A point's label has the options of the series' labels, and each it leaves out is the series' label's:
|
||||
|
||||
```ts
|
||||
// Only the last column has a label, with its value
|
||||
pointLabels: [undefined, undefined, undefined, { value: true }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
// Every column shows its value, and the first shows it inside, in bold
|
||||
dataLabels: { value: true },
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170], pointLabels: [{ position: "insideEnd", font: { bold: true } }] }],
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{
|
||||
name: "Sales",
|
||||
values: [120, 135, 150, 170],
|
||||
// Only the last column has a label, with its value
|
||||
pointLabels: [undefined, undefined, undefined, { value: true }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
// Every column shows its value, and the first shows it inside, in bold
|
||||
dataLabels: { value: true },
|
||||
series: [
|
||||
{
|
||||
name: "Sales",
|
||||
values: [120, 135, 150, 170],
|
||||
pointLabels: [{ position: "insideEnd", font: { bold: true } }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
`text` replaces what the label shows with text of its own, a line of the label for each line of the text. A label with text shows nothing else, so it has no `value`, `category`, `seriesName`, `percentage`, `bubbleSize` or `numberFormat`.
|
||||
|
||||
+94
-27
@@ -6,13 +6,28 @@ A chart's data is its categories and its series, or for a scatter or bubble char
|
||||
|
||||
Column, bar, line, area, pie, doughnut and radar charts take their data as a table: a row for each category, and a column for each series.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170] },
|
||||
{ name: "2025", values: [140, 150, 165, null] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170] },
|
||||
{ name: "2025", values: [140, 150, 165, null] },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -37,8 +52,27 @@ Each series can also have a `color`. See [Chart Colours](usage/chart-colors.md).
|
||||
|
||||
When a column, bar, line or area chart's categories are all `Date`s, the category axis spaces them by date, as Excel does, and labels them as dates:
|
||||
|
||||
```ts
|
||||
categories: [new Date("2025-01-01"), new Date("2025-02-01"), new Date("2025-05-01")],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: [new Date("2025-01-01"), new Date("2025-02-01"), new Date("2025-05-01")],
|
||||
series: [{ name: "Sign-ups", values: [320, 410, 520] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
The categories have to be all dates or none. Dates are read in UTC. See [Dates](usage/chart-axes.md#dates) on the axes page.
|
||||
@@ -47,15 +81,30 @@ The categories have to be all dates or none. Dates are read in UTC. See [Dates](
|
||||
|
||||
A column, bar, line or area chart's categories can be in groups, such as quarters in years. The axis labels the categories, with each group's name below its categories:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales by quarter",
|
||||
categories: [
|
||||
{ name: "2024", categories: ["Q1", "Q2", "Q3", "Q4"] },
|
||||
{ name: "2025", categories: ["Q1", "Q2"] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales by quarter",
|
||||
categories: [
|
||||
{ name: "2024", categories: ["Q1", "Q2", "Q3", "Q4"] },
|
||||
{ name: "2025", categories: ["Q1", "Q2"] },
|
||||
],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170, 160, 180] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170, 160, 180] }],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -69,16 +118,34 @@ Pages shows only the groups' names. See [Chart Compatibility](usage/chart-compat
|
||||
|
||||
A [scatter chart](usage/chart-scatter.md) has no categories. Each of its series has `points`, and each point has its own `x` and `y`:
|
||||
|
||||
```ts
|
||||
series: [
|
||||
{
|
||||
name: "Group A",
|
||||
points: [
|
||||
{ x: 150, y: 50 },
|
||||
{ x: 165, y: 61 },
|
||||
],
|
||||
},
|
||||
],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "scatter",
|
||||
series: [
|
||||
{
|
||||
name: "Group A",
|
||||
points: [
|
||||
{ x: 150, y: 50 },
|
||||
{ x: 165, y: 61 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
A [bubble chart](usage/chart-bubble.md)'s points have a `size` too: `{ x: 150, y: 50, size: 12 }`.
|
||||
|
||||
@@ -6,12 +6,27 @@ A chart's text is in the theme's body font, in dark grey, and the chart has a wh
|
||||
|
||||
`font` sets the font of all the chart's text: its title, legend, axes and labels.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
font: { name: "Georgia", color: "404040" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
font: { name: "Georgia", color: "404040" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -35,15 +50,30 @@ The title, the legend, each axis and the labels take a `font` of their own, with
|
||||
| Axis titles | `valueAxis: { title: { text, font } }` | 10 points |
|
||||
| Data labels | `dataLabels: { font }` | 9 points |
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
title: { text: "Rainfall", font: { size: 18, bold: true } },
|
||||
categories: ["Jan", "Feb", "Mar"],
|
||||
series: [{ name: "2025", values: [78, 62, 55] }],
|
||||
font: { name: "Georgia" },
|
||||
legend: { position: "top", font: { italics: true } },
|
||||
valueAxis: { title: { text: "mm", font: { italics: true } }, font: { size: 8 } },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
title: { text: "Rainfall", font: { size: 18, bold: true } },
|
||||
categories: ["Jan", "Feb", "Mar"],
|
||||
series: [{ name: "2025", values: [78, 62, 55] }],
|
||||
font: { name: "Georgia" },
|
||||
legend: { position: "top", font: { italics: true } },
|
||||
valueAxis: { title: { text: "mm", font: { italics: true } }, font: { size: 8 } },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -53,9 +83,29 @@ Here every piece of text is in Georgia, the title is 18 point bold, and the valu
|
||||
|
||||
The chart area is the whole chart, and the plot area is the part inside the axes. `chartArea` and `plotArea` give each a `fill` and a `border`:
|
||||
|
||||
```ts
|
||||
chartArea: { fill: "F7F9FC", border: { color: { theme: "accent1" }, width: 1.5 } },
|
||||
plotArea: { fill: "FFFFFF" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
chartArea: { fill: "F7F9FC", border: { color: { theme: "accent1" }, width: 1.5 } },
|
||||
plotArea: { fill: "FFFFFF" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
- `fill` is a hex colour, a theme colour, or `"none"` for no fill.
|
||||
|
||||
@@ -6,14 +6,29 @@ A line chart draws a line through each series' values, and an area chart fills t
|
||||
|
||||
## A Line Chart
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
title: "Temperature",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [
|
||||
{ name: "High", values: [21, 23, 25, 24, 22] },
|
||||
{ name: "Low", values: [12, 13, 15, 14, 13] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
title: "Temperature",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [
|
||||
{ name: "High", values: [21, 23, 25, 24, 22] },
|
||||
{ name: "Low", values: [12, 13, 15, 14, 13] },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -30,9 +45,28 @@ A `null` value leaves a gap in its line.
|
||||
| `"zero"` | Zero |
|
||||
| `"connect"` | Nothing, with the line joined from the point before to the one after |
|
||||
|
||||
```ts
|
||||
series: [{ name: "Visitors", values: [320, 410, null, 380, 460] }],
|
||||
emptyValues: "connect",
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [{ name: "Visitors", values: [320, 410, null, 380, 460] }],
|
||||
emptyValues: "connect",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Column, bar, line, area, radar and stock charts take `emptyValues`. Only lines are joined: a column chart's `"connect"` is a gap. Pages draws every empty value as a gap. See [Chart Compatibility](usage/chart-compatibility.md).
|
||||
@@ -43,12 +77,27 @@ Column, bar, line, area, radar and stock charts take `emptyValues`. Only lines a
|
||||
|
||||
Markers can have a shape and size of their own. Give `markers` a `shape`, a `size` in points, or both:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [{ name: "High", values: [21, 23, 25, 24, 22] }],
|
||||
markers: { shape: "diamond", size: 8 },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [{ name: "High", values: [21, 23, 25, 24, 22] }],
|
||||
markers: { shape: "diamond", size: 8 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -72,11 +121,30 @@ new ChartRun({
|
||||
|
||||
A series' `line` gives its line a colour, width or dash pattern of its own, such as a dashed line for a target:
|
||||
|
||||
```ts
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Target", values: [130, 140, 150, 160], line: { dash: "dash", width: 1.5 } },
|
||||
],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Target", values: [130, 140, 150, 160], line: { dash: "dash", width: 1.5 } },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
- `width` is in points, from `0` to `1584`. Lines are 2.25 points wide by default.
|
||||
@@ -87,15 +155,30 @@ series: [
|
||||
|
||||
A series' own `markers` and `smooth` replace the chart's, so one series can be different:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [
|
||||
{ name: "High", values: [21, 23, 25, 24, 22] },
|
||||
{ name: "Low", values: [12, 13, 15, 14, 13], markers: { shape: "square" }, smooth: true },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [
|
||||
{ name: "High", values: [21, 23, 25, 24, 22] },
|
||||
{ name: "Low", values: [12, 13, 15, 14, 13], markers: { shape: "square" }, smooth: true },
|
||||
],
|
||||
markers: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
markers: true,
|
||||
});
|
||||
```
|
||||
|
||||
@@ -105,17 +188,32 @@ Here the highs have circles and straight lines, and the lows squares and a smoot
|
||||
|
||||
An area chart takes the same options as a line chart, with `type: "area"` and without markers or lines:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "area",
|
||||
title: "Energy mix",
|
||||
categories: [2021, 2022, 2023, 2024, 2025],
|
||||
series: [
|
||||
{ name: "Wind", values: [20, 24, 28, 31, 35] },
|
||||
{ name: "Solar", values: [10, 13, 17, 21, 26] },
|
||||
{ name: "Gas", values: [45, 40, 35, 30, 25] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "area",
|
||||
title: "Energy mix",
|
||||
categories: [2021, 2022, 2023, 2024, 2025],
|
||||
series: [
|
||||
{ name: "Wind", values: [20, 24, 28, 31, 35] },
|
||||
{ name: "Solar", values: [10, 13, 17, 21, 26] },
|
||||
{ name: "Gas", values: [45, 40, 35, 30, 25] },
|
||||
],
|
||||
stacking: "stacked",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
stacking: "stacked",
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+63
-19
@@ -19,14 +19,29 @@ pie title Pets adopted by volunteers
|
||||
|
||||
is this chart:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
title: "Pets adopted by volunteers",
|
||||
categories: ["Dogs", "Cats", "Rats"],
|
||||
series: [{ name: "Pets", values: [386, 85, 15] }],
|
||||
dataLabels: { percentage: true },
|
||||
legend: { position: "right" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
title: "Pets adopted by volunteers",
|
||||
categories: ["Dogs", "Cats", "Rats"],
|
||||
series: [{ name: "Pets", values: [386, 85, 15] }],
|
||||
dataLabels: { percentage: true },
|
||||
legend: { position: "right" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -48,7 +63,8 @@ A Word chart's series has a name, which Mermaid's pie has none of, so give it on
|
||||
|
||||
When the Mermaid text is what you have, a few lines of your own code can turn a pie chart into a `ChartRun`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
// A Mermaid pie chart as a ChartRun: its title, and a slice for each "label" : value line
|
||||
@@ -69,6 +85,19 @@ const pieFromMermaid = (mermaid: string): ChartRun => {
|
||||
legend: { position: "right" },
|
||||
});
|
||||
};
|
||||
|
||||
const mermaid = `pie title Pets adopted by volunteers
|
||||
"Dogs" : 386
|
||||
"Cats" : 85
|
||||
"Rats" : 15`;
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph({ children: [pieFromMermaid(mermaid)] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
It reads Mermaid's pie syntax only. It leaves out the Mermaid config above the chart, such as its colours and `donutHole`.
|
||||
@@ -88,19 +117,34 @@ xychart
|
||||
|
||||
is this column chart, with its line drawn as a line, as a [combo chart](usage/chart-combo.md):
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const revenue = [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000];
|
||||
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales Revenue",
|
||||
categories: ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"],
|
||||
series: [
|
||||
{ name: "Revenue", values: revenue },
|
||||
{ name: "Trend", values: revenue, type: "line" },
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales Revenue",
|
||||
categories: ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"],
|
||||
series: [
|
||||
{ name: "Revenue", values: revenue },
|
||||
{ name: "Trend", values: revenue, type: "line" },
|
||||
],
|
||||
valueAxis: { title: "Revenue (in $)", minimum: 4000, maximum: 11000 },
|
||||
legend: false,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
valueAxis: { title: "Revenue (in $)", minimum: 4000, maximum: 11000 },
|
||||
legend: false,
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -6,12 +6,27 @@ A pie chart shows the parts of one whole as slices of a circle. A doughnut chart
|
||||
|
||||
## A Pie Chart
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
title: "Market share",
|
||||
categories: ["North", "South", "East", "West"],
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
title: "Market share",
|
||||
categories: ["North", "South", "East", "West"],
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -25,16 +40,31 @@ The values don't need to add up to 100: each slice is its value's share of the t
|
||||
|
||||
A doughnut chart has a ring for each series. The first series is the inside ring.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "doughnut",
|
||||
title: "Budget and spend",
|
||||
categories: ["Staff", "Rent", "Other"],
|
||||
series: [
|
||||
{ name: "Budget", values: [60, 25, 15] },
|
||||
{ name: "Spend", values: [65, 25, 10] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "doughnut",
|
||||
title: "Budget and spend",
|
||||
categories: ["Staff", "Rent", "Other"],
|
||||
series: [
|
||||
{ name: "Budget", values: [60, 25, 15] },
|
||||
{ name: "Spend", values: [65, 25, 10] },
|
||||
],
|
||||
holeSize: 40,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
holeSize: 40,
|
||||
});
|
||||
```
|
||||
|
||||
@@ -44,8 +74,27 @@ new ChartRun({
|
||||
|
||||
Each slice takes the next of the theme's accent colours. `colors` gives the slices colours of their own, in the order of the categories:
|
||||
|
||||
```ts
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15], colors: ["1F4E79", "2E75B6", "9DC3E6", "BDD7EE"] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
categories: ["North", "South", "East", "West"],
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15], colors: ["1F4E79", "2E75B6", "9DC3E6", "BDD7EE"] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
A slice without a colour, or with `undefined`, keeps the theme's colour. A category has the same colour in each ring of a doughnut, so give each ring the same `colors`. [Chart Colours](usage/chart-colors.md) explains the colours a chart can take.
|
||||
@@ -54,8 +103,28 @@ A slice without a colour, or with `undefined`, keeps the theme's colour. A categ
|
||||
|
||||
`dataLabels` puts a label on each slice. On a pie or doughnut chart, a label can show the slice's percentage of the whole:
|
||||
|
||||
```ts
|
||||
dataLabels: { percentage: true },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
categories: ["North", "South", "East", "West"],
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15] }],
|
||||
dataLabels: { percentage: true },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
[Chart Data Labels](usage/chart-data-labels.md) shows what else a label can show, and where labels can go. Each ring of a doughnut can have labels of its own, with its series' own `dataLabels`.
|
||||
@@ -64,14 +133,52 @@ dataLabels: { percentage: true },
|
||||
|
||||
`explosion` pulls slices out from the centre, as Word's "Pie Explosion" and "Point Explosion" do, by a percentage of the radius, from `0` to `400`. One number pulls out every slice:
|
||||
|
||||
```ts
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15], explosion: 10 }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
categories: ["North", "South", "East", "West"],
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15], explosion: 10 }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
A list pulls out each slice by its own amount, in the order of the categories. `undefined` leaves a slice in, so this pulls out only the last:
|
||||
|
||||
```ts
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15], explosion: [undefined, undefined, undefined, 25] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
categories: ["North", "South", "East", "West"],
|
||||
series: [{ name: "Share", values: [40, 25, 20, 15], explosion: [undefined, undefined, undefined, 25] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
A slice pulled out on its own is often labelled on its own too. See [Labels of Single Points](usage/chart-data-labels.md#labels-of-single-points).
|
||||
@@ -84,14 +191,29 @@ The first slice starts at 12 o'clock, and the slices go clockwise. `firstSliceAn
|
||||
|
||||
A pie of pie chart takes some slices out of the pie, and draws them as a second, smaller pie beside it. The pie has one slice in their place, joined to the second pie by lines. A bar of pie chart draws them as a stacked bar instead. They are Word's "Pie of Pie" and "Bar of Pie" charts:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "pieOfPie",
|
||||
title: "Spending",
|
||||
categories: ["Rent", "Food", "Travel", "Books", "Games", "Music"],
|
||||
series: [{ name: "Spending", values: [1200, 450, 180, 60, 45, 30] }],
|
||||
split: { by: "position", count: 3 },
|
||||
dataLabels: { percentage: true },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "pieOfPie",
|
||||
title: "Spending",
|
||||
categories: ["Rent", "Food", "Travel", "Books", "Games", "Music"],
|
||||
series: [{ name: "Spending", values: [1200, 450, 180, 60, 45, 30] }],
|
||||
split: { by: "position", count: 3 },
|
||||
dataLabels: { percentage: true },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+45
-15
@@ -6,16 +6,31 @@ A radar chart has a spoke for each category, and draws each series as a line aro
|
||||
|
||||
## A Radar Chart
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "radar",
|
||||
title: "Skills",
|
||||
categories: ["Speed", "Strength", "Range", "Stamina", "Skill"],
|
||||
series: [
|
||||
{ name: "Alice", values: [4, 3, 5, 2, 4] },
|
||||
{ name: "Bob", values: [3, 5, 2, 4, 3] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "radar",
|
||||
title: "Skills",
|
||||
categories: ["Speed", "Strength", "Range", "Stamina", "Skill"],
|
||||
series: [
|
||||
{ name: "Alice", values: [4, 3, 5, 2, 4] },
|
||||
{ name: "Bob", values: [3, 5, 2, 4, 3] },
|
||||
],
|
||||
valueAxis: { minimum: 0, maximum: 5, interval: 1 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
valueAxis: { minimum: 0, maximum: 5, interval: 1 },
|
||||
});
|
||||
```
|
||||
|
||||
@@ -28,12 +43,27 @@ new ChartRun({
|
||||
- `markers: true` draws a circle at each point, as Word's "Radar with Markers" does. Markers can have a shape and size of their own. See [Markers](usage/chart-line-and-area.md#markers).
|
||||
- `filled: true` fills the area inside each series' line, as Word's "Filled Radar" does. A filled radar chart has no markers, and its series no lines.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "radar",
|
||||
categories: ["Speed", "Strength", "Range", "Stamina", "Skill"],
|
||||
series: [{ name: "Alice", values: [4, 3, 5, 2, 4] }],
|
||||
filled: true,
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "radar",
|
||||
categories: ["Speed", "Strength", "Range", "Stamina", "Skill"],
|
||||
series: [{ name: "Alice", values: [4, 3, 5, 2, 4] }],
|
||||
filled: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+84
-29
@@ -6,29 +6,44 @@ A scatter chart plots points, each with its own x and y. Use it to show how two
|
||||
|
||||
## A Scatter Chart
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "scatter",
|
||||
title: "Height and weight",
|
||||
series: [
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
name: "Group A",
|
||||
points: [
|
||||
{ x: 150, y: 50 },
|
||||
{ x: 165, y: 61 },
|
||||
{ x: 180, y: 75 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Group B",
|
||||
points: [
|
||||
{ x: 155, y: 58 },
|
||||
{ x: 170, y: 72 },
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "scatter",
|
||||
title: "Height and weight",
|
||||
series: [
|
||||
{
|
||||
name: "Group A",
|
||||
points: [
|
||||
{ x: 150, y: 50 },
|
||||
{ x: 165, y: 61 },
|
||||
{ x: 180, y: 75 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Group B",
|
||||
points: [
|
||||
{ x: 155, y: 58 },
|
||||
{ x: 170, y: 72 },
|
||||
],
|
||||
},
|
||||
],
|
||||
xAxis: { title: "Height (cm)" },
|
||||
yAxis: { title: "Weight (kg)" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
xAxis: { title: "Height (cm)" },
|
||||
yAxis: { title: "Weight (kg)" },
|
||||
});
|
||||
```
|
||||
|
||||
@@ -43,20 +58,60 @@ A scatter chart draws a circle at each point, and doesn't join them:
|
||||
|
||||
Markers can have a shape and size, as on a line chart, and a series' `line` a colour, width and dash pattern. A series' own `markers` replace the chart's. See [Markers](usage/chart-line-and-area.md#markers) and [Lines](usage/chart-line-and-area.md#lines).
|
||||
|
||||
```ts
|
||||
series: [
|
||||
{ name: "Group A", points: [{ x: 150, y: 50 }, { x: 165, y: 61 }], markers: { shape: "triangle", size: 7 } },
|
||||
],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "scatter",
|
||||
series: [
|
||||
{
|
||||
name: "Group A",
|
||||
points: [
|
||||
{ x: 150, y: 50 },
|
||||
{ x: 165, y: 61 },
|
||||
],
|
||||
markers: { shape: "triangle", size: 7 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
A smooth line without markers draws a curve, such as a graph of a formula:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "scatter",
|
||||
series: [{ name: "y = x²", points: [-2, -1, 0, 1, 2].map((x) => ({ x, y: x * x })) }],
|
||||
markers: false,
|
||||
lines: "smooth",
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "scatter",
|
||||
series: [{ name: "y = x²", points: [-2, -1, 0, 1, 2].map((x) => ({ x, y: x * x })) }],
|
||||
markers: false,
|
||||
lines: "smooth",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -6,12 +6,27 @@ A chart is a run in a paragraph, like an image. It sits in the line of text, whe
|
||||
|
||||
`transformation` is the chart's size in pixels, at 96 pixels to an inch:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
transformation: { width: 400, height: 250 },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
transformation: { width: 400, height: 250 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -23,19 +38,30 @@ As in Word, a chart can be made wider without being made taller: its aspect rati
|
||||
|
||||
A chart with no title, legend or axes can be as small as a word, such as a trend beside a heading:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Visitors this year "),
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
|
||||
series: [{ name: "Visitors", values: [12, 15, 14, 18, 22, 21] }],
|
||||
legend: false,
|
||||
categoryAxis: { visible: false },
|
||||
valueAxis: { visible: false, gridlines: false },
|
||||
transformation: { width: 144, height: 48 },
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Visitors this year "),
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
|
||||
series: [{ name: "Visitors", values: [12, 15, 14, 18, 22, 21] }],
|
||||
legend: false,
|
||||
categoryAxis: { visible: false },
|
||||
valueAxis: { visible: false, gridlines: false },
|
||||
transformation: { width: 144, height: 48 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -46,21 +72,44 @@ Apple Pages doesn't draw a chart less than about half an inch (48 pixels) tall.
|
||||
|
||||
Add `floating` to position the chart on the page instead of in the line of text, with text wrapping around it. The options are the same as for [floating images](usage/images.md#floating), and the positions and wrapping types come from `docx`:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Mon", "Tue", "Wed"],
|
||||
series: [{ name: "Orders", values: [8, 12, 9] }],
|
||||
transformation: { width: 260, height: 180 },
|
||||
floating: {
|
||||
horizontalPosition: { relative: HorizontalPositionRelativeFrom.MARGIN, align: HorizontalPositionAlign.RIGHT },
|
||||
verticalPosition: { relative: VerticalPositionRelativeFrom.PARAGRAPH, offset: 0 },
|
||||
wrap: { type: TextWrappingType.SQUARE, side: TextWrappingSide.LEFT },
|
||||
},
|
||||
}),
|
||||
new TextRun("This text wraps around the chart, which is at the right margin."),
|
||||
```ts live
|
||||
import {
|
||||
Document,
|
||||
HorizontalPositionAlign,
|
||||
HorizontalPositionRelativeFrom,
|
||||
Paragraph,
|
||||
TextRun,
|
||||
TextWrappingSide,
|
||||
TextWrappingType,
|
||||
VerticalPositionRelativeFrom,
|
||||
} from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Mon", "Tue", "Wed"],
|
||||
series: [{ name: "Orders", values: [8, 12, 9] }],
|
||||
transformation: { width: 260, height: 180 },
|
||||
floating: {
|
||||
horizontalPosition: {
|
||||
relative: HorizontalPositionRelativeFrom.MARGIN,
|
||||
align: HorizontalPositionAlign.RIGHT,
|
||||
},
|
||||
verticalPosition: { relative: VerticalPositionRelativeFrom.PARAGRAPH, offset: 0 },
|
||||
wrap: { type: TextWrappingType.SQUARE, side: TextWrappingSide.LEFT },
|
||||
},
|
||||
}),
|
||||
new TextRun("This text wraps around the chart, which is at the right margin."),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -71,32 +120,43 @@ A chart can go in any paragraph: in the body, a table cell, a header, a footer o
|
||||
|
||||
To put two charts side by side, put each in a cell of a table, and make each narrower than its cell:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const cell = (chart: ChartRun): TableCell => new TableCell({ children: [new Paragraph({ children: [chart] })] });
|
||||
|
||||
new Table({
|
||||
width: { size: 100, type: WidthType.PERCENTAGE },
|
||||
rows: [
|
||||
new TableRow({
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
cell(
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
categories: ["North", "South", "East"],
|
||||
series: [{ name: "Share", values: [50, 30, 20] }],
|
||||
transformation: { width: 290, height: 260 },
|
||||
}),
|
||||
),
|
||||
cell(
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["North", "South", "East"],
|
||||
series: [{ name: "Sales", values: [120, 70, 45] }],
|
||||
transformation: { width: 290, height: 260 },
|
||||
}),
|
||||
),
|
||||
new Table({
|
||||
width: { size: 100, type: WidthType.PERCENTAGE },
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
cell(
|
||||
new ChartRun({
|
||||
type: "pie",
|
||||
categories: ["North", "South", "East"],
|
||||
series: [{ name: "Share", values: [50, 30, 20] }],
|
||||
transformation: { width: 290, height: 260 },
|
||||
}),
|
||||
),
|
||||
cell(
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["North", "South", "East"],
|
||||
series: [{ name: "Sales", values: [120, 70, 45] }],
|
||||
transformation: { width: 290, height: 260 },
|
||||
}),
|
||||
),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -105,16 +165,16 @@ new Table({
|
||||
|
||||
`patchDocument` puts a chart where a template has a placeholder, as it does an image. A `DOCUMENT` patch takes a paragraph with the chart in it, and a `PARAGRAPH` patch takes the chart itself, with any other runs:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Paragraph, patchDocument, PatchType } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("Template.docx"),
|
||||
data: fs.readFileSync("./demo/assets/simple-template.docx"),
|
||||
patches: {
|
||||
sales_chart: {
|
||||
paragraph_replace: {
|
||||
type: PatchType.DOCUMENT,
|
||||
children: [
|
||||
new Paragraph({
|
||||
@@ -130,6 +190,8 @@ const doc = await patchDocument({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
The chart is added with its workbook, so Word's "Edit Data" works, as it does for a chart in a new `Document`. Placeholders in headers and footers take charts too. See [Patcher](usage/patcher.md).
|
||||
@@ -142,11 +204,32 @@ A chart is described for screen readers from its type, title and data, such as "
|
||||
|
||||
`altText` gives the chart a description of your own, which is better when the chart has a point to make:
|
||||
|
||||
```ts
|
||||
altText: {
|
||||
name: "Sales by quarter",
|
||||
description: "Sales rose each quarter, from 120 units in Q1 to 170 in Q4",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales by quarter",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
altText: {
|
||||
name: "Sales by quarter",
|
||||
description: "Sales rose each quarter, from 120 units in Q1 to 170 in Q4",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
`name` is required, and `description` and `title` are optional. A chart with `altText` but no `description` is still described from its data.
|
||||
|
||||
+99
-18
@@ -8,14 +8,29 @@ A stock chart shows how a price moved over each day, or other period: its highes
|
||||
|
||||
## A Stock Chart
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "stock",
|
||||
title: "Share price",
|
||||
categories: [new Date("2025-01-06"), new Date("2025-01-07"), new Date("2025-01-08")],
|
||||
high: [103.1, 104.8, 105.0],
|
||||
low: [100.4, 101.9, 102.6],
|
||||
close: [102.4, 104.2, 102.9],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "stock",
|
||||
title: "Share price",
|
||||
categories: [new Date("2025-01-06"), new Date("2025-01-07"), new Date("2025-01-08")],
|
||||
high: [103.1, 104.8, 105.0],
|
||||
low: [100.4, 101.9, 102.6],
|
||||
close: [102.4, 104.2, 102.9],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -29,10 +44,32 @@ Each high has to be at least its low, and each open and close between them. `new
|
||||
|
||||
`open` adds each category's opening price. A bar goes from the open to the close: white where the price rose, and dark grey where it fell. This is Word's "Open-High-Low-Close" chart, also known as a candlestick chart:
|
||||
|
||||
```ts
|
||||
open: [101.2, 102.5, 104.1],
|
||||
upBars: { fill: "70AD47" },
|
||||
downBars: { fill: "C00000" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "stock",
|
||||
categories: [new Date("2025-01-06"), new Date("2025-01-07"), new Date("2025-01-08")],
|
||||
high: [103.1, 104.8, 105.0],
|
||||
low: [100.4, 101.9, 102.6],
|
||||
close: [102.4, 104.2, 102.9],
|
||||
open: [101.2, 102.5, 104.1],
|
||||
upBars: { fill: "70AD47" },
|
||||
downBars: { fill: "C00000" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
`upBars` and `downBars` are the fill and border of the bars where the price rose and fell, as `{ fill, border }`, like the [chart area's](usage/chart-fonts-and-fills.md).
|
||||
@@ -41,10 +78,32 @@ downBars: { fill: "C00000" },
|
||||
|
||||
`volume` adds each category's volume traded, as columns against an axis of their own on the left. The prices' axis moves to the right. This is Word's "Volume-High-Low-Close" chart, or with `open`, its "Volume-Open-High-Low-Close" chart:
|
||||
|
||||
```ts
|
||||
volume: [18200, 21500, 26400],
|
||||
volumeAxis: { displayUnits: "thousands" },
|
||||
valueAxis: { minimum: 90 },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "stock",
|
||||
categories: [new Date("2025-01-06"), new Date("2025-01-07"), new Date("2025-01-08")],
|
||||
high: [103.1, 104.8, 105.0],
|
||||
low: [100.4, 101.9, 102.6],
|
||||
close: [102.4, 104.2, 102.9],
|
||||
volume: [18200, 21500, 26400],
|
||||
volumeAxis: { displayUnits: "thousands" },
|
||||
valueAxis: { minimum: 90 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
`volumeAxis` is the volumes' axis, and `valueAxis` is always the prices' axis. Volumes can't be negative.
|
||||
@@ -57,8 +116,30 @@ A stock chart's dates are spaced evenly, one for each category, rather than by d
|
||||
|
||||
The legend shows the series by Word's names: "Volume", "Open", "High", "Low" and "Close". `names` changes them, such as to another language:
|
||||
|
||||
```ts
|
||||
names: { high: "Haut", low: "Bas", close: "Clôture" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "stock",
|
||||
categories: [new Date("2025-01-06"), new Date("2025-01-07"), new Date("2025-01-08")],
|
||||
high: [103.1, 104.8, 105.0],
|
||||
low: [100.4, 101.9, 102.6],
|
||||
close: [102.4, 104.2, 102.9],
|
||||
names: { high: "Haut", low: "Bas", close: "Clôture" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Only the volumes, and the closing price when there are no opening prices, have a key in the legend, so a stock chart without volumes often has `legend: false`.
|
||||
|
||||
+100
-23
@@ -13,14 +13,36 @@
|
||||
2. Right-click the chart, choose **Edit Alt Text**, and type a placeholder as its description, such as `{{sales}}`.
|
||||
3. Patch the template with a `ChartDataPatch` for the placeholder's key:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { patchDocument } from "docx";
|
||||
import { ChartDataPatch } from "docx/charts";
|
||||
import { Document, Packer, Paragraph, patchDocument } from "docx";
|
||||
import { ChartDataPatch, ChartRun } from "docx/charts";
|
||||
|
||||
// The template, made here as it would be in Word: a styled chart, with {{sales}} as its alt text's description
|
||||
const template = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales by quarter",
|
||||
categories: ["Q1", "Q2"],
|
||||
series: [{ name: "Last year", values: [100, 120], color: "1F4E79" }],
|
||||
dataLabels: { value: true },
|
||||
altText: { name: "Sales", description: "{{sales}}" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("Template.docx"),
|
||||
data: await Packer.toBuffer(template),
|
||||
patches: {
|
||||
sales: new ChartDataPatch({
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
@@ -31,6 +53,8 @@ const doc = await patchDocument({
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
Text patches, new charts and `ChartDataPatch`es go in the same `patches`. A `ChartDataPatch` only looks in charts' alt text, and a text patch only in text, so `{{sales}}` typed in the document's text stays as it is.
|
||||
@@ -41,33 +65,86 @@ Every chart whose alt text holds the placeholder gets the data, wherever it is:
|
||||
|
||||
The data is given as it is to [`ChartRun`](usage/chart-data.md), without the chart's `type`, which is the template's:
|
||||
|
||||
```ts
|
||||
// A column, bar, line, area, pie, doughnut or radar chart
|
||||
new ChartDataPatch({
|
||||
categories: ["Jan", "Feb", "Mar"],
|
||||
series: [{ name: "Visitors", values: [320, 410, null] }],
|
||||
});
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph, patchDocument } from "docx";
|
||||
import { ChartDataPatch, ChartRun } from "docx/charts";
|
||||
|
||||
// A scatter chart, or with each point's size, a bubble chart
|
||||
new ChartDataPatch({
|
||||
series: [
|
||||
// The template, made here as it would be in Word: a line, a bubble and a stock chart, each with a placeholder as its alt text
|
||||
const template = new Document({
|
||||
sections: [
|
||||
{
|
||||
name: "Stores",
|
||||
points: [
|
||||
{ x: 12, y: 340, size: 4 },
|
||||
{ x: 30, y: 510, size: 9 },
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
categories: ["A", "B"],
|
||||
series: [{ name: "Series 1", values: [1, 2] }],
|
||||
altText: { name: "Visitors", description: "{{visitors}}" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "bubble",
|
||||
series: [{ name: "Series 1", points: [{ x: 1, y: 1, size: 1 }] }],
|
||||
altText: { name: "Stores", description: "{{stores}}" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "stock",
|
||||
categories: ["A", "B"],
|
||||
high: [2, 3],
|
||||
low: [1, 2],
|
||||
close: [1.5, 2.5],
|
||||
altText: { name: "Prices", description: "{{prices}}" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// A stock chart: its prices, and its opening prices and volumes if it has them
|
||||
new ChartDataPatch({
|
||||
categories: [new Date("2025-01-06"), new Date("2025-01-07")],
|
||||
high: [103.1, 104.8],
|
||||
low: [100.4, 101.9],
|
||||
close: [102.4, 104.2],
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: await Packer.toBuffer(template),
|
||||
patches: {
|
||||
// A column, bar, line, area, pie, doughnut or radar chart
|
||||
visitors: new ChartDataPatch({
|
||||
categories: ["Jan", "Feb", "Mar"],
|
||||
series: [{ name: "Visitors", values: [320, 410, null] }],
|
||||
}),
|
||||
|
||||
// A scatter chart, or with each point's size, a bubble chart
|
||||
stores: new ChartDataPatch({
|
||||
series: [
|
||||
{
|
||||
name: "Stores",
|
||||
points: [
|
||||
{ x: 12, y: 340, size: 4 },
|
||||
{ x: 30, y: 510, size: 9 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
|
||||
// A stock chart: its prices, and its opening prices and volumes if it has them
|
||||
prices: new ChartDataPatch({
|
||||
categories: [new Date("2025-01-06"), new Date("2025-01-07")],
|
||||
high: [103.1, 104.8],
|
||||
low: [100.4, 101.9],
|
||||
close: [102.4, 104.2],
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
| Option | Type | Notes |
|
||||
|
||||
@@ -6,12 +6,27 @@ A chart's title says what it shows, and its legend says which colour is which se
|
||||
|
||||
`title` is written above the chart. There is no title by default.
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales by quarter",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Sales by quarter",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -19,8 +34,28 @@ Each line of the text is a line of the title, so `"Sales by quarter\n2024"` is a
|
||||
|
||||
To give the title a font of its own, give `title` its `text` and a `font`:
|
||||
|
||||
```ts
|
||||
title: { text: "Sales by quarter", font: { size: 18, bold: true, color: "1F4E79" } },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: { text: "Sales by quarter", font: { size: 18, bold: true, color: "1F4E79" } },
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [{ name: "Sales", values: [120, 135, 150, 170] }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
The title is 14 point text by default. See [Chart Fonts and Fills](usage/chart-fonts-and-fills.md).
|
||||
@@ -39,21 +74,59 @@ The legend is below the chart by default. It shows each series' name, or on a pi
|
||||
| `"right"` | To the right of the chart |
|
||||
| `"topRight"` | In the top right corner |
|
||||
|
||||
```ts
|
||||
legend: { position: "right" },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "2024", values: [120, 135, 150, 170] },
|
||||
{ name: "2025", values: [140, 150, 165, 180] },
|
||||
],
|
||||
legend: { position: "right" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
The legend takes a `font` too, such as `legend: { position: "right", font: { size: 10 } }`. Its text is 9 point by default.
|
||||
|
||||
`legend: false` leaves out the legend. A chart with one series often doesn't need one, as its title can say what the series is:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Orders",
|
||||
categories: ["Mon", "Tue", "Wed"],
|
||||
series: [{ name: "Orders", values: [8, 12, 9] }],
|
||||
legend: false,
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Orders",
|
||||
categories: ["Mon", "Tue", "Wed"],
|
||||
series: [{ name: "Orders", values: [8, 12, 9] }],
|
||||
legend: false,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -61,12 +134,31 @@ new ChartRun({
|
||||
|
||||
`hiddenEntries` leaves entries out of the legend, by their text, such as a target line everyone knows:
|
||||
|
||||
```ts
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Target", values: [140, 140, 140, 140], type: "line" },
|
||||
],
|
||||
legend: { hiddenEntries: ["Target"] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Q1", "Q2", "Q3", "Q4"],
|
||||
series: [
|
||||
{ name: "Sales", values: [120, 135, 150, 170] },
|
||||
{ name: "Target", values: [140, 140, 140, 140], type: "line" },
|
||||
],
|
||||
legend: { hiddenEntries: ["Target"] },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
An entry is a series' name, a [trendline's](usage/chart-trendlines-and-error-bars.md) name, such as "Linear (Sales)", or on a pie or doughnut chart, a category. The series stays in the chart. `new ChartRun(...)` throws for text that isn't an entry's, and lists the entries.
|
||||
@@ -77,17 +169,32 @@ Pages shows every entry. See [Chart Compatibility](usage/chart-compatibility.md)
|
||||
|
||||
`dataTable: true` puts a table of the chart's data under its plot, as Word's "Data Table" does: a row for each series, with its key from the legend, and a column for each category. It is often used in place of labels, or of the legend:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Rainfall (mm)",
|
||||
categories: ["Jan", "Feb", "Mar"],
|
||||
series: [
|
||||
{ name: "2024", values: [78, 52, 61] },
|
||||
{ name: "2025", values: [83, 60, 49] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
title: "Rainfall (mm)",
|
||||
categories: ["Jan", "Feb", "Mar"],
|
||||
series: [
|
||||
{ name: "2024", values: [78, 52, 61] },
|
||||
{ name: "2025", values: [83, 60, 49] },
|
||||
],
|
||||
dataTable: true,
|
||||
legend: false,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
dataTable: true,
|
||||
legend: false,
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -8,16 +8,31 @@ A trendline is a line fitted to a series' values, which shows their trend and ca
|
||||
|
||||
A series' `trendlines` fit lines to its values:
|
||||
|
||||
```ts
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
title: "Visitors",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
name: "Visitors",
|
||||
values: [320, 410, 380, 460, 610],
|
||||
trendlines: [{ type: "linear", forecastForward: 2, equation: true, rSquared: true }],
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "line",
|
||||
title: "Visitors",
|
||||
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
|
||||
series: [
|
||||
{
|
||||
name: "Visitors",
|
||||
values: [320, 410, 380, 460, 610],
|
||||
trendlines: [{ type: "linear", forecastForward: 2, equation: true, rSquared: true }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -62,8 +77,27 @@ A moving average has none of these but `name` and `line`.
|
||||
|
||||
A series' `errorBars` draw a line from each point, up and down, or on a bar chart, left and right:
|
||||
|
||||
```ts
|
||||
series: [{ name: "Average", values: [72, 65, 81], errorBars: { type: "percentage", value: 10 } }],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Class A", "Class B", "Class C"],
|
||||
series: [{ name: "Average", values: [72, 65, 81], errorBars: { type: "percentage", value: 10 } }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
`type` is how long the bars are, as in Word's "Format Error Bars":
|
||||
@@ -88,8 +122,33 @@ Column, bar, line, area, scatter and bubble charts have error bars, stacked or n
|
||||
|
||||
Custom error bars have a length of each point's own, such as a range of uncertainty. `plus` is how far each bar goes towards higher values, and `minus` towards lower ones, in the order of the categories or points:
|
||||
|
||||
```ts
|
||||
errorBars: { type: "custom", plus: [6, 9, 4], minus: [5, 8, 6] },
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "column",
|
||||
categories: ["Class A", "Class B", "Class C"],
|
||||
series: [
|
||||
{
|
||||
name: "Average",
|
||||
values: [72, 65, 81],
|
||||
errorBars: { type: "custom", plus: [6, 9, 4], minus: [5, 8, 6] },
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
- Give `plus`, `minus` or both. Bars go only the ways given, so custom error bars have no `direction`.
|
||||
@@ -100,18 +159,36 @@ errorBars: { type: "custom", plus: [6, 9, 4], minus: [5, 8, 6] },
|
||||
|
||||
A scatter or bubble chart's points can have error bars both ways: `xErrorBars` go left and right, along the x axis, and `yErrorBars` up and down:
|
||||
|
||||
```ts
|
||||
series: [
|
||||
{
|
||||
name: "Samples",
|
||||
points: [
|
||||
{ x: 1, y: 2.1 },
|
||||
{ x: 2, y: 3.9 },
|
||||
],
|
||||
xErrorBars: { type: "fixed", value: 0.2 },
|
||||
yErrorBars: { type: "standardError" },
|
||||
},
|
||||
],
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ChartRun({
|
||||
type: "scatter",
|
||||
series: [
|
||||
{
|
||||
name: "Samples",
|
||||
points: [
|
||||
{ x: 1, y: 2.1 },
|
||||
{ x: 2, y: 3.9 },
|
||||
],
|
||||
xErrorBars: { type: "fixed", value: 0.2 },
|
||||
yErrorBars: { type: "standardError" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Compatibility
|
||||
|
||||
@@ -8,7 +8,7 @@ Like an image, a chart is a run inside a `Paragraph`.
|
||||
|
||||
## Your First Chart
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
import { ChartRun } from "docx/charts";
|
||||
|
||||
+61
-27
@@ -10,7 +10,7 @@ Checkboxes allow you to add interactive checkbox controls to your Word documents
|
||||
|
||||
Create a simple checkbox:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { CheckBox, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -30,9 +30,19 @@ const doc = new Document({
|
||||
|
||||
Create a pre-checked checkbox:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [new CheckBox({ checked: true }), new TextRun(" Completed task")],
|
||||
```ts live
|
||||
import { CheckBox, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new CheckBox({ checked: true }), new TextRun(" Completed task")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -40,17 +50,31 @@ new Paragraph({
|
||||
|
||||
You can customize the symbols used for checked and unchecked states. This is useful for branding consistency, platform compatibility, or when the default symbols don't render correctly on certain systems:
|
||||
|
||||
```ts
|
||||
new CheckBox({
|
||||
checked: true,
|
||||
checkedState: {
|
||||
value: "2611", // Unicode ballot box with check
|
||||
font: "MS Gothic",
|
||||
},
|
||||
uncheckedState: {
|
||||
value: "2610", // Unicode ballot box
|
||||
font: "MS Gothic",
|
||||
},
|
||||
```ts live
|
||||
import { CheckBox, Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new CheckBox({
|
||||
checked: true,
|
||||
checkedState: {
|
||||
value: "2611", // Unicode ballot box with check
|
||||
font: "MS Gothic",
|
||||
},
|
||||
uncheckedState: {
|
||||
value: "2610", // Unicode ballot box
|
||||
font: "MS Gothic",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -84,16 +108,26 @@ new CheckBox({
|
||||
|
||||
Use the `alias` property to provide an accessibility label:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Do you agree to the terms?"),
|
||||
new TextRun({ break: 1 }),
|
||||
new CheckBox({
|
||||
checked: false,
|
||||
alias: "Terms agreement checkbox",
|
||||
}),
|
||||
new TextRun(" Yes, I agree"),
|
||||
```ts live
|
||||
import { CheckBox, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Do you agree to the terms?"),
|
||||
new TextRun({ break: 1 }),
|
||||
new CheckBox({
|
||||
checked: false,
|
||||
alias: "Terms agreement checkbox",
|
||||
}),
|
||||
new TextRun(" Yes, I agree"),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -102,7 +136,7 @@ new Paragraph({
|
||||
|
||||
Create a complete checklist:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { CheckBox, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const tasks = [
|
||||
@@ -128,7 +162,7 @@ const doc = new Document({
|
||||
|
||||
## Form with Multiple Checkboxes
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { CheckBox, Document, HeadingLevel, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
|
||||
+61
-23
@@ -8,7 +8,7 @@ Create multi-column layouts like newspapers or newsletters by configuring column
|
||||
|
||||
Create equal-width columns:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -20,7 +20,11 @@ const doc = new Document({
|
||||
space: 708, // Space between columns (~0.5 inches in twips; 1440 twips = 1 inch)
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("This text will flow across two columns...")],
|
||||
children: [
|
||||
new Paragraph(
|
||||
"This text will flow across two columns. When it reaches the bottom of the first column, it carries on at the top of the second, the way the text of a newspaper or a newsletter does. Add more text to see it flow from one column into the next.",
|
||||
),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -40,21 +44,34 @@ const doc = new Document({
|
||||
|
||||
Add a vertical line between columns:
|
||||
|
||||
```ts
|
||||
properties: {
|
||||
column: {
|
||||
count: 2,
|
||||
space: 708,
|
||||
separate: true, // Adds a line between columns
|
||||
},
|
||||
}
|
||||
```ts live
|
||||
import { ColumnBreak, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
column: {
|
||||
count: 2,
|
||||
space: 708,
|
||||
separate: true, // Adds a line between columns
|
||||
},
|
||||
},
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun("This text is in column 1."), new ColumnBreak(), new TextRun("This text is in column 2.")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Different Width Columns
|
||||
|
||||
Create columns with custom widths:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Column, Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -71,7 +88,11 @@ const doc = new Document({
|
||||
],
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("Content flows through unequal columns...")],
|
||||
children: [
|
||||
new Paragraph(
|
||||
"Content flows through unequal columns. The first column is two inches wide, with half an inch of space after it, and the second column is four inches wide, so the text fills a narrow column and then a wide one.",
|
||||
),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -88,7 +109,7 @@ const doc = new Document({
|
||||
|
||||
Force content to the next column using `ColumnBreak`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { ColumnBreak, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -112,20 +133,33 @@ const doc = new Document({
|
||||
|
||||
## Three Columns
|
||||
|
||||
```ts
|
||||
properties: {
|
||||
column: {
|
||||
count: 3,
|
||||
space: 708,
|
||||
},
|
||||
}
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
column: {
|
||||
count: 3,
|
||||
space: 708,
|
||||
},
|
||||
},
|
||||
children: [
|
||||
new Paragraph(
|
||||
"This text flows across three columns. Three narrow columns suit lists, glossaries and short news items, where each line holds only a few words. The text fills the first column, then the second, and then the third.",
|
||||
),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Mixing Column Layouts
|
||||
|
||||
Use multiple sections to mix column layouts:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, SectionType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -143,7 +177,11 @@ const doc = new Document({
|
||||
space: 708,
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("This content flows in two columns...")],
|
||||
children: [
|
||||
new Paragraph(
|
||||
"This content flows in two columns. The continuous section breaks before and after it keep the columns on the same page as the full-width paragraphs above and below them.",
|
||||
),
|
||||
],
|
||||
},
|
||||
// Back to single column
|
||||
{
|
||||
@@ -160,7 +198,7 @@ const doc = new Document({
|
||||
|
||||
Newsletter-style layout with unequal columns:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Column, ColumnBreak, Document, HeadingLevel, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
|
||||
+116
-48
@@ -16,18 +16,18 @@ To add comments in `docx`:
|
||||
|
||||
Add a comment to a range of text:
|
||||
|
||||
```ts
|
||||
import { Comment, CommentRangeEnd, CommentRangeStart, CommentReference, Document, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { CommentRangeEnd, CommentRangeStart, CommentReference, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
comments: {
|
||||
children: [
|
||||
new Comment({
|
||||
{
|
||||
id: 0,
|
||||
author: "John Smith",
|
||||
date: new Date(),
|
||||
children: [new Paragraph("This needs to be reviewed.")],
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
@@ -60,17 +60,35 @@ const doc = new Document({
|
||||
| parentId | `number` | Optional | ID of parent comment for reply threading |
|
||||
| resolved | `boolean` | Optional | Whether the comment thread is marked as resolved. The entire thread displays as resolved in Word |
|
||||
|
||||
?> Comments in the `children` array can be passed as plain objects or as `new Comment({...})` instances — both forms are equivalent.
|
||||
|
||||
## Point Comment
|
||||
|
||||
Add a comment at a specific point (not a range):
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Check this point"),
|
||||
new CommentReference(0), // Comment appears here
|
||||
```ts live
|
||||
import { CommentReference, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
comments: {
|
||||
children: [
|
||||
{
|
||||
id: 0,
|
||||
author: "John Smith",
|
||||
date: new Date(),
|
||||
children: [new Paragraph("A comment at this point.")],
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Check this point"),
|
||||
new CommentReference(0), // Comment appears here
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -79,22 +97,24 @@ new Paragraph({
|
||||
|
||||
Add several comments to a document:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { CommentRangeEnd, CommentRangeStart, CommentReference, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
comments: {
|
||||
children: [
|
||||
new Comment({
|
||||
{
|
||||
id: 0,
|
||||
author: "Alice",
|
||||
date: new Date("2024-01-15"),
|
||||
children: [new Paragraph("First comment")],
|
||||
}),
|
||||
new Comment({
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
author: "Bob",
|
||||
date: new Date("2024-01-16"),
|
||||
children: [new Paragraph("Second comment")],
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
@@ -123,7 +143,9 @@ const doc = new Document({
|
||||
|
||||
Create comment replies using the `parentId` property to build a thread. Reply comments must also have `CommentRangeStart`, `CommentRangeEnd`, and `CommentReference` wrapping the same text as their parent — Word uses these to anchor each comment to document text, and without them the comment has no visible anchor and may be discarded:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { CommentRangeEnd, CommentRangeStart, CommentReference, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
comments: {
|
||||
children: [
|
||||
@@ -176,40 +198,86 @@ const doc = new Document({
|
||||
|
||||
Mark a comment thread as resolved using the `resolved` property. Setting `resolved: true` on any comment in a thread causes Word to display the entire thread as resolved. For clarity, set it on the root comment:
|
||||
|
||||
```ts
|
||||
comments: {
|
||||
children: [
|
||||
```ts live
|
||||
import { CommentRangeEnd, CommentRangeStart, CommentReference, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
comments: {
|
||||
children: [
|
||||
{
|
||||
id: 0,
|
||||
author: "Charlie",
|
||||
date: new Date("2024-01-15"),
|
||||
resolved: true, // Marks the entire thread as resolved
|
||||
children: [new Paragraph("This timeline needs updating.")],
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
author: "Diana",
|
||||
date: new Date("2024-01-16"),
|
||||
parentId: 0,
|
||||
children: [new Paragraph("Done - updated the dates.")],
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
id: 0,
|
||||
author: "Charlie",
|
||||
date: new Date("2024-01-15"),
|
||||
resolved: true, // Marks the entire thread as resolved
|
||||
children: [new Paragraph("This timeline needs updating.")],
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
author: "Diana",
|
||||
date: new Date("2024-01-16"),
|
||||
parentId: 0,
|
||||
children: [new Paragraph("Done - updated the dates.")],
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new CommentRangeStart(0),
|
||||
new CommentRangeStart(1),
|
||||
new TextRun("The project finishes in March."),
|
||||
new CommentRangeEnd(0),
|
||||
new TextRun({ children: [new CommentReference(0)] }),
|
||||
new CommentRangeEnd(1),
|
||||
new TextRun({ children: [new CommentReference(1)] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Rich Text Comments
|
||||
|
||||
Comments can contain formatted text:
|
||||
|
||||
```ts
|
||||
new Comment({
|
||||
id: 0,
|
||||
author: "Reviewer",
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun({ text: "Important: ", bold: true }), new TextRun("Please verify the figures in this section.")],
|
||||
}),
|
||||
new Paragraph("See page 12 of the source document."),
|
||||
```ts live
|
||||
import { CommentRangeEnd, CommentRangeStart, CommentReference, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
comments: {
|
||||
children: [
|
||||
{
|
||||
id: 0,
|
||||
author: "Reviewer",
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({ text: "Important: ", bold: true }),
|
||||
new TextRun("Please verify the figures in this section."),
|
||||
],
|
||||
}),
|
||||
new Paragraph("See page 12 of the source document."),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new CommentRangeStart(0),
|
||||
new TextRun("Sales grew by 12% this year."),
|
||||
new CommentRangeEnd(0),
|
||||
new CommentReference(0),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -218,20 +286,20 @@ new Comment({
|
||||
|
||||
Document with review comments:
|
||||
|
||||
```ts
|
||||
import { Comment, CommentRangeEnd, CommentRangeStart, CommentReference, Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { CommentRangeEnd, CommentRangeStart, CommentReference, Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const doc = new Document({
|
||||
comments: {
|
||||
children: [
|
||||
new Comment({
|
||||
{
|
||||
id: 0,
|
||||
author: "Editor",
|
||||
date: new Date(),
|
||||
children: [new Paragraph("Consider rephrasing this for clarity.")],
|
||||
}),
|
||||
new Comment({
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
author: "Fact Checker",
|
||||
date: new Date(),
|
||||
@@ -240,7 +308,7 @@ const doc = new Document({
|
||||
children: [new TextRun({ text: "Verified ", bold: true }), new TextRun("- Source: Annual Report 2023")],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
|
||||
@@ -10,30 +10,64 @@ More info: https://en.wikipedia.org/wiki/Twip
|
||||
|
||||
### Convert Inches to Twip
|
||||
|
||||
```ts
|
||||
import { convertInchesToTwip } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, convertInchesToTwip } from "docx";
|
||||
|
||||
convertInchesToTwip(1); // returns 1440
|
||||
convertInchesToTwip(0.5); // returns 720
|
||||
convertInchesToTwip(2); // returns 2880
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Indented 1 inch",
|
||||
indent: { left: convertInchesToTwip(1) }, // returns 1440
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Indented 0.5 inches",
|
||||
indent: { left: convertInchesToTwip(0.5) }, // returns 720
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Indented 2 inches",
|
||||
indent: { left: convertInchesToTwip(2) }, // returns 2880
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Convert Millimeters to Twip
|
||||
|
||||
```ts
|
||||
import { convertMillimetersToTwip } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, convertMillimetersToTwip } from "docx";
|
||||
|
||||
convertMillimetersToTwip(25.4); // returns 1440 (1 inch = 25.4mm)
|
||||
convertMillimetersToTwip(50); // returns 2834
|
||||
convertMillimetersToTwip(10); // returns 567
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Indented 25.4mm",
|
||||
indent: { left: convertMillimetersToTwip(25.4) }, // returns 1440 (1 inch = 25.4mm)
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Indented 50mm",
|
||||
indent: { left: convertMillimetersToTwip(50) }, // returns 2834
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Indented 10mm",
|
||||
indent: { left: convertMillimetersToTwip(10) }, // returns 567
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### Setting Page Margins
|
||||
|
||||
```ts
|
||||
import { Document, convertInchesToTwip } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, convertInchesToTwip } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
@@ -48,7 +82,7 @@ const doc = new Document({
|
||||
},
|
||||
},
|
||||
},
|
||||
children: [/* ... */],
|
||||
children: [new Paragraph("The margins are 1 inch, with 1.5 inches on the left for binding.")],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -56,8 +90,8 @@ const doc = new Document({
|
||||
|
||||
### Setting Page Size
|
||||
|
||||
```ts
|
||||
import { Document, convertMillimetersToTwip, PageOrientation } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, convertMillimetersToTwip, PageOrientation } from "docx";
|
||||
|
||||
// A4 paper size
|
||||
const doc = new Document({
|
||||
@@ -72,7 +106,7 @@ const doc = new Document({
|
||||
},
|
||||
},
|
||||
},
|
||||
children: [/* ... */],
|
||||
children: [new Paragraph("This page is A4.")],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -80,8 +114,8 @@ const doc = new Document({
|
||||
|
||||
### Column Spacing
|
||||
|
||||
```ts
|
||||
import { Document, convertMillimetersToTwip } from "docx";
|
||||
```ts live
|
||||
import { ColumnBreak, Document, Paragraph, TextRun, convertMillimetersToTwip } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
@@ -92,7 +126,15 @@ const doc = new Document({
|
||||
space: convertMillimetersToTwip(10), // 10mm between columns
|
||||
},
|
||||
},
|
||||
children: [/* ... */],
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("This text is in the first column."),
|
||||
new ColumnBreak(),
|
||||
new TextRun("This text is in the second column, 10mm away."),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -100,22 +142,30 @@ const doc = new Document({
|
||||
|
||||
### Table Cell Width
|
||||
|
||||
```ts
|
||||
import { Table, TableCell, TableRow, WidthType, convertInchesToTwip } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow, WidthType, convertInchesToTwip } from "docx";
|
||||
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new TableCell({
|
||||
width: {
|
||||
size: convertInchesToTwip(2), // 2 inch wide cell
|
||||
type: WidthType.DXA,
|
||||
},
|
||||
children: [new Paragraph("Cell content")],
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({
|
||||
width: {
|
||||
size: convertInchesToTwip(2), // 2 inch wide cell
|
||||
type: WidthType.DXA,
|
||||
},
|
||||
children: [new Paragraph("Cell content")],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -148,16 +198,39 @@ new Table({
|
||||
|
||||
For image positioning, OOXML uses EMUs (English Metric Units). One inch equals 914400 EMUs.
|
||||
|
||||
```ts
|
||||
// Image offset of 1 inch
|
||||
floating: {
|
||||
horizontalPosition: {
|
||||
offset: 914400, // 1 inch in EMUs
|
||||
},
|
||||
verticalPosition: {
|
||||
offset: 914400,
|
||||
},
|
||||
}
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "gif",
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
transformation: {
|
||||
width: 200,
|
||||
height: 200,
|
||||
},
|
||||
// Image offset of 1 inch
|
||||
floating: {
|
||||
horizontalPosition: {
|
||||
offset: 914400, // 1 inch in EMUs
|
||||
},
|
||||
verticalPosition: {
|
||||
offset: 914400,
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
?> Unlike twips, there are currently no built-in conversion functions for EMUs. You can calculate them manually: `inches * 914400` or `mm * 36000`.
|
||||
|
||||
+61
-24
@@ -4,8 +4,10 @@
|
||||
|
||||
To create a new document, it is very easy:
|
||||
|
||||
```ts
|
||||
const doc = new docx.Document({
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
@@ -18,14 +20,20 @@ const doc = new docx.Document({
|
||||
|
||||
You can add metadata properties to the Word document:
|
||||
|
||||
```ts
|
||||
const doc = new docx.Document({
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
creator: "Dolan Miu",
|
||||
description: "My extremely interesting document",
|
||||
title: "My Document",
|
||||
subject: "Report",
|
||||
keywords: "report, annual, finance",
|
||||
sections: [/* ... */],
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -112,21 +120,35 @@ These properties appear in Word's File > Info panel and in file properties.
|
||||
|
||||
Set the hex value in the document like so:
|
||||
|
||||
```ts
|
||||
const doc = new docx.Document({
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
background: {
|
||||
color: "C45911",
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Or use a color of the document's theme, lighter or darker if you like, so the page changes color with the theme. See [Themes](usage/themes.md#text-tables-and-borders-in-the-themes-colors):
|
||||
|
||||
```ts
|
||||
const doc = new docx.Document({
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
background: {
|
||||
color: { theme: "accent2", lighter: 80 },
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -136,8 +158,10 @@ const doc = new docx.Document({
|
||||
|
||||
Add custom metadata properties that appear in Word's document properties:
|
||||
|
||||
```ts
|
||||
const doc = new docx.Document({
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
customProperties: [
|
||||
{
|
||||
name: "Department",
|
||||
@@ -149,34 +173,40 @@ const doc = new docx.Document({
|
||||
},
|
||||
{
|
||||
name: "Approved",
|
||||
value: true,
|
||||
value: "true",
|
||||
},
|
||||
{
|
||||
name: "Version",
|
||||
value: 2.5,
|
||||
value: "2.5",
|
||||
},
|
||||
],
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
sections: [/* ... */],
|
||||
});
|
||||
```
|
||||
|
||||
Custom properties support these value types:
|
||||
|
||||
- `string` - Text values
|
||||
- `number` - Numeric values
|
||||
- `boolean` - True/false values
|
||||
Custom property values are text (`string`), so write numbers and true/false values as text, as above.
|
||||
|
||||
### Document Features
|
||||
|
||||
Enable special features like track changes or field updating:
|
||||
|
||||
```ts
|
||||
const doc = new docx.Document({
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
features: {
|
||||
trackRevisions: true, // Enable track changes
|
||||
updateFields: true, // Update fields (like TOC) when opened
|
||||
},
|
||||
sections: [/* ... */],
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -191,12 +221,19 @@ See [Lars Corneliussen's blog post](https://startbigthinksmall.wordpress.com/201
|
||||
|
||||
Compatibility Settings are optional settings used to preserve visual fidelity of documents created in earlier word processing applications. Some of these settings provide ability for specific behaviors, described in detail below; and others simply instruct applications to mimic the behavior of an existing word processing application.
|
||||
|
||||
```ts
|
||||
const doc = new docx.Document({
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
compatibility: {
|
||||
version: 15,
|
||||
doNotExpandShiftReturn: true,
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Endnotes allow you to add references that appear at the end of the document. The
|
||||
|
||||
## Example
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, EndnoteReferenceRun, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -83,4 +83,6 @@ Insert `EndnoteReferenceRun` in paragraphs to create reference markers:
|
||||
|
||||
## Demo
|
||||
|
||||
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/footnotes-and-endnotes/endnotes.ts ":include")
|
||||
|
||||
_Source: https://github.com/dolanmiu/docx/blob/master/demo/footnotes-and-endnotes/endnotes.ts_
|
||||
|
||||
+55
-5
@@ -21,25 +21,47 @@ Word uses field codes to identify what the result of the field should be. You ca
|
||||
|
||||
Fields can be added as a child of a paragraph:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, SimpleField, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("This document was created by: "), new SimpleField("AUTHOR")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Fields can contain a cached value that gives the word processor a text to show without having to calculate all fields. The cached value can be updated by selecting the field and pressing F9. A cached value can be passed in as the second argument to the constructor.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, SimpleField, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("This document was created by: "), new SimpleField("AUTHOR", "Richard Brodie")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Formulas
|
||||
|
||||
One type of field is the formula that can be used to do some basic calculations. This can be done with static values, e.g. `12 + 34`, but a value from a bookmark can also be used in a calculation. This can be seen in the following example:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Bookmark, Document, Paragraph, SimpleField, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [
|
||||
new TextRun("Value one is: "),
|
||||
@@ -50,6 +72,14 @@ const paragraph = new Paragraph({
|
||||
new SimpleField("=One+Two"),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Mail merge fields
|
||||
@@ -58,18 +88,38 @@ Fields are often used in a mail merge where a template document is created and d
|
||||
|
||||
A convenience class was added to add these mail merge fields to the document easily. You can add these to a paragraph like any other field and only have to supply the name of the field in your data set:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, SimpleMailMergeField, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("Your score was "), new SimpleMailMergeField("Score"), new TextRun(" of 100 points")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
This code is equivalent to:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, SimpleField, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("Your score was "), new SimpleField("MERGEFIELD Score", "«Score»"), new TextRun(" of 100 points")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Demo
|
||||
|
||||
+104
-36
@@ -6,16 +6,16 @@ Custom fonts allow you to embed fonts directly into your document, ensuring cons
|
||||
|
||||
Embed a font by providing the font data in the `Document` constructor:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { CharacterSet, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const fontData = fs.readFileSync("./fonts/MyCustomFont.ttf");
|
||||
const fontData = fs.readFileSync("./demo/assets/Pacifico.ttf");
|
||||
|
||||
const doc = new Document({
|
||||
fonts: [
|
||||
{
|
||||
name: "MyCustomFont",
|
||||
name: "Pacifico",
|
||||
data: fontData,
|
||||
characterSet: CharacterSet.ANSI,
|
||||
},
|
||||
@@ -27,7 +27,7 @@ const doc = new Document({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "This text uses a custom font",
|
||||
font: "MyCustomFont",
|
||||
font: "Pacifico",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
@@ -80,39 +80,80 @@ Available character sets:
|
||||
|
||||
### In TextRun
|
||||
|
||||
```ts
|
||||
new TextRun({
|
||||
text: "Custom font text",
|
||||
font: "MyCustomFont",
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { CharacterSet, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const fontData = fs.readFileSync("./demo/assets/Pacifico.ttf");
|
||||
|
||||
const doc = new Document({
|
||||
fonts: [{ name: "Pacifico", data: fontData, characterSet: CharacterSet.ANSI }],
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Custom font text",
|
||||
font: "Pacifico",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### In Paragraph Style
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
run: {
|
||||
font: "MyCustomFont",
|
||||
},
|
||||
children: [new TextRun("All text in this paragraph uses the custom font")],
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { CharacterSet, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const fontData = fs.readFileSync("./demo/assets/Pacifico.ttf");
|
||||
|
||||
const doc = new Document({
|
||||
fonts: [{ name: "Pacifico", data: fontData, characterSet: CharacterSet.ANSI }],
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
run: {
|
||||
font: "Pacifico",
|
||||
},
|
||||
children: [new TextRun("All text in this paragraph uses the custom font")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### In Document Styles
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { CharacterSet, Document, Paragraph } from "docx";
|
||||
|
||||
const fontData = fs.readFileSync("./demo/assets/Pacifico.ttf");
|
||||
|
||||
const doc = new Document({
|
||||
fonts: [{ name: "CustomFont", data: fontData, characterSet: CharacterSet.ANSI }],
|
||||
fonts: [{ name: "Pacifico", data: fontData, characterSet: CharacterSet.ANSI }],
|
||||
styles: {
|
||||
default: {
|
||||
document: {
|
||||
run: {
|
||||
font: "CustomFont",
|
||||
font: "Pacifico",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
sections: [/* ... */],
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("All text in the document uses the custom font")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -120,10 +161,15 @@ const doc = new Document({
|
||||
|
||||
A font can also be one of the fonts of the document's [theme](usage/themes.md), so text in it changes font when the theme's fonts change:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { CharacterSet, Document, Paragraph } from "docx";
|
||||
|
||||
const fontData = fs.readFileSync("./demo/assets/Pacifico.ttf");
|
||||
|
||||
const doc = new Document({
|
||||
fonts: [{ name: "CustomFont", data: fontData, characterSet: CharacterSet.ANSI }],
|
||||
theme: { fonts: { body: "CustomFont" } },
|
||||
fonts: [{ name: "Pacifico", data: fontData, characterSet: CharacterSet.ANSI }],
|
||||
theme: { fonts: { body: "Pacifico" } },
|
||||
styles: {
|
||||
default: {
|
||||
document: {
|
||||
@@ -133,7 +179,11 @@ const doc = new Document({
|
||||
},
|
||||
},
|
||||
},
|
||||
sections: [/* ... */],
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("All text in the document uses the theme's font for body text")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -141,17 +191,21 @@ const doc = new Document({
|
||||
|
||||
Embed multiple fonts:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { CharacterSet, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
fonts: [
|
||||
{
|
||||
name: "HeadingFont",
|
||||
data: fs.readFileSync("./fonts/Heading.ttf"),
|
||||
// The demo folder has one font, so both are Pacifico here: give each its own font file
|
||||
data: fs.readFileSync("./demo/assets/Pacifico.ttf"),
|
||||
characterSet: CharacterSet.ANSI,
|
||||
},
|
||||
{
|
||||
name: "BodyFont",
|
||||
data: fs.readFileSync("./fonts/Body.ttf"),
|
||||
data: fs.readFileSync("./demo/assets/Pacifico.ttf"),
|
||||
characterSet: CharacterSet.ANSI,
|
||||
},
|
||||
],
|
||||
@@ -185,17 +239,31 @@ const doc = new Document({
|
||||
|
||||
You can mix embedded fonts with system fonts:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "System font (Arial), ",
|
||||
font: "Arial",
|
||||
}),
|
||||
new TextRun({
|
||||
text: "Custom embedded font",
|
||||
font: "MyCustomFont",
|
||||
}),
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { CharacterSet, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const fontData = fs.readFileSync("./demo/assets/Pacifico.ttf");
|
||||
|
||||
const doc = new Document({
|
||||
fonts: [{ name: "Pacifico", data: fontData, characterSet: CharacterSet.ANSI }],
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "System font (Arial), ",
|
||||
font: "Arial",
|
||||
}),
|
||||
new TextRun({
|
||||
text: "Custom embedded font",
|
||||
font: "Pacifico",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -8,7 +8,7 @@ Footnotes allow you to add references that appear at the bottom of each page. Th
|
||||
|
||||
## Example
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, FootnoteReferenceRun, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -59,8 +59,8 @@ Insert `FootnoteReferenceRun` in paragraphs to create reference markers:
|
||||
|
||||
Footnotes can contain images using `ImageRun`:
|
||||
|
||||
```ts
|
||||
import { Document, FootnoteReferenceRun, ImageRun, Packer, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { Document, FootnoteReferenceRun, ImageRun, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -71,10 +71,10 @@ const doc = new Document({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "jpg",
|
||||
data: fs.readFileSync("./image.jpg"),
|
||||
data: fs.readFileSync("./demo/assets/images/cat.jpg"),
|
||||
transformation: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
height: 67,
|
||||
},
|
||||
}),
|
||||
new TextRun("Caption for the image"),
|
||||
@@ -99,8 +99,8 @@ const doc = new Document({
|
||||
|
||||
Footnotes support numbered and bulleted lists:
|
||||
|
||||
```ts
|
||||
import { AlignmentType, convertInchesToTwip, Document, FootnoteReferenceRun, LevelFormat, Packer, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { AlignmentType, convertInchesToTwip, Document, FootnoteReferenceRun, LevelFormat, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
numbering: {
|
||||
|
||||
@@ -6,7 +6,7 @@ Every section has headers and footers that appear on each page within that secti
|
||||
|
||||
## Basic Headers and Footers
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Footer, Header, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -40,7 +40,9 @@ const doc = new Document({
|
||||
|
||||
To have a different header/footer on the first page:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Footer, Header, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -63,7 +65,13 @@ const doc = new Document({
|
||||
children: [], // No footer on first page
|
||||
}),
|
||||
},
|
||||
children: [/* ... */],
|
||||
children: [
|
||||
new Paragraph("First page"),
|
||||
new Paragraph({
|
||||
text: "Second page",
|
||||
pageBreakBefore: true,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -73,7 +81,9 @@ const doc = new Document({
|
||||
|
||||
For documents like books with different left/right pages:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, Document, Header, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
evenAndOddHeaderAndFooters: true, // Enable at document level
|
||||
sections: [
|
||||
@@ -96,7 +106,11 @@ const doc = new Document({
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [/* ... */],
|
||||
children: [
|
||||
new Paragraph("Page 1"),
|
||||
new Paragraph({ text: "Page 2", pageBreakBefore: true }),
|
||||
new Paragraph({ text: "Page 3", pageBreakBefore: true }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -106,8 +120,8 @@ const doc = new Document({
|
||||
|
||||
Add page numbers using the `PageNumber` class:
|
||||
|
||||
```ts
|
||||
import { AlignmentType, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { AlignmentType, Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
const footer = new Footer({
|
||||
children: [
|
||||
@@ -126,32 +140,65 @@ const footer = new Footer({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: {
|
||||
default: footer,
|
||||
},
|
||||
children: [new Paragraph("First page"), new Paragraph({ text: "Second page", pageBreakBefore: true })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Common Page Number Patterns
|
||||
|
||||
**Centered page number:**
|
||||
|
||||
```ts
|
||||
new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
alignment: AlignmentType.CENTER,
|
||||
children: [new TextRun({ children: [PageNumber.CURRENT] })],
|
||||
}),
|
||||
```ts live
|
||||
import { AlignmentType, Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
alignment: AlignmentType.CENTER,
|
||||
children: [new TextRun({ children: [PageNumber.CURRENT] })],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
**Right-aligned page number:**
|
||||
|
||||
```ts
|
||||
new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
alignment: AlignmentType.RIGHT,
|
||||
children: [new TextRun("Page "), new TextRun({ children: [PageNumber.CURRENT] })],
|
||||
}),
|
||||
```ts live
|
||||
import { AlignmentType, Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
alignment: AlignmentType.RIGHT,
|
||||
children: [new TextRun("Page "), new TextRun({ children: [PageNumber.CURRENT] })],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -160,8 +207,8 @@ new Footer({
|
||||
|
||||
Headers and footers can contain numbered or bulleted lists:
|
||||
|
||||
```ts
|
||||
import { AlignmentType, convertInchesToTwip, Document, Footer, LevelFormat, Packer, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { AlignmentType, convertInchesToTwip, Document, Footer, LevelFormat, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
numbering: {
|
||||
@@ -210,8 +257,9 @@ const doc = new Document({
|
||||
|
||||
Add logos or images:
|
||||
|
||||
```ts
|
||||
import { Header, ImageRun, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Header, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const header = new Header({
|
||||
children: [
|
||||
@@ -219,24 +267,35 @@ const header = new Header({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./logo.png"),
|
||||
data: fs.readFileSync("./demo/assets/images/linux-png.png"),
|
||||
transformation: {
|
||||
width: 100,
|
||||
height: 50,
|
||||
width: 50,
|
||||
height: 60,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: header,
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Watermarks
|
||||
|
||||
Watermarks are placed in headers so that they repeat on every page:
|
||||
|
||||
```ts
|
||||
import { Header, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
import { TextWatermark } from "docx/watermarks";
|
||||
|
||||
const header = new Header({
|
||||
@@ -246,6 +305,17 @@ const header = new Header({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: header,
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
See [Watermarks](usage/watermarks.md) for text and image watermark options.
|
||||
@@ -254,37 +324,52 @@ See [Watermarks](usage/watermarks.md) for text and image watermark options.
|
||||
|
||||
Control the distance from the edge of the page:
|
||||
|
||||
```ts
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
page: {
|
||||
margin: {
|
||||
header: 720, // Distance from top edge to header (in twips)
|
||||
footer: 720, // Distance from bottom edge to footer
|
||||
```ts live
|
||||
import { Document, Footer, Header, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
page: {
|
||||
margin: {
|
||||
header: 720, // Distance from top edge to header (in twips)
|
||||
footer: 720, // Distance from bottom edge to footer
|
||||
},
|
||||
},
|
||||
},
|
||||
headers: {
|
||||
default: new Header({
|
||||
children: [new Paragraph("Header text")],
|
||||
}),
|
||||
},
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [new Paragraph("Footer text")],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
headers: {/* ... */},
|
||||
footers: {/* ... */},
|
||||
children: [/* ... */],
|
||||
},
|
||||
];
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Multiple Elements in Headers/Footers
|
||||
|
||||
Headers and footers can contain multiple paragraphs, tables, and images:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, Document, Header, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const header = new Header({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./logo.png"),
|
||||
transformation: { width: 80, height: 40 },
|
||||
data: fs.readFileSync("./demo/assets/images/linux-png.png"),
|
||||
transformation: { width: 40, height: 48 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
@@ -298,14 +383,25 @@ const header = new Header({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: header,
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Using Tables for Layout
|
||||
|
||||
Create complex header layouts with tables:
|
||||
|
||||
```ts
|
||||
import { AlignmentType, BorderStyle, Header, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
|
||||
```ts live
|
||||
import { AlignmentType, BorderStyle, Document, Header, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
|
||||
|
||||
// Helper to create invisible borders for layout tables
|
||||
const noBorders = {
|
||||
@@ -350,13 +446,26 @@ const header = new Header({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: header,
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Multiple Sections with Different Headers
|
||||
|
||||
Each section can have its own headers and footers:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -383,7 +492,7 @@ const doc = new Document({
|
||||
|
||||
Professional document with company header:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, Document, Footer, Header, ImageRun, PageNumber, Packer, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
@@ -401,8 +510,8 @@ const doc = new Document({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./logo.png"),
|
||||
transformation: { width: 150, height: 75 },
|
||||
data: fs.readFileSync("./demo/assets/images/linux-png.png"),
|
||||
transformation: { width: 75, height: 90 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
@@ -434,7 +543,7 @@ const doc = new Document({
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content...")],
|
||||
children: [new Paragraph("Cover page"), new Paragraph({ text: "Document content...", pageBreakBefore: true })],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -10,7 +10,9 @@ To create an internal hyperlink you need first to create a `Bookmark`, which con
|
||||
|
||||
A bookmark is composed of an anchor (an identifier) and the text displayed. After creating a bookmark just add it to a paragraph. For example, creating a bookmarked heading:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Bookmark, Document, HeadingLevel, Paragraph, TextRun } from "docx";
|
||||
|
||||
const chapter1 = new Paragraph({
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
children: [
|
||||
@@ -20,11 +22,21 @@ const chapter1 = new Paragraph({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [chapter1],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Then you can create an hyperlink pointing to that bookmark with an `InternalHyperLink`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Bookmark, Document, HeadingLevel, InternalHyperlink, Paragraph, TextRun } from "docx";
|
||||
|
||||
const link = new InternalHyperlink({
|
||||
children: [
|
||||
new TextRun({
|
||||
@@ -34,26 +46,86 @@ const link = new InternalHyperlink({
|
||||
],
|
||||
anchor: "anchorForChapter1",
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({ children: [link] }),
|
||||
new Paragraph({
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
pageBreakBefore: true,
|
||||
children: [new Bookmark({ id: "anchorForChapter1", children: [new TextRun("Chapter 1")] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Page reference
|
||||
|
||||
You can also get the page number of the bookmark by creating a page reference to it:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Bookmark, Document, HeadingLevel, PageReference, Paragraph, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("Chapter 1 can be seen on page "), new PageReference("anchorForChapter1")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
paragraph,
|
||||
new Paragraph({
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
pageBreakBefore: true,
|
||||
children: [new Bookmark({ id: "anchorForChapter1", children: [new TextRun("Chapter 1")] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Numbered item reference
|
||||
|
||||
You can also create cross references for numbered items with `NumberedItemReference`.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, Bookmark, Document, LevelFormat, NumberedItemReference, Paragraph, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("See Paragraph "), new NumberedItemReference("anchorForParagraph1", "1.1")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
numbering: {
|
||||
config: [
|
||||
{
|
||||
reference: "paragraph-numbering",
|
||||
levels: [
|
||||
{ level: 0, format: LevelFormat.DECIMAL, text: "%1.", alignment: AlignmentType.START },
|
||||
{ level: 1, format: LevelFormat.DECIMAL, text: "%1.%2.", alignment: AlignmentType.START },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
paragraph,
|
||||
new Paragraph({ text: "Introduction", numbering: { reference: "paragraph-numbering", level: 0 } }),
|
||||
new Paragraph({
|
||||
numbering: { reference: "paragraph-numbering", level: 1 },
|
||||
children: [new Bookmark({ id: "anchorForParagraph1", children: [new TextRun("The paragraph being referenced")] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
@@ -63,7 +135,9 @@ const paragraph = new Paragraph({
|
||||
|
||||
To create an external hyperlink you just need to specify the url and the text of the link, then add it to a paragraph:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ExternalHyperlink, Paragraph, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [
|
||||
new ExternalHyperlink({
|
||||
@@ -77,6 +151,14 @@ const paragraph = new Paragraph({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Related Topics
|
||||
@@ -95,7 +177,9 @@ It is possible to set the style of the text of both internal and external hyperl
|
||||
|
||||
Example:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ExternalHyperlink, Paragraph, TextRun } from "docx";
|
||||
|
||||
const styledLink = new ExternalHyperlink({
|
||||
children: [
|
||||
new TextRun({
|
||||
@@ -114,4 +198,12 @@ const styledLink = new ExternalHyperlink({
|
||||
],
|
||||
link: "https://docx.js.org",
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph({ children: [styledLink] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
+226
-67
@@ -35,14 +35,17 @@
|
||||
|
||||
To create a `floating` image on top of text:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: 'gif',
|
||||
type: "gif",
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
transformation: {
|
||||
width: 200,
|
||||
height: 200,
|
||||
}
|
||||
},
|
||||
floating: {
|
||||
horizontalPosition: {
|
||||
offset: 1014400,
|
||||
@@ -52,11 +55,26 @@ const image = new ImageRun({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [image, new TextRun("The image floats on top of this text, instead of making room for it in the line.")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
By default with no arguments, its an `inline` image:
|
||||
By default with no arguments, its an `inline` image. Add it into the document by adding the image into a paragraph:
|
||||
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
```ts
|
||||
const image = new ImageRun({
|
||||
type: "gif",
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
@@ -65,19 +83,17 @@ const image = new ImageRun({
|
||||
height: 100,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Add it into the document by adding the image into a paragraph:
|
||||
|
||||
```ts
|
||||
const doc = new Document({
|
||||
sections: [{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [image],
|
||||
}),
|
||||
],
|
||||
}];
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [image],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -85,24 +101,29 @@ const doc = new Document({
|
||||
|
||||
Adding images can be easily done by creating an instance of `ImageRun`. This can be added in a `Paragraph` or `Hyperlink`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: [IMAGE_TYPE],
|
||||
data: [IMAGE_BUFFER],
|
||||
transformation: {
|
||||
width: [IMAGE_SIZE],
|
||||
height: [IMAGE_SIZE],
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}];
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./demo/assets/images/dog.png"),
|
||||
transformation: {
|
||||
width: 166,
|
||||
height: 150,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -114,7 +135,7 @@ const doc = new Document({
|
||||
|
||||

|
||||
|
||||
Three types of image positioning is supported:
|
||||
Two types of image positioning are supported:
|
||||
|
||||
- Floating
|
||||
- Inline
|
||||
@@ -123,19 +144,22 @@ By default, images are exported as `Inline` elements.
|
||||
|
||||
### Usage
|
||||
|
||||
Pass `options` into the `[POSITION_OPTIONS]` mentioned in the [Intro above](#Intro).
|
||||
To float an image, give the `ImageRun` a `floating` option, as the examples below do.
|
||||
|
||||
## Floating
|
||||
|
||||
To change the position the image to be on top of the text, simply add the `floating` property to the last argument. By default, the offsets are relative to the top left corner of the `page`. Offset units are in [emus](https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/):
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: "png",
|
||||
data: buffer,
|
||||
data: fs.readFileSync("./demo/assets/images/linux-png.png"),
|
||||
transformation: {
|
||||
width: 903,
|
||||
height: 1149,
|
||||
width: 200,
|
||||
height: 240,
|
||||
},
|
||||
floating: {
|
||||
horizontalPosition: {
|
||||
@@ -146,27 +170,57 @@ const image = new ImageRun({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
image,
|
||||
new TextRun("The image is placed 1014400 EMUs from the top left corner of the page, on top of this text."),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, HorizontalPositionRelativeFrom, ImageRun, Paragraph, TextRun, VerticalPositionRelativeFrom } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: "png",
|
||||
data: buffer,
|
||||
data: fs.readFileSync("./demo/assets/images/linux-png.png"),
|
||||
transformation: {
|
||||
width: 903,
|
||||
height: 1149,
|
||||
width: 60,
|
||||
height: 72,
|
||||
},
|
||||
floating: {
|
||||
horizontalPosition: {
|
||||
relative: HorizontalPositionRelativeFrom.RIGHT_MARGIN,
|
||||
offset: 1014400,
|
||||
offset: 182880,
|
||||
},
|
||||
verticalPosition: {
|
||||
relative: VerticalPositionRelativeFrom.BOTTOM_MARGIN,
|
||||
offset: 1014400,
|
||||
offset: 182880,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [image, new TextRun("The image is placed in the bottom right corner, in the right and bottom margins.")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Options
|
||||
@@ -214,7 +268,10 @@ wrap: {
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph, TextRun, TextWrappingSide, TextWrappingType } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: "gif",
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
@@ -235,6 +292,18 @@ const image = new ImageRun({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [image, new TextRun("This text wraps around both sides of the image. ".repeat(40))],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Wrap options have the following properties are:
|
||||
@@ -263,7 +332,10 @@ margins: {
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph, TextRun, TextWrappingSide, TextWrappingType } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: "gif",
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
@@ -288,19 +360,46 @@ const image = new ImageRun({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [image, new TextRun("The margins keep this text further from the top and bottom of the image. ".repeat(40))],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Run Formatting
|
||||
|
||||
Use `run` to format the run the image is in, with the same options as a `TextRun`'s formatting. `position` raises or lowers an inline image from the text's baseline, by a signed length such as `"2pt"` or `"-2pt"`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph, TextRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: "gif",
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
transformation: { width: 100, height: 100 },
|
||||
run: { position: "-2pt" },
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun("Text before "), image, new TextRun(" text after")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
To place an image at page coordinates or control text wrapping, use [`floating`](#floating) instead.
|
||||
@@ -309,16 +408,28 @@ To place an image at page coordinates or control text wrapping, use [`floating`]
|
||||
|
||||
Specifies common non-visual DrawingML properties. A name, title and description for a picture can be specified.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: "gif",
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
transformation: { width: 100, height: 100 },
|
||||
altText: {
|
||||
title: "This is an ultimate title",
|
||||
description: "This is an ultimate image",
|
||||
name: "My Ultimate Image",
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph({ children: [image] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Options
|
||||
@@ -333,27 +444,49 @@ const image = new ImageRun({
|
||||
|
||||
Give an image a `link` to open a web page when it is clicked (with Ctrl in Word), the same as Word's **Insert > Link** on a picture:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./logo.png"),
|
||||
transformation: { width: 120, height: 40 },
|
||||
data: fs.readFileSync("./demo/assets/images/linux-png.png"),
|
||||
transformation: { width: 100, height: 120 },
|
||||
altText: { name: "Logo", description: "Company logo", title: "Logo" },
|
||||
link: "https://example.com",
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph({ children: [image] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
An image inside an `ExternalHyperlink` links to the hyperlink's address already. If it has a `link` of its own, its own link is used.
|
||||
|
||||
Mark an image as `decorative` when it carries no information, such as a border or a flourish, so screen readers skip it. It is the same as Word's **Mark as decorative**, and is used instead of alternative text:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const flourish = new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./flourish.png"),
|
||||
transformation: { width: 300, height: 20 },
|
||||
type: "jpg",
|
||||
data: fs.readFileSync("./demo/assets/images/cat.jpg"),
|
||||
transformation: { width: 300, height: 200 },
|
||||
decorative: true,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph({ children: [flourish] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Both work for inline and floating images.
|
||||
@@ -369,7 +502,10 @@ Both work for inline and floating images.
|
||||
|
||||
Crop an image by trimming a percentage off each edge before it's stretched to fill its frame. Pass a `crop` property to `ImageRun` with `left`, `top`, `right` and/or `bottom` percentages (`0` to `100`):
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const image = new ImageRun({
|
||||
type: "gif",
|
||||
data: fs.readFileSync("./demo/assets/images/pizza.gif"),
|
||||
@@ -384,6 +520,14 @@ const image = new ImageRun({
|
||||
bottom: 5,
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph({ children: [image] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Options
|
||||
@@ -399,16 +543,31 @@ const image = new ImageRun({
|
||||
|
||||
Images can be marked as inserted or deleted revisions for change tracking. Pass an `insertion` or `deletion` property to `ImageRun`, or both for an image that was inserted and then deleted, such as by another author:
|
||||
|
||||
```ts
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./image.png"),
|
||||
transformation: { width: 120, height: 120 },
|
||||
insertion: {
|
||||
id: 30,
|
||||
author: "Firstname Lastname",
|
||||
date: "2020-10-06T09:00:00Z",
|
||||
},
|
||||
```ts live
|
||||
import { Document, ImageRun, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./demo/assets/images/dog.png"),
|
||||
transformation: { width: 120, height: 120 },
|
||||
insertion: {
|
||||
id: 30,
|
||||
author: "Firstname Lastname",
|
||||
date: "2020-10-06T09:00:00Z",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+96
-39
@@ -8,7 +8,7 @@ Line numbers are useful for legal documents, code listings, scripts, and any doc
|
||||
|
||||
Add line numbers to a section:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, LineNumberRestartFormat, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -39,60 +39,117 @@ const doc = new Document({
|
||||
|
||||
Control when line numbers restart:
|
||||
|
||||
```ts
|
||||
import { LineNumberRestartFormat } from "docx";
|
||||
```ts live
|
||||
import { Document, LineNumberRestartFormat, Paragraph } from "docx";
|
||||
|
||||
// Continuous - numbers continue throughout document
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
restart: LineNumberRestartFormat.CONTINUOUS,
|
||||
}
|
||||
|
||||
// Restart each page
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
restart: LineNumberRestartFormat.NEW_PAGE,
|
||||
}
|
||||
|
||||
// Restart each section
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
restart: LineNumberRestartFormat.NEW_SECTION,
|
||||
}
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
// Continuous - numbers continue throughout document
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
restart: LineNumberRestartFormat.CONTINUOUS,
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("Numbered continuously"), new Paragraph("Numbered continuously")],
|
||||
},
|
||||
{
|
||||
properties: {
|
||||
// Restart each page
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
restart: LineNumberRestartFormat.NEW_PAGE,
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("Numbered from the top of each page"), new Paragraph("Numbered from the top of each page")],
|
||||
},
|
||||
{
|
||||
properties: {
|
||||
// Restart each section
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
restart: LineNumberRestartFormat.NEW_SECTION,
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("Numbered from the start of the section"), new Paragraph("Numbered from the start of the section")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Count Interval
|
||||
|
||||
Show line numbers at specific intervals:
|
||||
|
||||
```ts
|
||||
// Show every 5th line number (5, 10, 15...)
|
||||
lineNumbers: {
|
||||
countBy: 5,
|
||||
restart: LineNumberRestartFormat.CONTINUOUS,
|
||||
}
|
||||
```ts live
|
||||
import { Document, LineNumberRestartFormat, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
// Show every 5th line number (5, 10, 15...)
|
||||
lineNumbers: {
|
||||
countBy: 5,
|
||||
restart: LineNumberRestartFormat.CONTINUOUS,
|
||||
},
|
||||
},
|
||||
children: Array.from({ length: 15 }, (_, index) => new Paragraph(`Line ${index + 1}`)),
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Starting Number
|
||||
|
||||
Start from a specific line number:
|
||||
|
||||
```ts
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
start: 100, // First line is 100
|
||||
restart: LineNumberRestartFormat.CONTINUOUS,
|
||||
}
|
||||
```ts live
|
||||
import { Document, LineNumberRestartFormat, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
start: 100, // First line is 100
|
||||
restart: LineNumberRestartFormat.CONTINUOUS,
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("The first line"), new Paragraph("The second line"), new Paragraph("The third line")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Suppressing Line Numbers
|
||||
|
||||
Suppress line numbers for specific paragraphs:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
text: "This paragraph will not have a line number",
|
||||
suppressLineNumbers: true,
|
||||
```ts live
|
||||
import { Document, LineNumberRestartFormat, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
lineNumbers: {
|
||||
countBy: 1,
|
||||
restart: LineNumberRestartFormat.CONTINUOUS,
|
||||
},
|
||||
},
|
||||
children: [
|
||||
new Paragraph("This paragraph has a line number"),
|
||||
new Paragraph({
|
||||
text: "This paragraph will not have a line number",
|
||||
suppressLineNumbers: true,
|
||||
}),
|
||||
new Paragraph("This paragraph has a line number too"),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -102,8 +159,8 @@ This is useful for headings, titles, or any content that shouldn't be numbered.
|
||||
|
||||
Legal document with line numbers:
|
||||
|
||||
```ts
|
||||
import { Document, HeadingLevel, LineNumberRestartFormat, Packer, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, HeadingLevel, LineNumberRestartFormat, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
@@ -139,7 +196,7 @@ const doc = new Document({
|
||||
|
||||
## Multiple Sections with Different Settings
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, LineNumberRestartFormat, Paragraph, SectionType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
|
||||
+706
-192
File diff suppressed because it is too large
Load Diff
+117
-65
@@ -53,11 +53,12 @@ Levels define the numbering definition itself, what it looks like, the indention
|
||||
|
||||
## Using ordered lists in `docx`
|
||||
|
||||
Add a `numbering` section to the `Document` to numbering style, define your levels. Use `LevelFormat.UPPER_ROMAN` for the `format` in `levels`:
|
||||
Add a `numbering` section to the `Document` to numbering style, define your levels. Use `LevelFormat.UPPER_ROMAN` for the `format` in `levels`. And then on a `Paragraph`, we can use the numbering created:
|
||||
|
||||
```ts live
|
||||
import { AlignmentType, Document, LevelFormat, Paragraph } from "docx";
|
||||
|
||||
```ts
|
||||
const doc = new Document({
|
||||
...
|
||||
numbering: {
|
||||
config: [
|
||||
{
|
||||
@@ -74,27 +75,33 @@ const doc = new Document({
|
||||
},
|
||||
},
|
||||
},
|
||||
...
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
...
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Hey you!",
|
||||
numbering: {
|
||||
reference: "my-numbering",
|
||||
level: 0,
|
||||
},
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Hey you again!",
|
||||
numbering: {
|
||||
reference: "my-numbering",
|
||||
level: 0,
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
And then on a `Paragraph`, we can add use the numbering created:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
text: "Hey you!",
|
||||
numbering: {
|
||||
reference: "my-numbering",
|
||||
level: 0,
|
||||
},
|
||||
}),
|
||||
```
|
||||
|
||||
### Numbering options
|
||||
|
||||
Along with `reference` and `level`, the `numbering` object supports an optional `instance` property:
|
||||
@@ -107,30 +114,59 @@ Along with `reference` and `level`, the `numbering` object supports an optional
|
||||
|
||||
Example:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
text: "First list item",
|
||||
numbering: { reference: "my-numbering", level: 0, instance: 1 },
|
||||
});
|
||||
```ts live
|
||||
import { AlignmentType, Document, LevelFormat, Paragraph } from "docx";
|
||||
|
||||
new Paragraph({
|
||||
text: "Second list item",
|
||||
numbering: { reference: "my-numbering", level: 0, instance: 1 },
|
||||
});
|
||||
|
||||
new Paragraph({
|
||||
text: "New list, starts again at 1",
|
||||
numbering: { reference: "my-numbering", level: 0, instance: 2 },
|
||||
const doc = new Document({
|
||||
numbering: {
|
||||
config: [
|
||||
{
|
||||
reference: "my-numbering",
|
||||
levels: [
|
||||
{
|
||||
level: 0,
|
||||
format: LevelFormat.DECIMAL,
|
||||
text: "%1.",
|
||||
alignment: AlignmentType.START,
|
||||
style: {
|
||||
paragraph: {
|
||||
indent: { left: 720, hanging: 260 },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "First list item",
|
||||
numbering: { reference: "my-numbering", level: 0, instance: 1 },
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Second list item",
|
||||
numbering: { reference: "my-numbering", level: 0, instance: 1 },
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "New list, starts again at 1",
|
||||
numbering: { reference: "my-numbering", level: 0, instance: 2 },
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Un-ordered lists / Bullet points
|
||||
|
||||
Add a `numbering` section to the `Document` to numbering style, define your levels. Use `LevelFormat.BULLET` for the `format` in `levels`:
|
||||
Add a `numbering` section to the `Document` to numbering style, define your levels. Use `LevelFormat.BULLET` for the `format` in `levels`. And then on a `Paragraph`, we can use the numbering created:
|
||||
|
||||
```ts live
|
||||
import { AlignmentType, convertInchesToTwip, Document, LevelFormat, Paragraph } from "docx";
|
||||
|
||||
```ts
|
||||
const doc = new Document({
|
||||
...
|
||||
numbering: {
|
||||
config: [
|
||||
{
|
||||
@@ -139,7 +175,7 @@ const doc = new Document({
|
||||
{
|
||||
level: 0,
|
||||
format: LevelFormat.BULLET,
|
||||
text: "\u1F60",
|
||||
text: "\u2022",
|
||||
alignment: AlignmentType.LEFT,
|
||||
style: {
|
||||
paragraph: {
|
||||
@@ -151,29 +187,37 @@ const doc = new Document({
|
||||
},
|
||||
],
|
||||
},
|
||||
...
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Hey you!",
|
||||
numbering: {
|
||||
reference: "my-bullet-points",
|
||||
level: 0,
|
||||
},
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "Hey you again!",
|
||||
numbering: {
|
||||
reference: "my-bullet-points",
|
||||
level: 0,
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
And then on a `Paragraph`, we can add use the numbering created:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
text: "Hey you!",
|
||||
numbering: {
|
||||
reference: "my-bullet-points",
|
||||
level: 0,
|
||||
},
|
||||
}),
|
||||
```
|
||||
|
||||
## Disabling numbering inherited from paragraph style
|
||||
|
||||
If the numbering is set on a paragraph style, you may wish to disable it for a specific paragraph:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, convertInchesToTwip, Document, LevelFormat, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
...
|
||||
numbering: {
|
||||
config: [
|
||||
{
|
||||
@@ -182,7 +226,7 @@ const doc = new Document({
|
||||
{
|
||||
level: 0,
|
||||
format: LevelFormat.BULLET,
|
||||
text: "\u1F60",
|
||||
text: "\u2022",
|
||||
alignment: AlignmentType.LEFT,
|
||||
style: {
|
||||
paragraph: {
|
||||
@@ -197,39 +241,47 @@ const doc = new Document({
|
||||
styles: {
|
||||
paragraphStyles: [
|
||||
{
|
||||
id: 'bullet',
|
||||
name: 'Bullet',
|
||||
basedOn: 'Normal',
|
||||
next: 'Normal',
|
||||
id: "bullet",
|
||||
name: "Bullet",
|
||||
basedOn: "Normal",
|
||||
next: "Normal",
|
||||
run: {},
|
||||
paragraph: {
|
||||
numbering: {
|
||||
reference: 'my-bullet-points',
|
||||
reference: "my-bullet-points",
|
||||
level: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
...
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "A bullet point from the style",
|
||||
style: "bullet",
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "No bullet points!",
|
||||
style: "bullet",
|
||||
numbering: false,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
text: "No bullet points!",
|
||||
style: "Bullet",
|
||||
numbering: false,
|
||||
}),
|
||||
```
|
||||
|
||||
## Associating a level with a paragraph style
|
||||
|
||||
You can link a numbering level to a paragraph style using `style.style`. Any paragraph that uses the associated style will automatically adopt the numbering level without needing to specify `numbering` on each paragraph individually.
|
||||
|
||||
This is useful for creating reusable list styles — define the numbering once and apply it via the paragraph style:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, Document, LevelFormat, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
styles: {
|
||||
paragraphStyles: [
|
||||
|
||||
+68
-8
@@ -8,7 +8,18 @@ Packers works in both a node and browser environment (Angular etc). Now, the pac
|
||||
|
||||
This will return a NodeJS `Buffer`. If this is used in the browser, it will return a `UInt8Array` instead.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Packer.toBuffer(doc).then((buffer) => {
|
||||
fs.writeFileSync("My Document.docx", buffer);
|
||||
});
|
||||
@@ -16,7 +27,17 @@ Packer.toBuffer(doc).then((buffer) => {
|
||||
|
||||
### Export as string
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Packer.toString(doc).then((string) => {
|
||||
console.log(string);
|
||||
});
|
||||
@@ -24,7 +45,17 @@ Packer.toString(doc).then((string) => {
|
||||
|
||||
### Export as a `base64` string
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Packer.toBase64String(doc).then((string) => {
|
||||
console.log(string);
|
||||
});
|
||||
@@ -53,10 +84,19 @@ Packer.toArrayBuffer(doc).then((arrayBuffer) => {
|
||||
|
||||
### Export as a Stream
|
||||
|
||||
```ts
|
||||
Packer.toStream(doc).then((stream) => {
|
||||
// read from stream
|
||||
```ts live
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const stream = Packer.toStream(doc);
|
||||
// read from stream
|
||||
```
|
||||
|
||||
### Export using optional arguments
|
||||
@@ -67,7 +107,17 @@ The first is for controlling the indentation of the xml and should be a `boolean
|
||||
|
||||
The second is an array of subfile overrides (`{path: string, data: string}[]`). These overrides can be used to write additional subfiles to the result or even override default subfiles in the case that the default handling of these subfiles does not meet your needs.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const overrides = [{ path: "word/commentsExtended.xml", data: "string_data" }];
|
||||
Packer.toString(doc, true, overrides).then((string) => {
|
||||
console.log(string);
|
||||
@@ -78,7 +128,17 @@ Packer.toString(doc, true, overrides).then((string) => {
|
||||
|
||||
You can also use the lower-level `Packer.pack` method to export to any specified type.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Packer, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Packer.pack(doc, "string").then((string) => {
|
||||
console.log(string);
|
||||
});
|
||||
|
||||
+38
-23
@@ -8,8 +8,8 @@ Page layout options control the physical appearance of your document pages, incl
|
||||
|
||||
Set custom page dimensions:
|
||||
|
||||
```ts
|
||||
import { Document, PageOrientation, Paragraph, convertMillimetersToTwip } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, convertMillimetersToTwip } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
@@ -42,11 +42,11 @@ const doc = new Document({
|
||||
|
||||
Set portrait or landscape orientation:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, PageOrientation, Paragraph, convertMillimetersToTwip } from "docx";
|
||||
|
||||
// Landscape A4
|
||||
// Note: For landscape, swap width and height values so the larger dimension becomes the width
|
||||
// Note: For landscape, give the portrait width and height; docx swaps them so the larger dimension becomes the width
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -54,8 +54,8 @@ const doc = new Document({
|
||||
page: {
|
||||
size: {
|
||||
orientation: PageOrientation.LANDSCAPE,
|
||||
width: convertMillimetersToTwip(297), // A4 height becomes landscape width
|
||||
height: convertMillimetersToTwip(210), // A4 width becomes landscape height
|
||||
width: convertMillimetersToTwip(210), // A4 width becomes landscape height
|
||||
height: convertMillimetersToTwip(297), // A4 height becomes landscape width
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -65,13 +65,13 @@ const doc = new Document({
|
||||
});
|
||||
```
|
||||
|
||||
?> When switching to landscape, you must manually swap the width and height values. The `orientation` property alone only tells Word how to display the page - you still need to provide the correct dimensions.
|
||||
?> When switching to landscape, give the page's portrait width and height: with `orientation: PageOrientation.LANDSCAPE`, docx swaps them for you, so don't swap them yourself. Without a `width` and `height`, the page is A4 turned on its side.
|
||||
|
||||
## Printer Paper Code
|
||||
|
||||
Use the `code` property to specify a printer-specific paper code. This tells the printer which paper tray or paper type to use when the specified dimensions could match multiple paper types. Common codes include `1` (Letter), `5` (Legal), `8` (A3), and `9` (A4).
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, convertMillimetersToTwip } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -108,7 +108,7 @@ const doc = new Document({
|
||||
|
||||
Set margins for the page:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, convertInchesToTwip } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -146,8 +146,8 @@ const doc = new Document({
|
||||
|
||||
Add borders around pages:
|
||||
|
||||
```ts
|
||||
import { BorderStyle, Document, PageBorderDisplay, PageBorderOffsetFrom, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { BorderStyle, Document, Paragraph } from "docx";
|
||||
|
||||
// Note: Border size is measured in 1/8 points (so size: 8 = 1pt, size: 16 = 2pt)
|
||||
const doc = new Document({
|
||||
@@ -209,26 +209,41 @@ Common border styles include:
|
||||
|
||||
Control when and how borders appear:
|
||||
|
||||
```ts
|
||||
import { PageBorderDisplay, PageBorderOffsetFrom, PageBorderZOrder } from "docx";
|
||||
```ts live
|
||||
import { BorderStyle, Document, PageBorderDisplay, PageBorderOffsetFrom, PageBorderZOrder, Paragraph } from "docx";
|
||||
|
||||
page: {
|
||||
borders: {
|
||||
pageBorders: {
|
||||
display: PageBorderDisplay.ALL_PAGES, // or FIRST_PAGE, NOT_FIRST_PAGE
|
||||
offsetFrom: PageBorderOffsetFrom.TEXT, // or PAGE
|
||||
zOrder: PageBorderZOrder.FRONT, // or BACK
|
||||
const border = { style: BorderStyle.SINGLE, size: 8, color: "000000" };
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
page: {
|
||||
borders: {
|
||||
pageBorders: {
|
||||
display: PageBorderDisplay.ALL_PAGES, // or FIRST_PAGE, NOT_FIRST_PAGE
|
||||
offsetFrom: PageBorderOffsetFrom.TEXT, // or PAGE
|
||||
zOrder: PageBorderZOrder.FRONT, // or BACK
|
||||
},
|
||||
// individual border definitions
|
||||
pageBorderTop: border,
|
||||
pageBorderRight: border,
|
||||
pageBorderBottom: border,
|
||||
pageBorderLeft: border,
|
||||
},
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("Page with borders measured from the text")],
|
||||
},
|
||||
// ... individual border definitions
|
||||
},
|
||||
}
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
Combining multiple layout options:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { BorderStyle, Document, PageBorderDisplay, PageOrientation, Paragraph, convertInchesToTwip, convertMillimetersToTwip } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
|
||||
+117
-33
@@ -4,12 +4,27 @@
|
||||
|
||||
?> **Note:** This feature only works on Headers and Footers
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
children: ["Page #: ", PageNumber.CURRENT],
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
children: ["Page #: ", PageNumber.CURRENT],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -22,12 +37,27 @@ PageNumber.CURRENT;
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
children: ["Page Number ", PageNumber.CURRENT],
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
children: ["Page Number ", PageNumber.CURRENT],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -40,12 +70,27 @@ PageNumber.TOTAL_PAGES;
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
children: ["Total Pages Number: ", PageNumber.TOTAL_PAGES],
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
children: ["Total Pages Number: ", PageNumber.TOTAL_PAGES],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -54,13 +99,28 @@ new Paragraph({
|
||||
|
||||
You can combine the two to get "Page 2 of 10" effect:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("My awesome text here for my university dissertation. "),
|
||||
new TextRun({
|
||||
children: ["Page ", PageNumber.CURRENT, " of ", PageNumber.TOTAL_PAGES],
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("My awesome text here for my university dissertation. "),
|
||||
new TextRun({
|
||||
children: ["Page ", PageNumber.CURRENT, " of ", PageNumber.TOTAL_PAGES],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -69,11 +129,18 @@ new Paragraph({
|
||||
|
||||
When a document has multiple sections, you can restart page numbering for each section using `pageNumbers.start` in the section properties:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Footer, PageNumber, Paragraph, TextRun } from "docx";
|
||||
|
||||
const footer = new Footer({
|
||||
children: [new Paragraph({ children: [new TextRun({ children: ["Page ", PageNumber.CURRENT] })] })],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Section 1 content")],
|
||||
footers: { default: footer },
|
||||
children: [new Paragraph("Section 1 content"), new Paragraph({ text: "More of section 1", pageBreakBefore: true })],
|
||||
},
|
||||
{
|
||||
properties: {
|
||||
@@ -83,6 +150,7 @@ const doc = new Document({
|
||||
},
|
||||
},
|
||||
},
|
||||
footers: { default: footer },
|
||||
children: [new Paragraph("Section 2 — page numbering restarts here")],
|
||||
},
|
||||
],
|
||||
@@ -93,13 +161,29 @@ const doc = new Document({
|
||||
|
||||
You can also set the chapter number separator style using the `separator` property:
|
||||
|
||||
```ts
|
||||
import { PageNumberSeparator } from "docx";
|
||||
```ts live
|
||||
import { Document, Footer, PageNumber, PageNumberSeparator, Paragraph, TextRun } from "docx";
|
||||
|
||||
pageNumbers: {
|
||||
start: 1,
|
||||
separator: PageNumberSeparator.EM_DASH, // e.g. "1—1"
|
||||
}
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
properties: {
|
||||
page: {
|
||||
pageNumbers: {
|
||||
start: 1,
|
||||
separator: PageNumberSeparator.EM_DASH, // e.g. "1—1"
|
||||
},
|
||||
},
|
||||
},
|
||||
footers: {
|
||||
default: new Footer({
|
||||
children: [new Paragraph({ children: [new TextRun({ children: ["Page ", PageNumber.CURRENT] })] })],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Available separators: `COLON`, `EM_DASH`, `EN_DASH`, `HYPHEN`, `PERIOD`.
|
||||
|
||||
+314
-114
@@ -8,51 +8,87 @@ You can create `Paragraphs` in the following ways:
|
||||
|
||||
### Shorthand
|
||||
|
||||
```ts
|
||||
import { Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const paragraph = new Paragraph("Short hand Hello World");
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Short hand Hello World")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Children Method
|
||||
|
||||
This method is useful for adding different [text](usage/text.md) with different styles, [symbols](usage/symbols.md), or adding [images](usage/images.md) inline.
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello World"), new SymbolRun("F071")],
|
||||
```ts live
|
||||
import { Document, Paragraph, SymbolRun, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello World"), new SymbolRun("F071")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Explicit
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Short hand notation for adding text.",
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Short hand notation for adding text.",
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
After you create the paragraph, you must add the paragraph into a `section`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const paragraph = new Paragraph("Hello World");
|
||||
|
||||
const doc = new Document({
|
||||
sections: [{
|
||||
children: [paragraph],
|
||||
}];
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Or the preferred convention, define the paragraph inside the section and remove the usage of variables:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello World")],
|
||||
}),
|
||||
],
|
||||
}];
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello World")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -90,9 +126,19 @@ This is the text in a paragraph. You can also add text by using the `Paragraph`
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Hello World",
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Hello World",
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -102,10 +148,20 @@ const paragraph = new Paragraph({
|
||||
|
||||
Setting a Heading 1 paragraph with "Hello World" as it's text:
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Hello World",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Hello World",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -128,23 +184,33 @@ Add borders to a `Paragraph`. Good for making the `Paragraph` stand out. Border
|
||||
|
||||
Add border on the top and the bottom of the paragraph
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "I have borders on my top and bottom sides!",
|
||||
border: {
|
||||
top: {
|
||||
color: "auto",
|
||||
space: 1,
|
||||
style: "single",
|
||||
size: 6,
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "I have borders on my top and bottom sides!",
|
||||
border: {
|
||||
top: {
|
||||
color: "auto",
|
||||
space: 1,
|
||||
style: "single",
|
||||
size: 6,
|
||||
},
|
||||
bottom: {
|
||||
color: "auto",
|
||||
space: 1,
|
||||
style: "single",
|
||||
size: 6,
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
bottom: {
|
||||
color: "auto",
|
||||
space: 1,
|
||||
style: "single",
|
||||
size: 6,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -154,14 +220,24 @@ Colors of borders and shading can be hex values, or colors of the document's the
|
||||
|
||||
Add color to an entire paragraph block
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "shading",
|
||||
shading: {
|
||||
type: ShadingType.REVERSE_DIAGONAL_STRIPE,
|
||||
color: "00FFFF",
|
||||
fill: "FF0000",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, ShadingType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "shading",
|
||||
shading: {
|
||||
type: ShadingType.REVERSE_DIAGONAL_STRIPE,
|
||||
color: "00FFFF",
|
||||
fill: "FF0000",
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -169,10 +245,20 @@ const paragraph = new Paragraph({
|
||||
|
||||
Allow First/Last Line to Display on a Separate Page
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "shading",
|
||||
widowControl: true,
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "widow control",
|
||||
widowControl: true,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -195,12 +281,23 @@ Note: The `lineRule` property has different values depending on the version of W
|
||||
|
||||
Add spacing before the paragraph:
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Paragraph with spacing before",
|
||||
spacing: {
|
||||
before: 200,
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph("Paragraph without spacing"),
|
||||
new Paragraph({
|
||||
text: "Paragraph with spacing before",
|
||||
spacing: {
|
||||
before: 200,
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -224,12 +321,22 @@ Set paragraph indentation from the page margins using the `indent` property.
|
||||
|
||||
**Example — first-line indent in twips:**
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Indented first line",
|
||||
indent: {
|
||||
firstLine: 720, // 720 twips = 0.5 inch
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Indented first line. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat.",
|
||||
indent: {
|
||||
firstLine: 720, // 720 twips = 0.5 inch
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -237,24 +344,44 @@ const paragraph = new Paragraph({
|
||||
|
||||
Use `firstLineChars` when you want Word to calculate the indent relative to the font's character width rather than a fixed measurement. The value is in hundredths of a character, so `200` means two characters.
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "First line indented by two characters",
|
||||
indent: {
|
||||
firstLineChars: 200,
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "First line indented by two characters. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat.",
|
||||
indent: {
|
||||
firstLineChars: 200,
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
**Example — left and hanging indent:**
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Hanging indent paragraph",
|
||||
indent: {
|
||||
left: 720,
|
||||
hanging: 360, // first line hangs back 360 twips from the left indent
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Hanging indent paragraph. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat.",
|
||||
indent: {
|
||||
left: 720,
|
||||
hanging: 360, // first line hangs back 360 twips from the left indent
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -262,9 +389,20 @@ const paragraph = new Paragraph({
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
outlineLevel: 0,
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Hello World",
|
||||
outlineLevel: 0,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -274,12 +412,20 @@ To create styles, please refer to the [styling documentation](usage/styling-with
|
||||
|
||||
### Headings and titles
|
||||
|
||||
```ts
|
||||
import { HeadingLevel, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
text: "Hello World",
|
||||
heading: HeadingLevel.TITLE,
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Hello World",
|
||||
heading: HeadingLevel.TITLE,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -289,11 +435,21 @@ To change the text alignment of a paragraph, add an `AlignmentType` option on th
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Hello World",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
alignment: AlignmentType.CENTER,
|
||||
```ts live
|
||||
import { AlignmentType, Document, HeadingLevel, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Hello World",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
alignment: AlignmentType.CENTER,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -303,7 +459,9 @@ The above will create a `heading 1` which is `centered`.
|
||||
|
||||
When a paragraph is justified, incomplete lines ending in a soft line break are stretched to fill the full width by default. To prevent this, enable `doNotExpandShiftReturn` in the document's compatibility options:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
compatibility: {
|
||||
doNotExpandShiftReturn: true,
|
||||
@@ -312,7 +470,7 @@ const doc = new Document({
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "This justified paragraph won't stretch soft line breaks.",
|
||||
children: [new TextRun("This justified paragraph won't stretch"), new TextRun({ text: "soft line breaks.", break: 1 })],
|
||||
alignment: AlignmentType.JUSTIFIED,
|
||||
}),
|
||||
],
|
||||
@@ -325,23 +483,44 @@ const doc = new Document({
|
||||
|
||||
To add a thematic break in the `Paragraph`:
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Amazing Heading",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
thematicBreak: true,
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Amazing Heading",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
thematicBreak: true,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
The above example will create a heading with a page break directly under it.
|
||||
The above example will create a heading with a horizontal line directly under it.
|
||||
|
||||
## Page Break
|
||||
|
||||
To move to a new page (insert a page break):
|
||||
|
||||
```ts
|
||||
const paragraph = new docx.Paragraph({
|
||||
children: [new TextRun("Amazing Heading"), new PageBreak()],
|
||||
```ts live
|
||||
import { Document, PageBreak, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun("Amazing Heading"), new PageBreak()],
|
||||
}),
|
||||
new Paragraph("This text starts on the new page"),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -351,10 +530,21 @@ The above example will create a heading and start a new page immediately afterwa
|
||||
|
||||
This option (available in word) will make sure that the paragraph will start on a new page (if it's not already on a new page).
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Hello World on another page",
|
||||
pageBreakBefore: true,
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph("Hello World"),
|
||||
new Paragraph({
|
||||
text: "Hello World on another page",
|
||||
pageBreakBefore: true,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -366,10 +556,20 @@ Example: https://github.com/dolanmiu/docx/blob/master/demo/paragraphs/page-break
|
||||
|
||||
Paragraphs have `keepLines` and `keepNext` properties that allow restricting page breaks within and between paragraphs. See [this Microsoft article](https://support.microsoft.com/en-us/office/keep-text-together-in-word-af94e5b8-3a5a-4cb0-9c53-dea56b43d96d) for more details.
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
text: "Stay on the same page",
|
||||
keepLines: true,
|
||||
keepNext: true,
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Stay on the same page",
|
||||
keepLines: true,
|
||||
keepNext: true,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
+18
-5
@@ -12,11 +12,15 @@ The patcher allows you to modify existing documents, and add new content to them
|
||||
import * as fs from "fs";
|
||||
import { patchDocument } from "docx";
|
||||
|
||||
patchDocument(fs.readFileSync("My Document.docx"), {
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("My Document.docx"),
|
||||
patches: {
|
||||
// Patches here
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Patched Document.docx", doc);
|
||||
```
|
||||
|
||||
## Patches
|
||||
@@ -57,14 +61,21 @@ A patch can also be for a drawing whose alt text holds the placeholder, rather t
|
||||
|
||||
The patch can be as simple as a string, or as complex as a table. Images, hyperlinks, charts from `docx/charts` (see [Charts in Templates](usage/chart-size-and-position.md#in-templates)), and other complex elements within the `docx` library are also supported.
|
||||
|
||||
```ts
|
||||
patchDocument(fs.readFileSync("My Document.docx"), {
|
||||
This example patches `{{name}}` and `{{paragraph_replace}}` in [simple-template.docx](https://github.com/dolanmiu/docx/blob/master/demo/assets/simple-template.docx):
|
||||
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { ExternalHyperlink, ImageRun, Paragraph, patchDocument, PatchType, TextRun } from "docx";
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("./demo/assets/simple-template.docx"),
|
||||
patches: {
|
||||
my_patch: {
|
||||
name: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [new TextRun("Sir. "), new TextRun("John Doe"), new TextRun("(The Conqueror)")],
|
||||
},
|
||||
my_second_patch: {
|
||||
paragraph_replace: {
|
||||
type: PatchType.DOCUMENT,
|
||||
children: [
|
||||
new Paragraph("Lorem ipsum paragraph"),
|
||||
@@ -91,6 +102,8 @@ patchDocument(fs.readFileSync("My Document.docx"), {
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
+36
-12
@@ -10,7 +10,9 @@ For example, you could have one section which is portrait with a header and foot
|
||||
|
||||
This creates a simple section in a document with one paragraph inside:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -28,7 +30,9 @@ const doc = new Document({
|
||||
|
||||
Create documents with multiple sections for different layouts:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, PageOrientation, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -66,8 +70,8 @@ Setting the section type determines how the contents of the section will be plac
|
||||
| `ODD_PAGE` | Start on the next odd-numbered page |
|
||||
| `NEXT_COLUMN` | Start in the next column |
|
||||
|
||||
```ts
|
||||
import { SectionType } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, SectionType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
@@ -95,7 +99,9 @@ const doc = new Document({
|
||||
|
||||
### Different Headers Per Section
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -120,8 +126,8 @@ const doc = new Document({
|
||||
|
||||
### Portrait and Landscape Mix
|
||||
|
||||
```ts
|
||||
import { PageOrientation, convertMillimetersToTwip } from "docx";
|
||||
```ts live
|
||||
import { Document, PageOrientation, Paragraph, Table, TableCell, TableRow, convertMillimetersToTwip } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
@@ -135,15 +141,27 @@ const doc = new Document({
|
||||
page: {
|
||||
size: {
|
||||
orientation: PageOrientation.LANDSCAPE,
|
||||
width: convertMillimetersToTwip(297),
|
||||
height: convertMillimetersToTwip(210),
|
||||
// The A4 portrait size, which LANDSCAPE turns on its side
|
||||
width: convertMillimetersToTwip(210),
|
||||
height: convertMillimetersToTwip(297),
|
||||
},
|
||||
},
|
||||
},
|
||||
children: [
|
||||
new Table({
|
||||
// Wide table that needs landscape
|
||||
rows: [/* ... */],
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: ["January", "February", "March", "April", "May", "June", "July", "August"].map(
|
||||
(month) => new TableCell({ children: [new Paragraph(month)] }),
|
||||
),
|
||||
}),
|
||||
new TableRow({
|
||||
children: ["120", "135", "150", "160", "155", "170", "180", "175"].map(
|
||||
(sales) => new TableCell({ children: [new Paragraph(sales)] }),
|
||||
),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
@@ -153,7 +171,9 @@ const doc = new Document({
|
||||
|
||||
### Multi-Column Section
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, SectionType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -169,7 +189,11 @@ const doc = new Document({
|
||||
space: 708,
|
||||
},
|
||||
},
|
||||
children: [new Paragraph("Two-column content...")],
|
||||
children: [
|
||||
new Paragraph(
|
||||
"Two-column content flows down the first column and then carries on at the top of the second, like the columns of a newspaper. The section breaks before and after it are continuous, so the columns sit on the same page as the paragraphs around them.",
|
||||
),
|
||||
],
|
||||
},
|
||||
{
|
||||
// Back to single column
|
||||
|
||||
@@ -2,13 +2,26 @@
|
||||
|
||||
Adjustments change the proportions of a [shape](usage/shapes.md), the same way as dragging its yellow handles in Word. This page lists the adjustments of every shape that has them. Shapes that aren't listed, such as `rectangle`, `ellipse` and the flowchart shapes, have none.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ShapeRun } from "docx/shapes";
|
||||
|
||||
new ShapeRun({
|
||||
type: "rightArrowCallout",
|
||||
adjustments: { shaftThickness: 20, headWidth: 50, headLength: 25, boxWidth: 60 },
|
||||
transformation: { width: 200, height: 80 },
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ShapeRun({
|
||||
type: "rightArrowCallout",
|
||||
adjustments: { shaftThickness: 20, headWidth: 50, headLength: 25, boxWidth: 60 },
|
||||
transformation: { width: 200, height: 80 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+1056
-328
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,9 @@
|
||||
|
||||
## Example
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, Document, HeadingLevel, Paragraph, TextRun } from "docx";
|
||||
|
||||
const para = new Paragraph({
|
||||
text: "To whom it may concern:",
|
||||
heading: HeadingLevel.HEADING_2,
|
||||
@@ -15,6 +17,14 @@ const name = new TextRun({
|
||||
font: "Calibri",
|
||||
allCaps: true,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [para, new Paragraph({ children: [name] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Available Options
|
||||
@@ -66,23 +76,43 @@ Unlike CSS, less specific rules don't _necessarily_ override parent rules. The r
|
||||
|
||||
This is the type of formatting that your uncle uses when he types out documents: _N ... a ... m ... e ... :_ Then he grabs the mouse, highlights _Name:_ and moves over to the **B** for bold. This manner of formatting results in markup that is similar to writing `<span style="bold: true">Name:</span>` if you were typing out HTML. `docx` (the format) allows you to specify this for any of the four types of items. `docx` (the library) only supports this type of formatting for paragraphs and characters, using a _fluent_ api. Thus you could do:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const name = new TextRun({
|
||||
text: "Name:",
|
||||
bold: true,
|
||||
font: "Calibri",
|
||||
allCaps: true,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph({ children: [name, new TextRun(" Clippy")] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Or for paragraph formatting:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { AlignmentType, Document, HeadingLevel, Paragraph } from "docx";
|
||||
|
||||
const para = new Paragraph({
|
||||
text: "To whom it may concern:",
|
||||
heading: HeadingLevel.HEADING_2,
|
||||
alignment: AlignmentType.CENTER,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [para],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Declarative Styles (similar to external CSS)
|
||||
@@ -91,7 +121,9 @@ const para = new Paragraph({
|
||||
|
||||
To add styles, define your custom styles in the `document`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph, UnderlineType } from "docx";
|
||||
|
||||
// The first argument is an ID you use to apply the style to paragraphs
|
||||
// The second argument is a human-friendly name to show in the UI
|
||||
const doc = new Document({
|
||||
@@ -143,6 +175,20 @@ const doc = new Document({
|
||||
},
|
||||
],
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "A heading in the Heading 2 style",
|
||||
heading: HeadingLevel.HEADING_2,
|
||||
}),
|
||||
new Paragraph({
|
||||
text: "A paragraph in My Wonky Style",
|
||||
style: "myWonkyStyle",
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -156,12 +202,18 @@ Setting document defaults acts like a `*` rule in CSS: it applies to every parag
|
||||
|
||||
Paragraphs that don't name a style use the default paragraph style, `Normal`, which the headings and other built-in styles are based on. `docx` writes a `Normal` with no formatting of its own, so paragraphs take the document defaults. To format it, give a paragraph style with the id `Normal`. It takes the place of `docx`'s and stays the default:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
styles: {
|
||||
paragraphStyles: [{ id: "Normal", name: "Normal", run: { font: "Calibri", size: 22 } }],
|
||||
},
|
||||
sections: [],
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("A paragraph in the Normal style, in 11 point Calibri")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -28,26 +28,50 @@
|
||||
|
||||
Read the styles using `fs`, and put it into the `Document` object in the constructor:
|
||||
|
||||
```ts
|
||||
const styles = fs.readFileSync("./styles.xml", "utf-8");
|
||||
const doc = new docx.Document({
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const styles = fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8");
|
||||
const doc = new Document({
|
||||
title: "Title",
|
||||
externalStyles: styles,
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("Some normal text, in the Normal style of styles.xml")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Your styles take the place of the library's default styles with the same ids, and your document defaults take the place of the library's. The library's default styles fill in the ones your `styles.xml` leaves out, such as `Hyperlink` or `FootnoteText`. A default style you set in `styles.default`, such as `heading1` or `document`, takes the place of yours.
|
||||
|
||||
You can use paragraphs, `heading1()`, `heading2()` etc and it will be styled according to your `styles.xml` created earlier. You can even use your new style you made by calling the `style` method:
|
||||
You can use paragraphs, `HeadingLevel.HEADING_1`, `HeadingLevel.HEADING_2` etc and it will be styled according to your `styles.xml` created earlier. You can even use your new style you made with the `style` option:
|
||||
|
||||
```ts
|
||||
doc.createParagraph("Cool Heading Text").heading1();
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const paragraph = new docx.Paragraph('This is a custom named style from the template "Cool New Style"');
|
||||
paragraph.style("Cool New Style");
|
||||
doc.add(paragraph);
|
||||
|
||||
doc.createParagraph("Some normal text");
|
||||
const styles = fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8");
|
||||
const doc = new Document({
|
||||
title: "Title",
|
||||
externalStyles: styles,
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Cool Heading Text",
|
||||
heading: HeadingLevel.HEADING_1,
|
||||
}),
|
||||
new Paragraph({
|
||||
text: 'This is a custom named style from the template "MyFancyStyle"',
|
||||
style: "MyFancyStyle",
|
||||
}),
|
||||
new Paragraph("Some normal text"),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Example: https://github.com/dolanmiu/docx/blob/master/demo/styles/xml-styles.ts
|
||||
|
||||
+49
-13
@@ -4,11 +4,19 @@
|
||||
|
||||
You can add multiple `symbol runs` in `Paragraphs` along with [text runs](usage/text.md) using the Paragraph's `children` property.
|
||||
|
||||
```ts
|
||||
import { Paragraph, TextRun, SymbolRun } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun, SymbolRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("This is a checkbox: "), new SymbolRun("F071")],
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun("This is a checkbox: "), new SymbolRun("F071")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -16,10 +24,24 @@ const paragraph = new Paragraph({
|
||||
|
||||
By default symbol runs will use the `Wingdings` font. To switch fonts, pass an object instead of a string to the `SymbolRun` constructor and specify `char` and `symbolfont` properties:
|
||||
|
||||
```ts
|
||||
const symbol = new SymbolRun({
|
||||
char: "F071",
|
||||
symbolfont: "Arial",
|
||||
```ts live
|
||||
import { Document, Paragraph, SymbolRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new SymbolRun({
|
||||
char: "F071",
|
||||
symbolfont: "Arial",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -39,11 +61,25 @@ Symbols are specified by their hexidecimal code. Ref http://officeopenxml.com/WP
|
||||
|
||||
Symbol runs can have their display modified just like text runs. For example, they can be bolded and italicized:
|
||||
|
||||
```ts
|
||||
const symbol = new SymbolRun({
|
||||
char: "F071",
|
||||
bold: true,
|
||||
italics: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, SymbolRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new SymbolRun({
|
||||
char: "F071",
|
||||
bold: true,
|
||||
italics: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -14,7 +14,9 @@ All you need to do is create a `TableOfContents` object and assign it to the doc
|
||||
|
||||
**Note**: updateFields feature must be enabled for TableOfContents to update correctly.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph, TableOfContents } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
features: {
|
||||
updateFields: true,
|
||||
@@ -75,7 +77,9 @@ Each entry is a `ToCEntry` object with the following properties:
|
||||
|
||||
Entry indentation comes from paragraph styles applied to each level. The defaults are `TOC1`, `TOC2`, etc. You can override these with the `stylesWithLevels` (`\t`) option — entries will use the style whose `level` matches the entry's `level`.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Bookmark, Document, HeadingLevel, Paragraph, TableOfContents } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
features: {
|
||||
updateFields: true,
|
||||
@@ -134,11 +138,26 @@ These options control the TOC structure rather than field switches:
|
||||
|
||||
You can provide placeholder content that will be displayed until the TOC is updated:
|
||||
|
||||
```ts
|
||||
new TableOfContents("Summary", {
|
||||
hyperlink: true,
|
||||
headingStyleRange: "1-5",
|
||||
contentChildren: [new Paragraph({ text: "Chapter 1..........1" }), new Paragraph({ text: "Chapter 2..........5" })],
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph, TableOfContents } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
features: {
|
||||
updateFields: true,
|
||||
},
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new TableOfContents("Summary", {
|
||||
hyperlink: true,
|
||||
headingStyleRange: "1-5",
|
||||
contentChildren: [new Paragraph({ text: "Chapter 1..........1" }), new Paragraph({ text: "Chapter 2..........5" })],
|
||||
}),
|
||||
new Paragraph({ text: "Chapter 1", heading: HeadingLevel.HEADING_1, pageBreakBefore: true }),
|
||||
new Paragraph({ text: "Chapter 2", heading: HeadingLevel.HEADING_1, pageBreakBefore: true }),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+350
-39
@@ -8,17 +8,25 @@
|
||||
- `Rows` contain a list of `TableCells`
|
||||
- `TableCells` contain a list of `Paragraphs` and/or `Tables`. You can add `Tables` as tables can be nested inside each other
|
||||
|
||||
Create a simple table like so:
|
||||
Create a simple table, then add the table in the `section`:
|
||||
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
```ts
|
||||
const table = new Table({
|
||||
rows: [Array of `TableRow`s]
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [new TableCell({ children: [new Paragraph("Name")] }), new TableCell({ children: [new Paragraph("Age")] })],
|
||||
}),
|
||||
new TableRow({
|
||||
children: [new TableCell({ children: [new Paragraph("Alice")] }), new TableCell({ children: [new Paragraph("32")] })],
|
||||
}),
|
||||
new TableRow({
|
||||
children: [new TableCell({ children: [new Paragraph("Bob")] }), new TableCell({ children: [new Paragraph("27")] })],
|
||||
}),
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Then add the table in the `section`
|
||||
|
||||
```ts
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -44,14 +52,27 @@ const table = new Table({
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
|
||||
|
||||
const table = new Table({
|
||||
...,
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [new TableCell({ children: [new Paragraph("Hello")] }), new TableCell({ children: [new Paragraph("World")] })],
|
||||
}),
|
||||
],
|
||||
width: {
|
||||
size: 4535,
|
||||
type: WidthType.DXA,
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [table],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -59,11 +80,28 @@ const table = new Table({
|
||||
|
||||
A table's columns are defined by its grid (`w:tblGrid`), whose widths are always in twips (twentieths of a point). You can set them explicitly with `columnWidths`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const table = new Table({
|
||||
...,
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("3505 twips wide")] }),
|
||||
new TableCell({ children: [new Paragraph("5505 twips wide")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
columnWidths: [3505, 5505],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [table],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
When `columnWidths` is omitted, `docx` derives the grid for you from the table's `width` and the cells' `width`s. Percentages are resolved against the actual page size and margins of the section the table is in (or the parent cell for nested tables) when the document is packed, and columns without a width share whatever is left equally. So a 100% wide table with 90% / 10% cells on a default A4 page gets a grid of `[8123, 903]`, and a table with no widths at all gets equal, full-width columns.
|
||||
@@ -72,13 +110,27 @@ When `columnWidths` is omitted, `docx` derives the grid for you from the table's
|
||||
|
||||
### Set Indent
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
|
||||
|
||||
const table = new Table({
|
||||
...,
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [new TableCell({ children: [new Paragraph("Hello")] }), new TableCell({ children: [new Paragraph("World")] })],
|
||||
}),
|
||||
],
|
||||
indent: {
|
||||
size: 600,
|
||||
type: WidthType.DXA,
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Paragraph("This paragraph starts at the margin, and the table below is indented from it."), table],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -86,7 +138,9 @@ const table = new Table({
|
||||
|
||||
A table consists of multiple `table rows`. Table rows have a list of `children` which accepts a list of `table cells` explained below. You can create a simple `table row` like so:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const tableRow = new TableRow({
|
||||
children: [
|
||||
new TableCell({
|
||||
@@ -94,11 +148,21 @@ const tableRow = new TableRow({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [tableRow] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Or preferably, add the tableRow directly into the `table` without declaring a variable:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const table = new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
@@ -110,6 +174,14 @@ const table = new Table({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [table],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Options
|
||||
@@ -127,11 +199,38 @@ Here is a list of options you can add to the `table row`:
|
||||
|
||||
If a table is paginated on multiple pages, it is possible to repeat a row at the top of each new page by setting `tableHeader` to `true`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const row = new TableRow({
|
||||
...,
|
||||
children: [new TableCell({ children: [new Paragraph("Item")] }), new TableCell({ children: [new Paragraph("Quantity")] })],
|
||||
tableHeader: true,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
row,
|
||||
// Enough rows to run onto a second page, where the header row repeats
|
||||
...Array.from(
|
||||
{ length: 60 },
|
||||
(_, index) =>
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph(`Item ${index + 1}`)] }),
|
||||
new TableCell({ children: [new Paragraph(`${index + 1}`)] }),
|
||||
],
|
||||
}),
|
||||
),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Pagination
|
||||
@@ -140,26 +239,56 @@ const row = new TableRow({
|
||||
|
||||
To prevent breaking contents of a row across multiple pages, call `cantSplit`:
|
||||
|
||||
```ts
|
||||
const row = new Row({
|
||||
...,
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const row = new TableRow({
|
||||
children: [
|
||||
new TableCell({
|
||||
children: [
|
||||
new Paragraph("The lines of this row stay together."),
|
||||
new Paragraph("If the row doesn't fit at the bottom of a page,"),
|
||||
new Paragraph("the whole row moves to the next page."),
|
||||
],
|
||||
}),
|
||||
],
|
||||
cantSplit: true,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [row] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Table Cells
|
||||
|
||||
Cells need to be added in the `table row`, you can create a table cell like:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const tableCell = new TableCell({
|
||||
children: [new Paragraph("hello")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [new TableRow({ children: [tableCell] })] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Or preferably, add the tableRow directly into the `table row` without declaring a variable:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const tableRow = new TableRow({
|
||||
children: [
|
||||
new TableCell({
|
||||
@@ -167,6 +296,14 @@ const tableRow = new TableRow({
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [tableRow] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Options
|
||||
@@ -193,9 +330,11 @@ const tableRow = new TableRow({
|
||||
|
||||
##### Example
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { BorderStyle, Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
...,
|
||||
children: [new Paragraph("Hello")],
|
||||
borders: {
|
||||
top: {
|
||||
style: BorderStyle.DASH_DOT_STROKED,
|
||||
@@ -209,15 +348,25 @@ const cell = new TableCell({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [new TableRow({ children: [cell] })] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
##### Google DOCS
|
||||
|
||||
Google DOCS does not support start and end borders, instead they use left and right borders. So to set left and right borders for Google DOCS you should use:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { BorderStyle, Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
...,
|
||||
children: [new Paragraph("Hello")],
|
||||
borders: {
|
||||
left: {
|
||||
style: BorderStyle.DOT_DOT_DASH,
|
||||
@@ -231,16 +380,34 @@ const cell = new TableCell({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [new TableRow({ children: [cell] })] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Add paragraph to a cell
|
||||
|
||||
Once you have got the cell, you can add data to it:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
children: [new Paragraph("Hello")],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [new Table({ rows: [new TableRow({ children: [cell] })] })],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Set width of a cell
|
||||
@@ -270,9 +437,34 @@ const cell = new TableCell({
|
||||
|
||||
To have a table within a table, simply add it in the `children` block of a `table cell`:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
children: [new Table(...)],
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Inner cell 1")] }),
|
||||
new TableCell({ children: [new Paragraph("Inner cell 2")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [new TableRow({ children: [new TableCell({ children: [new Paragraph("Outer cell")] }), cell] })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -297,10 +489,32 @@ const cell = new TableCell({
|
||||
|
||||
For example, to center align a cell:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow, VerticalAlignTable } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
children: [new Paragraph("Centered")],
|
||||
verticalAlign: VerticalAlignTable.CENTER,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Line 1"), new Paragraph("Line 2"), new Paragraph("Line 3")] }),
|
||||
cell,
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Merging cells together
|
||||
@@ -321,11 +535,30 @@ const cell = new TableCell({
|
||||
|
||||
The example will merge three rows together.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
...,
|
||||
children: [new Paragraph("Merged across three rows")],
|
||||
rowSpan: 3,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({ children: [cell, new TableCell({ children: [new Paragraph("Row 1")] })] }),
|
||||
// The merged cell takes the first place in the next two rows, so they have one cell each
|
||||
new TableRow({ children: [new TableCell({ children: [new Paragraph("Row 2")] })] }),
|
||||
new TableRow({ children: [new TableCell({ children: [new Paragraph("Row 3")] })] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Column Merge
|
||||
@@ -344,30 +577,99 @@ const cell = new TableCell({
|
||||
|
||||
The example will merge three columns together.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const cell = new TableCell({
|
||||
...,
|
||||
children: [new Paragraph("Merged across three columns")],
|
||||
columnSpan: 3,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({ children: [cell] }),
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Column 1")] }),
|
||||
new TableCell({ children: [new Paragraph("Column 2")] }),
|
||||
new TableCell({ children: [new Paragraph("Column 3")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Visual Right to Left Table
|
||||
|
||||
It is possible to reverse how the cells of the table are displayed. The table direction. More info here: https://superuser.com/questions/996912/how-to-change-a-table-direction-in-microsoft-word
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const table = new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("1")] }),
|
||||
new TableCell({ children: [new Paragraph("2")] }),
|
||||
new TableCell({ children: [new Paragraph("3")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
visuallyRightToLeft: true,
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [table],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Table Look (Conditional Formatting)
|
||||
|
||||
Control which conditional formatting from a table style is applied. Table styles can define special formatting for the first row, first column, etc. Use `tableLook` to toggle these formatting options.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, Table, TableCell, TableRow } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const table = new Table({
|
||||
style: "GridTable5Dark-Accent3",
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Header 1")] }),
|
||||
new TableCell({ children: [new Paragraph("Header 2")] }),
|
||||
new TableCell({ children: [new Paragraph("Header 3")] }),
|
||||
],
|
||||
}),
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Row 1, Col 1")] }),
|
||||
new TableCell({ children: [new Paragraph("Row 1, Col 2")] }),
|
||||
new TableCell({ children: [new Paragraph("Row 1, Col 3")] }),
|
||||
],
|
||||
}),
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Row 2, Col 1")] }),
|
||||
new TableCell({ children: [new Paragraph("Row 2, Col 2")] }),
|
||||
new TableCell({ children: [new Paragraph("Row 2, Col 3")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
// A table style from the document's styles, here the ones in demo/assets/custom-styles.xml
|
||||
style: "MyCustomTableStyle",
|
||||
tableLook: {
|
||||
firstRow: true, // Apply first row formatting
|
||||
lastRow: false, // Don't apply last row formatting
|
||||
@@ -377,6 +679,15 @@ const table = new Table({
|
||||
noVBand: true, // Don't apply vertical banding (column stripes)
|
||||
},
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
externalStyles: fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8"),
|
||||
sections: [
|
||||
{
|
||||
children: [table],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
**Note**: When `tableLook` is not specified at all, Word applies row and column banding by default, but does not apply first/last row/column formatting.
|
||||
|
||||
+114
-23
@@ -12,19 +12,36 @@ Simply declare the tab stops on the paragraph, as shown below. Use the tab chara
|
||||
|
||||
### Example
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
children: [
|
||||
new TextRun({ text: "Hey everyone", bold: true }),
|
||||
new TextRun("\t11th November 1999"),
|
||||
new TextRun({
|
||||
children: [new Tab(), "11th November 1999"],
|
||||
}),
|
||||
],
|
||||
tabStops: [
|
||||
```ts live
|
||||
import { Document, Paragraph, Tab, TabStopPosition, TabStopType, TextRun } from "docx";
|
||||
|
||||
const tabStops = [
|
||||
{
|
||||
type: TabStopType.RIGHT,
|
||||
position: TabStopPosition.MAX,
|
||||
},
|
||||
];
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
type: TabStopType.RIGHT,
|
||||
position: TabStopPosition.MAX,
|
||||
children: [
|
||||
// With the tab character
|
||||
new Paragraph({
|
||||
children: [new TextRun({ text: "Hey everyone", bold: true }), new TextRun("\t11th November 1999")],
|
||||
tabStops,
|
||||
}),
|
||||
// Or with a Tab
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({ text: "Hey everyone", bold: true }),
|
||||
new TextRun({
|
||||
children: [new Tab(), "11th November 1999"],
|
||||
}),
|
||||
],
|
||||
tabStops,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -32,7 +49,9 @@ const paragraph = new Paragraph({
|
||||
|
||||
The example above will create a left aligned text, and a right aligned text on the same line. The laymans approach to this problem would be to either use text boxes or tables. Not ideal!
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TabStopPosition, TabStopType, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("\t\tSecond tab stop here I come!")],
|
||||
tabStops: [
|
||||
@@ -46,14 +65,24 @@ const paragraph = new Paragraph({
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
The above shows the use of two tab stops, and how to select/use it.
|
||||
|
||||
You can add multiple tab stops of the same `type` too.
|
||||
|
||||
```ts
|
||||
const paragraph = new Paragraph({
|
||||
```ts live
|
||||
import { Document, Paragraph, Tab, TabStopPosition, TabStopType, TextRun } from "docx";
|
||||
|
||||
const withTabCharacters = new Paragraph({
|
||||
children: [new TextRun("Multiple \ttab \tstops!")],
|
||||
tabStops: [
|
||||
{
|
||||
@@ -67,7 +96,7 @@ const paragraph = new Paragraph({
|
||||
],
|
||||
});
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
const withTabChildren = new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
children: ["Multiple ", new Tab(), "tab ", new Tab(), "stops!"],
|
||||
@@ -84,12 +113,23 @@ const paragraph = new Paragraph({
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [withTabCharacters, withTabChildren],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Left Tab Stop
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TabStopType, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("Before\tLeft aligned at 2268")],
|
||||
tabStops: [
|
||||
{
|
||||
type: TabStopType.LEFT,
|
||||
@@ -97,14 +137,25 @@ const paragraph = new Paragraph({
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
2268 is the distance from the left side.
|
||||
|
||||
### Center Tab Stop
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TabStopType, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("\tCentered on 2268")],
|
||||
tabStops: [
|
||||
{
|
||||
type: TabStopType.CENTER,
|
||||
@@ -112,14 +163,25 @@ const paragraph = new Paragraph({
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
2268 is the distance from the center.
|
||||
|
||||
### Right Tab Stop
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TabStopType, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("\tEnds at 2268")],
|
||||
tabStops: [
|
||||
{
|
||||
type: TabStopType.RIGHT,
|
||||
@@ -127,14 +189,25 @@ const paragraph = new Paragraph({
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
2268 is the distance from the left side.
|
||||
|
||||
### Max Right Tab Stop
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TabStopPosition, TabStopType, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("Left aligned\tRight aligned")],
|
||||
tabStops: [
|
||||
{
|
||||
type: TabStopType.RIGHT,
|
||||
@@ -142,6 +215,14 @@ const paragraph = new Paragraph({
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
This will create a tab stop on the very edge of the right hand side. Handy for right aligning and left aligning text on the same line.
|
||||
@@ -156,8 +237,10 @@ They are easier to use than the normal tab stops, as you can use the `Positional
|
||||
|
||||
### Example
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
```ts live
|
||||
import { Document, Paragraph, PositionalTab, PositionalTabAlignment, PositionalTabLeader, PositionalTabRelativeTo, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [
|
||||
new TextRun("Full name"),
|
||||
new TextRun({
|
||||
@@ -172,7 +255,15 @@ new Paragraph({
|
||||
bold: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [paragraph],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
+197
-89
@@ -31,13 +31,28 @@ Best regards,
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { patchDocument, PatchType, TextRun } from "docx";
|
||||
import { Document, Packer, Paragraph, patchDocument, PatchType, TextRun } from "docx";
|
||||
|
||||
patchDocument({
|
||||
// The template, made here as it would be in Word
|
||||
const template = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph("Dear {{customer_name}},"),
|
||||
new Paragraph("Thank you for your order #{{order_number}}."),
|
||||
new Paragraph("Your items will ship on {{ship_date}}."),
|
||||
new Paragraph("Best regards,"),
|
||||
new Paragraph("{{company_name}}"),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("template.docx"),
|
||||
data: await Packer.toBuffer(template), // or fs.readFileSync("template.docx")
|
||||
patches: {
|
||||
customer_name: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
@@ -56,149 +71,227 @@ patchDocument({
|
||||
children: [new TextRun("Acme Corp")],
|
||||
},
|
||||
},
|
||||
}).then((doc) => {
|
||||
fs.writeFileSync("output.docx", doc);
|
||||
});
|
||||
|
||||
fs.writeFileSync("output.docx", doc);
|
||||
```
|
||||
|
||||
## Patch Types
|
||||
|
||||
The examples below patch [simple-template.docx](https://github.com/dolanmiu/docx/blob/master/demo/assets/simple-template.docx), which has placeholders such as `{{name}}`, `{{paragraph_replace}}` and `{{table}}`.
|
||||
|
||||
### PARAGRAPH Type
|
||||
|
||||
Use `PatchType.PARAGRAPH` to replace with inline content (TextRun, images, hyperlinks):
|
||||
|
||||
```ts
|
||||
my_patch: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [
|
||||
new TextRun("Hello "),
|
||||
new TextRun({ text: "World", bold: true }),
|
||||
],
|
||||
}
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { patchDocument, PatchType, TextRun } from "docx";
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("./demo/assets/simple-template.docx"),
|
||||
patches: {
|
||||
name: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [new TextRun("Hello "), new TextRun({ text: "World", bold: true })],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
### DOCUMENT Type
|
||||
|
||||
Use `PatchType.DOCUMENT` to replace with block-level content (paragraphs, tables):
|
||||
|
||||
```ts
|
||||
my_patch: {
|
||||
type: PatchType.DOCUMENT,
|
||||
children: [
|
||||
new Paragraph("First paragraph"),
|
||||
new Paragraph("Second paragraph"),
|
||||
new Table({
|
||||
rows: [/* ... */],
|
||||
}),
|
||||
],
|
||||
}
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Paragraph, patchDocument, PatchType, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("./demo/assets/simple-template.docx"),
|
||||
patches: {
|
||||
paragraph_replace: {
|
||||
type: PatchType.DOCUMENT,
|
||||
children: [
|
||||
new Paragraph("First paragraph"),
|
||||
new Paragraph("Second paragraph"),
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("First cell")] }),
|
||||
new TableCell({ children: [new Paragraph("Second cell")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
## Advanced Patches
|
||||
|
||||
### Images
|
||||
|
||||
```ts
|
||||
import { ImageRun, PatchType } from "docx";
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { ImageRun, patchDocument, PatchType } from "docx";
|
||||
|
||||
image_placeholder: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./logo.png"),
|
||||
transformation: { width: 100, height: 50 },
|
||||
}),
|
||||
],
|
||||
}
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("./demo/assets/simple-template.docx"),
|
||||
patches: {
|
||||
image_test: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [
|
||||
new ImageRun({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./demo/assets/images/dog.png"),
|
||||
transformation: { width: 100, height: 90 },
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
### Hyperlinks
|
||||
|
||||
```ts
|
||||
import { ExternalHyperlink, PatchType, TextRun } from "docx";
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { ExternalHyperlink, patchDocument, PatchType, TextRun } from "docx";
|
||||
|
||||
link_placeholder: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [
|
||||
new ExternalHyperlink({
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("./demo/assets/simple-template.docx"),
|
||||
patches: {
|
||||
item_1: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Visit our website",
|
||||
style: "Hyperlink",
|
||||
new ExternalHyperlink({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Visit our website",
|
||||
style: "Hyperlink",
|
||||
}),
|
||||
],
|
||||
link: "https://example.com",
|
||||
}),
|
||||
],
|
||||
link: "https://example.com",
|
||||
}),
|
||||
],
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
### Tables
|
||||
|
||||
```ts
|
||||
import { Paragraph, PatchType, Table, TableCell, TableRow } from "docx";
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Paragraph, patchDocument, PatchType, Table, TableCell, TableRow } from "docx";
|
||||
|
||||
table_placeholder: {
|
||||
type: PatchType.DOCUMENT,
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Item")] }),
|
||||
new TableCell({ children: [new Paragraph("Price")] }),
|
||||
],
|
||||
}),
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Widget")] }),
|
||||
new TableCell({ children: [new Paragraph("$9.99")] }),
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("./demo/assets/simple-template.docx"),
|
||||
patches: {
|
||||
table: {
|
||||
type: PatchType.DOCUMENT,
|
||||
children: [
|
||||
new Table({
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Item")] }),
|
||||
new TableCell({ children: [new Paragraph("Price")] }),
|
||||
],
|
||||
}),
|
||||
new TableRow({
|
||||
children: [
|
||||
new TableCell({ children: [new Paragraph("Widget")] }),
|
||||
new TableCell({ children: [new Paragraph("$9.99")] }),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
## Preserving Styles
|
||||
|
||||
Set `keepOriginalStyles: true` to preserve the formatting of the placeholder text:
|
||||
|
||||
```ts
|
||||
patchDocument({
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { patchDocument, PatchType, TextRun } from "docx";
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("template.docx"),
|
||||
data: fs.readFileSync("./demo/assets/simple-template-3.docx"),
|
||||
keepOriginalStyles: true, // Preserve template formatting
|
||||
patches: {
|
||||
// ...
|
||||
salutation: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [new TextRun("Mr.")],
|
||||
},
|
||||
"first-name": {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [new TextRun("John")],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
## Headers and Footers
|
||||
|
||||
Placeholders in headers and footers are also replaced:
|
||||
|
||||
```ts
|
||||
header_title: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [new TextRun("Company Report 2024")],
|
||||
},
|
||||
footer_text: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [new TextRun("Confidential")],
|
||||
}
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { patchDocument, PatchType, TextRun } from "docx";
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("./demo/assets/simple-template.docx"),
|
||||
patches: {
|
||||
header_adjective: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [new TextRun("great header")],
|
||||
},
|
||||
footer_text: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
children: [new TextRun("Confidential")],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
fs.writeFileSync("My Document.docx", doc);
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
Invoice template:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { ExternalHyperlink, ImageRun, Paragraph, patchDocument, PatchType, Table, TableCell, TableRow, TextRun } from "docx";
|
||||
import { Document, Packer, Paragraph, patchDocument, PatchType, Table, TableCell, TableRow, TextRun } from "docx";
|
||||
|
||||
// Invoice data
|
||||
const invoice = {
|
||||
@@ -212,9 +305,24 @@ const invoice = {
|
||||
total: 95.0,
|
||||
};
|
||||
|
||||
patchDocument({
|
||||
// The template, made here as it would be in Word
|
||||
const template = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph("Invoice {{invoice_number}}"),
|
||||
new Paragraph("Date: {{invoice_date}}"),
|
||||
new Paragraph("Bill to: {{customer_name}}"),
|
||||
new Paragraph("{{line_items}}"),
|
||||
new Paragraph("Total: {{total}}"),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const doc = await patchDocument({
|
||||
outputType: "nodebuffer",
|
||||
data: fs.readFileSync("invoice-template.docx"),
|
||||
data: await Packer.toBuffer(template), // or fs.readFileSync("invoice-template.docx")
|
||||
patches: {
|
||||
invoice_number: {
|
||||
type: PatchType.PARAGRAPH,
|
||||
@@ -264,9 +372,9 @@ patchDocument({
|
||||
],
|
||||
},
|
||||
},
|
||||
}).then((doc) => {
|
||||
fs.writeFileSync("invoice-output.docx", doc);
|
||||
});
|
||||
|
||||
fs.writeFileSync("invoice-output.docx", doc);
|
||||
```
|
||||
|
||||
## Tips
|
||||
|
||||
+127
-67
@@ -10,7 +10,7 @@ Similar to `Text Frames`, but the difference being that it is `VML` `Shape` base
|
||||
|
||||
Create a text box with basic content:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun, Textbox } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -46,25 +46,45 @@ const doc = new Document({
|
||||
|
||||
### Fixed Size
|
||||
|
||||
```ts
|
||||
new Textbox({
|
||||
children: [new Paragraph("Fixed size textbox")],
|
||||
style: {
|
||||
width: "200pt",
|
||||
height: "100pt",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, Textbox } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Textbox({
|
||||
children: [new Paragraph("Fixed size textbox")],
|
||||
style: {
|
||||
width: "200pt",
|
||||
height: "100pt",
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Auto Height
|
||||
|
||||
```ts
|
||||
new Textbox({
|
||||
children: [new Paragraph("Auto height based on content")],
|
||||
style: {
|
||||
width: "200pt",
|
||||
height: "auto",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, Textbox } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Textbox({
|
||||
children: [new Paragraph("Auto height based on content")],
|
||||
style: {
|
||||
width: "200pt",
|
||||
height: "auto",
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -72,14 +92,24 @@ new Textbox({
|
||||
|
||||
Align the textbox horizontally:
|
||||
|
||||
```ts
|
||||
new Textbox({
|
||||
alignment: "center",
|
||||
children: [new Paragraph("Centered textbox")],
|
||||
style: {
|
||||
width: "200pt",
|
||||
height: "auto",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, Textbox } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Textbox({
|
||||
alignment: "center",
|
||||
children: [new Paragraph("Centered textbox")],
|
||||
style: {
|
||||
width: "200pt",
|
||||
height: "auto",
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -93,17 +123,27 @@ Available alignment values:
|
||||
|
||||
A text box can also be one of a paragraph's children, such as after some text. It is then part of that paragraph, and its own paragraph options, such as `alignment`, don't apply:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("See the note: "),
|
||||
new Textbox({
|
||||
children: [new Paragraph("A note")],
|
||||
style: {
|
||||
width: "200pt",
|
||||
height: "auto",
|
||||
},
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun, Textbox } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("See the note: "),
|
||||
new Textbox({
|
||||
children: [new Paragraph("A note")],
|
||||
style: {
|
||||
width: "200pt",
|
||||
height: "auto",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
@@ -112,20 +152,30 @@ new Paragraph({
|
||||
|
||||
Text boxes can contain multiple paragraphs:
|
||||
|
||||
```ts
|
||||
new Textbox({
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Title",
|
||||
heading: HeadingLevel.HEADING_2,
|
||||
}),
|
||||
new Paragraph("First paragraph of content."),
|
||||
new Paragraph("Second paragraph of content."),
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph, Textbox } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Textbox({
|
||||
children: [
|
||||
new Paragraph({
|
||||
text: "Title",
|
||||
heading: HeadingLevel.HEADING_2,
|
||||
}),
|
||||
new Paragraph("First paragraph of content."),
|
||||
new Paragraph("Second paragraph of content."),
|
||||
],
|
||||
style: {
|
||||
width: "300pt",
|
||||
height: "auto",
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
style: {
|
||||
width: "300pt",
|
||||
height: "auto",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
@@ -133,28 +183,38 @@ new Textbox({
|
||||
|
||||
Apply formatting to text within the textbox:
|
||||
|
||||
```ts
|
||||
new Textbox({
|
||||
children: [
|
||||
new Paragraph({
|
||||
alignment: AlignmentType.CENTER,
|
||||
```ts live
|
||||
import { AlignmentType, Document, Paragraph, TextRun, Textbox } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Important Notice",
|
||||
bold: true,
|
||||
size: 28,
|
||||
new Textbox({
|
||||
children: [
|
||||
new Paragraph({
|
||||
alignment: AlignmentType.CENTER,
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Important Notice",
|
||||
bold: true,
|
||||
size: 28,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
alignment: AlignmentType.CENTER,
|
||||
children: [new TextRun("This is highlighted information")],
|
||||
}),
|
||||
],
|
||||
style: {
|
||||
width: "250pt",
|
||||
height: "auto",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
alignment: AlignmentType.CENTER,
|
||||
children: [new TextRun("This is highlighted information")],
|
||||
}),
|
||||
},
|
||||
],
|
||||
style: {
|
||||
width: "250pt",
|
||||
height: "auto",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
@@ -162,8 +222,8 @@ new Textbox({
|
||||
|
||||
Sidebar callout box:
|
||||
|
||||
```ts
|
||||
import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TextRun, Textbox } from "docx";
|
||||
```ts live
|
||||
import { AlignmentType, Document, Packer, Paragraph, TextRun, Textbox } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const doc = new Document({
|
||||
|
||||
+84
-51
@@ -61,28 +61,38 @@ To make a `Text Frame`, add the `frame` property on a paragraph. Frames support
|
||||
|
||||
Position a frame using exact coordinates relative to the anchor:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
frame: {
|
||||
type: "absolute",
|
||||
position: {
|
||||
x: 1000,
|
||||
y: 3000,
|
||||
```ts live
|
||||
import { BorderStyle, Document, FrameAnchorType, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
frame: {
|
||||
type: "absolute",
|
||||
position: {
|
||||
x: 1000,
|
||||
y: 3000,
|
||||
},
|
||||
width: 4000,
|
||||
height: 1000,
|
||||
anchor: {
|
||||
horizontal: FrameAnchorType.MARGIN,
|
||||
vertical: FrameAnchorType.MARGIN,
|
||||
},
|
||||
},
|
||||
border: {
|
||||
top: { color: "auto", space: 1, style: BorderStyle.SINGLE, size: 6 },
|
||||
bottom: { color: "auto", space: 1, style: BorderStyle.SINGLE, size: 6 },
|
||||
left: { color: "auto", space: 1, style: BorderStyle.SINGLE, size: 6 },
|
||||
right: { color: "auto", space: 1, style: BorderStyle.SINGLE, size: 6 },
|
||||
},
|
||||
children: [new TextRun("Hello World"), new TextRun({ text: "Foo Bar", bold: true })],
|
||||
}),
|
||||
],
|
||||
},
|
||||
width: 4000,
|
||||
height: 1000,
|
||||
anchor: {
|
||||
horizontal: FrameAnchorType.MARGIN,
|
||||
vertical: FrameAnchorType.MARGIN,
|
||||
},
|
||||
},
|
||||
border: {
|
||||
top: { color: "auto", space: 1, value: "single", size: 6 },
|
||||
bottom: { color: "auto", space: 1, value: "single", size: 6 },
|
||||
left: { color: "auto", space: 1, value: "single", size: 6 },
|
||||
right: { color: "auto", space: 1, value: "single", size: 6 },
|
||||
},
|
||||
children: [new TextRun("Hello World"), new TextRun({ text: "Foo Bar", bold: true })],
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -90,23 +100,33 @@ new Paragraph({
|
||||
|
||||
Position a frame using alignment values instead of exact coordinates:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
frame: {
|
||||
type: "alignment",
|
||||
alignment: {
|
||||
x: HorizontalPositionAlign.CENTER,
|
||||
y: VerticalPositionAlign.TOP,
|
||||
```ts live
|
||||
import { Document, FrameAnchorType, FrameWrap, HorizontalPositionAlign, Paragraph, TextRun, VerticalPositionAlign } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
frame: {
|
||||
type: "alignment",
|
||||
alignment: {
|
||||
x: HorizontalPositionAlign.CENTER,
|
||||
y: VerticalPositionAlign.TOP,
|
||||
},
|
||||
width: 4000,
|
||||
height: 1000,
|
||||
anchor: {
|
||||
horizontal: FrameAnchorType.PAGE,
|
||||
vertical: FrameAnchorType.PAGE,
|
||||
},
|
||||
wrap: FrameWrap.AROUND,
|
||||
},
|
||||
children: [new TextRun("Centered at top of page")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
width: 4000,
|
||||
height: 1000,
|
||||
anchor: {
|
||||
horizontal: FrameAnchorType.PAGE,
|
||||
vertical: FrameAnchorType.PAGE,
|
||||
},
|
||||
wrap: FrameWrap.AROUND,
|
||||
},
|
||||
children: [new TextRun("Centered at top of page")],
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -114,21 +134,34 @@ new Paragraph({
|
||||
|
||||
Create a decorative large initial letter using the `dropCap` and `lines` properties:
|
||||
|
||||
```ts
|
||||
new Paragraph({
|
||||
frame: {
|
||||
type: "absolute",
|
||||
position: { x: 0, y: 0 },
|
||||
width: 1440,
|
||||
height: 1440,
|
||||
anchor: {
|
||||
horizontal: FrameAnchorType.TEXT,
|
||||
vertical: FrameAnchorType.TEXT,
|
||||
```ts live
|
||||
import { Document, DropCapType, FrameAnchorType, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
frame: {
|
||||
type: "absolute",
|
||||
position: { x: 0, y: 0 },
|
||||
width: 1440,
|
||||
height: 1440,
|
||||
anchor: {
|
||||
horizontal: FrameAnchorType.TEXT,
|
||||
vertical: FrameAnchorType.TEXT,
|
||||
},
|
||||
dropCap: DropCapType.DROP,
|
||||
lines: 3,
|
||||
},
|
||||
children: [new TextRun({ text: "O", size: 72 })],
|
||||
}),
|
||||
new Paragraph(
|
||||
"nce upon a time, there was a paragraph that began with a large letter. The letter dropped down three lines into the text, and the rest of the paragraph flowed around it, the way the first page of a chapter in a book often begins.",
|
||||
),
|
||||
],
|
||||
},
|
||||
dropCap: DropCapType.DROP,
|
||||
lines: 3,
|
||||
},
|
||||
children: [new TextRun({ text: "O", size: 72 })],
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+331
-79
@@ -4,11 +4,19 @@
|
||||
|
||||
You can add multiple `text runs` in `Paragraphs`. This is the most verbose way of writing a `Paragraph` but it is also the most flexible:
|
||||
|
||||
```ts
|
||||
import { Paragraph, TextRun } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const paragraph = new Paragraph({
|
||||
children: [new TextRun("My awesome text here for my university dissertation"), new TextRun("Foo Bar")],
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun("My awesome text here for my university dissertation"), new TextRun("Foo Bar")],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -20,19 +28,47 @@ More info [here](https://english.stackexchange.com/questions/97081/what-is-the-t
|
||||
|
||||
### Bold
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "Foo Bar",
|
||||
bold: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Foo Bar",
|
||||
bold: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Italics
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "Foo Bar",
|
||||
italics: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "Foo Bar",
|
||||
italics: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -49,51 +85,121 @@ Underline has a few options
|
||||
|
||||
**Example:**
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "and then underlined ",
|
||||
underline: {
|
||||
type: UnderlineType.DOUBLE,
|
||||
color: "990011",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun, UnderlineType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "and then underlined ",
|
||||
underline: {
|
||||
type: UnderlineType.DOUBLE,
|
||||
color: "990011",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
To do a simple vanilla underline:
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "and then underlined ",
|
||||
underline: {},
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "and then underlined ",
|
||||
underline: {},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Emphasis Mark
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "and then emphasis mark",
|
||||
emphasisMark: {},
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "and then emphasis mark",
|
||||
emphasisMark: {},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Shading and Highlighting
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "shading",
|
||||
shading: {
|
||||
type: ShadingType.REVERSE_DIAGONAL_STRIPE,
|
||||
color: "00FFFF",
|
||||
fill: "FF0000",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, ShadingType, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "shading",
|
||||
shading: {
|
||||
type: ShadingType.REVERSE_DIAGONAL_STRIPE,
|
||||
color: "00FFFF",
|
||||
fill: "FF0000",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "highlighting",
|
||||
highlight: "yellow",
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "highlighting",
|
||||
highlight: "yellow",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -101,55 +207,141 @@ See [demo/text/highlighting-text.ts](https://github.com/dolanmiu/docx/blob/maste
|
||||
|
||||
### Strike through
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "strike",
|
||||
strike: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "strike",
|
||||
strike: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Double strike through
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "doubleStrike",
|
||||
doubleStrike: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "doubleStrike",
|
||||
doubleStrike: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Superscript
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "superScript",
|
||||
superScript: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Normal text and "),
|
||||
new TextRun({
|
||||
text: "superScript",
|
||||
superScript: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Subscript
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "subScript",
|
||||
subScript: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Normal text and "),
|
||||
new TextRun({
|
||||
text: "subScript",
|
||||
subScript: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### All Capitals
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "allCaps",
|
||||
allCaps: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "allCaps",
|
||||
allCaps: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Small Capitals
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "smallCaps",
|
||||
smallCaps: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "smallCaps",
|
||||
smallCaps: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -159,19 +351,49 @@ You may want to hide your text in your document.
|
||||
|
||||
`Vanish` should affect the normal display of text, but an application may have settings to force hidden text to be displayed.
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "This text will be hidden",
|
||||
vanish: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("This text is shown. "),
|
||||
new TextRun({
|
||||
text: "This text will be hidden",
|
||||
vanish: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
`SpecVanish` was typically used to ensure that a paragraph style can be applied to a part of a paragraph, and still appear as in the Table of Contents (which in previous word processors would ignore the use of the style if it were being used as a character style).
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "This text will be hidden forever.",
|
||||
specVanish: true,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("This text is shown. "),
|
||||
new TextRun({
|
||||
text: "This text will be hidden forever.",
|
||||
specVanish: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -179,18 +401,48 @@ const text = new TextRun({
|
||||
|
||||
Sometimes you would want to put text underneath another line of text but inside the same paragraph.
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "break",
|
||||
break: 1,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Text before the break"),
|
||||
new TextRun({
|
||||
text: "break",
|
||||
break: 1,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
Adding two breaks:
|
||||
|
||||
```ts
|
||||
const text = new TextRun({
|
||||
text: "break",
|
||||
break: 2,
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun("Text before the break"),
|
||||
new TextRun({
|
||||
text: "break",
|
||||
break: 2,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
+52
-11
@@ -6,8 +6,8 @@ Every document `docx` writes has a theme (`word/theme/theme1.xml`): Office's the
|
||||
|
||||
## A theme of your own
|
||||
|
||||
```ts
|
||||
import { Document } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
theme: {
|
||||
@@ -15,7 +15,30 @@ const doc = new Document({
|
||||
colors: { dark2: "1B3A4B", accent1: "1F6F8B", accent2: "E07A5F" },
|
||||
fonts: { headings: "Cambria", body: "Calibri" },
|
||||
},
|
||||
sections: [],
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "In the theme's font for headings, and accent 1",
|
||||
font: { theme: "headings" },
|
||||
color: { theme: "accent1" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: "In the theme's font for body text, and accent 2",
|
||||
font: { theme: "body" },
|
||||
color: { theme: "accent2" },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -54,7 +77,9 @@ Colors and fonts that aren't given are Office's.
|
||||
|
||||
A run's or a style's `font` can be one of the theme's fonts: `{ theme: "headings" }` or `{ theme: "body" }`. It's the theme's font for every script, as Word's own styles use it.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, HeadingLevel, Paragraph, TextRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
theme: { fonts: { headings: "Cambria", body: "Calibri" } },
|
||||
styles: {
|
||||
@@ -85,7 +110,9 @@ Wherever text, underlines, borders and shading take a color, they can take one o
|
||||
|
||||
`lighter` and `darker` make the color lighter or darker, from 0 (unchanged) to 100 (white or black), as Word's color menus do: "Blue, Accent 1, Lighter 80%" is `{ theme: "accent1", lighter: 80 }`, and "Blue, Accent 1, Darker 25%" is `{ theme: "accent1", darker: 25 }`.
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { BorderStyle, Document, HeadingLevel, Paragraph, ShadingType, TextRun, UnderlineType } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
theme: { colors: { accent1: "1F6F8B" } },
|
||||
styles: {
|
||||
@@ -96,6 +123,7 @@ const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun("A heading in accent 1, darker 25%")] }),
|
||||
new Paragraph({
|
||||
// A rule under the paragraph, and a light background
|
||||
border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: { theme: "accent1" } } },
|
||||
@@ -130,14 +158,27 @@ Word writes a theme color with the color it comes to, for applications that don'
|
||||
|
||||
Shapes from `docx/shapes` can be filled and outlined in the theme's colors, lighter or darker if you like, as Word's color menus offer them. See [Theme colours](usage/shapes.md#theme-colours).
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Paragraph } from "docx";
|
||||
import { ShapeRun } from "docx/shapes";
|
||||
|
||||
new ShapeRun({
|
||||
type: "roundedRectangle",
|
||||
transformation: { width: 120, height: 60 },
|
||||
fill: { theme: "accent1", lighter: 80 },
|
||||
line: { theme: "accent1", darker: 25 },
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ShapeRun({
|
||||
type: "roundedRectangle",
|
||||
transformation: { width: 120, height: 60 },
|
||||
fill: { theme: "accent1", lighter: 80 },
|
||||
line: { theme: "accent1", darker: 25 },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+131
-35
@@ -19,8 +19,8 @@ In a page without a bundler, load `dist/watermarks.umd.cjs` after `dist/index.um
|
||||
|
||||
## Text Watermark
|
||||
|
||||
```ts
|
||||
import { Document, Header, Packer, Paragraph } from "docx";
|
||||
```ts live
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
import { TextWatermark } from "docx/watermarks";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -61,22 +61,62 @@ By default the text is drawn diagonally across the page in semi-transparent silv
|
||||
|
||||
### Customising the Text
|
||||
|
||||
```ts
|
||||
new TextWatermark({
|
||||
text: "CONFIDENTIAL",
|
||||
font: "Arial",
|
||||
color: "FF0000",
|
||||
opacity: 0.3,
|
||||
bold: true,
|
||||
```ts live
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
import { TextWatermark } from "docx/watermarks";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: new Header({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextWatermark({
|
||||
text: "CONFIDENTIAL",
|
||||
font: "Arial",
|
||||
color: "FF0000",
|
||||
opacity: 0.3,
|
||||
bold: true,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Horizontal Layout
|
||||
|
||||
```ts
|
||||
new TextWatermark({
|
||||
text: "SAMPLE",
|
||||
layout: "horizontal",
|
||||
```ts live
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
import { TextWatermark } from "docx/watermarks";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: new Header({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextWatermark({
|
||||
text: "SAMPLE",
|
||||
layout: "horizontal",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -84,19 +124,39 @@ new TextWatermark({
|
||||
|
||||
Word stretches watermark text to fill the shape, so the shape's width and height control how large the text appears. Because `docx` cannot measure fonts, the default height is estimated from the text length so that the letters keep their proportions. Set `width` and `height` explicitly to take full control:
|
||||
|
||||
```ts
|
||||
new TextWatermark({
|
||||
text: "DRAFT",
|
||||
width: 400,
|
||||
height: 100,
|
||||
```ts live
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
import { TextWatermark } from "docx/watermarks";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: new Header({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextWatermark({
|
||||
text: "DRAFT",
|
||||
width: 400,
|
||||
height: 100,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Image Watermark
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Header, Packer, Paragraph } from "docx";
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
import { ImageWatermark } from "docx/watermarks";
|
||||
|
||||
const doc = new Document({
|
||||
@@ -109,7 +169,7 @@ const doc = new Document({
|
||||
children: [
|
||||
new ImageWatermark({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./logo.png"),
|
||||
data: fs.readFileSync("./demo/assets/images/dog.png"),
|
||||
transformation: {
|
||||
width: 400,
|
||||
height: 400,
|
||||
@@ -140,12 +200,33 @@ The image is centred on the page and, by default, washed out so that the documen
|
||||
|
||||
### Full-Strength Image
|
||||
|
||||
```ts
|
||||
new ImageWatermark({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./logo.png"),
|
||||
transformation: { width: 300, height: 300 },
|
||||
washout: false,
|
||||
```ts live
|
||||
import * as fs from "fs";
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
import { ImageWatermark } from "docx/watermarks";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: new Header({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new ImageWatermark({
|
||||
type: "png",
|
||||
data: fs.readFileSync("./demo/assets/images/dog.png"),
|
||||
transformation: { width: 300, height: 300 },
|
||||
washout: false,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -153,7 +234,10 @@ new ImageWatermark({
|
||||
|
||||
Watermarks live in headers, so they follow the header rules. Use a `first` header to watermark only the cover page, or omit the watermark from the `first` header to leave the cover page clean:
|
||||
|
||||
```ts
|
||||
```ts live
|
||||
import { Document, Header, Paragraph } from "docx";
|
||||
import { TextWatermark } from "docx/watermarks";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
@@ -172,7 +256,7 @@ const doc = new Document({
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [/* ... */],
|
||||
children: [new Paragraph("Cover page"), new Paragraph({ text: "Second page, with the watermark", pageBreakBefore: true })],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -184,12 +268,24 @@ Each section has its own headers, so different sections can carry different wate
|
||||
|
||||
The watermark is an inline element, so it can share a paragraph with ordinary header content:
|
||||
|
||||
```ts
|
||||
new Header({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextWatermark({ text: "DRAFT" }), new TextRun("Company Name")],
|
||||
}),
|
||||
```ts live
|
||||
import { Document, Header, Paragraph, TextRun } from "docx";
|
||||
import { TextWatermark } from "docx/watermarks";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: new Header({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextWatermark({ text: "DRAFT" }), new TextRun("Company Name")],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children: [new Paragraph("Document content")],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
+179
-79
@@ -24,8 +24,8 @@ Use `WpsShapeRun` when you need fills, outlines, rotation, or precise positionin
|
||||
|
||||
A `WpsShapeRun` is added as a child of a `Paragraph`, similar to `ImageRun`:
|
||||
|
||||
```ts
|
||||
import { Document, Paragraph, TextRun, WpsShapeRun } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, WpsShapeRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
@@ -66,15 +66,29 @@ const doc = new Document({
|
||||
|
||||
Controls the size, offset, rotation, and flip of the text box. Dimensions are in **pixels** (converted to EMUs internally at 1px = 9525 EMUs).
|
||||
|
||||
```ts
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Rotated text box")],
|
||||
transformation: {
|
||||
width: 300,
|
||||
height: 150,
|
||||
rotation: 45, // degrees
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, WpsShapeRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Rotated text box")],
|
||||
transformation: {
|
||||
width: 300,
|
||||
height: 150,
|
||||
rotation: 45, // degrees
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -90,23 +104,37 @@ new WpsShapeRun({
|
||||
|
||||
By default, a `WpsShapeRun` is rendered inline. Add the `floating` property to anchor it at a specific position on the page. Offset values are in EMUs (1 inch = 914400 EMUs).
|
||||
|
||||
```ts
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Floating text box")],
|
||||
transformation: {
|
||||
width: 200,
|
||||
height: 100,
|
||||
},
|
||||
floating: {
|
||||
zIndex: 10,
|
||||
horizontalPosition: {
|
||||
offset: 1014400,
|
||||
```ts live
|
||||
import { Document, Paragraph, WpsShapeRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Floating text box")],
|
||||
transformation: {
|
||||
width: 200,
|
||||
height: 100,
|
||||
},
|
||||
floating: {
|
||||
zIndex: 10,
|
||||
horizontalPosition: {
|
||||
offset: 1014400,
|
||||
},
|
||||
verticalPosition: {
|
||||
offset: 1014400,
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
verticalPosition: {
|
||||
offset: 1014400,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -118,15 +146,29 @@ Set a background color using `solidFill`:
|
||||
|
||||
### RGB Color
|
||||
|
||||
```ts
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Red background")],
|
||||
transformation: { width: 200, height: 100 },
|
||||
solidFill: {
|
||||
type: "rgb",
|
||||
value: "FF0000", // hex color
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, WpsShapeRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Red background")],
|
||||
transformation: { width: 200, height: 100 },
|
||||
solidFill: {
|
||||
type: "rgb",
|
||||
value: "FF0000", // hex color
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -134,17 +176,29 @@ new WpsShapeRun({
|
||||
|
||||
Use theme colors instead of hardcoded values:
|
||||
|
||||
```ts
|
||||
import { SchemeColor } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, SchemeColor, WpsShapeRun } from "docx";
|
||||
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Themed background")],
|
||||
transformation: { width: 200, height: 100 },
|
||||
solidFill: {
|
||||
type: "scheme",
|
||||
value: SchemeColor.ACCENT1,
|
||||
},
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Themed background")],
|
||||
transformation: { width: 200, height: 100 },
|
||||
solidFill: {
|
||||
type: "scheme",
|
||||
value: SchemeColor.ACCENT1,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -156,27 +210,61 @@ Add a border/outline to the text box:
|
||||
|
||||
### Solid Outline
|
||||
|
||||
```ts
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Bordered text box")],
|
||||
transformation: { width: 200, height: 100 },
|
||||
outline: {
|
||||
type: "solidFill",
|
||||
solidFillType: "rgb",
|
||||
value: "0000FF",
|
||||
width: 9525, // width in EMUs (9525 = 1px)
|
||||
cap: "ROUND",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, WpsShapeRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Bordered text box")],
|
||||
transformation: { width: 200, height: 100 },
|
||||
outline: {
|
||||
type: "solidFill",
|
||||
solidFillType: "rgb",
|
||||
value: "0000FF",
|
||||
width: 9525, // width in EMUs (9525 = 1px)
|
||||
cap: "ROUND",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### No Outline
|
||||
|
||||
```ts
|
||||
outline: {
|
||||
type: "noFill",
|
||||
},
|
||||
```ts live
|
||||
import { Document, Paragraph, WpsShapeRun } from "docx";
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("No outline")],
|
||||
transformation: { width: 200, height: 100 },
|
||||
solidFill: { type: "rgb", value: "DEEAF6" },
|
||||
outline: {
|
||||
type: "noFill",
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
### Outline Options
|
||||
@@ -194,23 +282,35 @@ outline: {
|
||||
|
||||
Configure text layout inside the text box:
|
||||
|
||||
```ts
|
||||
import { VerticalAnchor } from "docx";
|
||||
```ts live
|
||||
import { Document, Paragraph, VerticalAnchor, WpsShapeRun } from "docx";
|
||||
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Centered text")],
|
||||
transformation: { width: 200, height: 200 },
|
||||
bodyProperties: {
|
||||
verticalAnchor: VerticalAnchor.CENTER,
|
||||
margins: {
|
||||
top: 45720, // in EMUs
|
||||
bottom: 45720,
|
||||
left: 91440,
|
||||
right: 91440,
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new WpsShapeRun({
|
||||
type: "wps",
|
||||
children: [new Paragraph("Centered text")],
|
||||
transformation: { width: 200, height: 200 },
|
||||
bodyProperties: {
|
||||
verticalAnchor: VerticalAnchor.CENTER,
|
||||
margins: {
|
||||
top: 45720, // in EMUs
|
||||
bottom: 45720,
|
||||
left: 91440,
|
||||
right: 91440,
|
||||
},
|
||||
noAutoFit: true,
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
noAutoFit: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
@@ -226,8 +326,8 @@ new WpsShapeRun({
|
||||
|
||||
A floating callout box with background fill, outline, and centered text:
|
||||
|
||||
```ts
|
||||
import { AlignmentType, Document, Packer, Paragraph, SchemeColor, TextRun, VerticalAnchor, WpsShapeRun } from "docx";
|
||||
```ts live
|
||||
import { AlignmentType, Document, Packer, Paragraph, TextRun, VerticalAnchor, WpsShapeRun } from "docx";
|
||||
import * as fs from "fs";
|
||||
|
||||
const doc = new Document({
|
||||
|
||||
+29
-8
@@ -11,7 +11,16 @@ import tsEslint from "typescript-eslint";
|
||||
|
||||
const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
{
|
||||
ignores: ["**/vite*.config.ts", "**/dist/**", "**/coverage/**", "**/*.js", "eslint.config.ts", "**/demo/**", "**/scripts/**"],
|
||||
ignores: [
|
||||
"**/vite*.config.ts",
|
||||
"**/dist/**",
|
||||
"docs/live-examples/lib/**",
|
||||
"**/coverage/**",
|
||||
"**/*.js",
|
||||
"eslint.config.ts",
|
||||
"**/demo/**",
|
||||
"**/scripts/**",
|
||||
],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
importX.flatConfigs.recommended,
|
||||
@@ -109,10 +118,13 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
],
|
||||
|
||||
"@typescript-eslint/consistent-type-assertions": "error",
|
||||
"@typescript-eslint/consistent-type-imports": ["error", {
|
||||
prefer: "type-imports",
|
||||
fixStyle: "inline-type-imports",
|
||||
}],
|
||||
"@typescript-eslint/consistent-type-imports": [
|
||||
"error",
|
||||
{
|
||||
prefer: "type-imports",
|
||||
fixStyle: "inline-type-imports",
|
||||
},
|
||||
],
|
||||
"@typescript-eslint/dot-notation": "error",
|
||||
|
||||
"@typescript-eslint/explicit-function-return-type": [
|
||||
@@ -381,7 +393,10 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
paths: [{ name: "docx", message: "docx doesn't import itself by name. Use a path alias such as @file/" }],
|
||||
patterns: [
|
||||
{ group: ["docx/*"], message: "docx doesn't import its optional entries, such as docx/shapes" },
|
||||
{ regex: "(^|/)(shapes|watermarks|charts)(/|$)", message: "docx doesn't import its optional entries, such as docx/shapes" },
|
||||
{
|
||||
regex: "(^|/)(shapes|watermarks|charts)(/|$)",
|
||||
message: "docx doesn't import its optional entries, such as docx/shapes",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -395,7 +410,10 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
"error",
|
||||
{
|
||||
patterns: [
|
||||
{ group: ["@file/*", "@util/*", "@export/*", "@shared", "@shared/*"], message: 'Optional entries import docx from "docx"' },
|
||||
{
|
||||
group: ["@file/*", "@util/*", "@export/*", "@shared", "@shared/*"],
|
||||
message: 'Optional entries import docx from "docx"',
|
||||
},
|
||||
{ regex: "^\\.\\./", message: 'Optional entries import docx from "docx"' },
|
||||
],
|
||||
},
|
||||
@@ -410,7 +428,10 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
|
||||
"error",
|
||||
{
|
||||
patterns: [
|
||||
{ group: ["@file/*", "@util/*", "@export/*", "@shared", "@shared/*"], message: 'Optional entries import docx from "docx"' },
|
||||
{
|
||||
group: ["@file/*", "@util/*", "@export/*", "@shared", "@shared/*"],
|
||||
message: 'Optional entries import docx from "docx"',
|
||||
},
|
||||
{ regex: "^\\.\\./\\.\\./", message: 'Optional entries import docx from "docx"' },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -89,6 +89,7 @@
|
||||
"prettier": "prettier -l \"{src,scripts,demo,docs}/**/*.{ts,html,md}\"",
|
||||
"prettier:fix": "npm run prettier -- --write",
|
||||
"cspell": "cspell \"{src,demo,docs,scripts}/**/*.{ts,scss,html,md}\" && cspell \"./*.*\"",
|
||||
"build.docs": "npm run build && mkdir -p docs/live-examples/lib && cp dist/*.iife.js dist/*.d.ts docs/live-examples/lib/",
|
||||
"serve.docs": "cd docs && docsify serve",
|
||||
"extract": "tsx scripts/extract-document.ts",
|
||||
"check-api": "tsx scripts/check-api.ts",
|
||||
|
||||
Reference in New Issue
Block a user