docs: Improve inline docs and docs website (#3353)

* docs: Improve inline docs and docs website

* Fix lint

* Fix spelling
This commit is contained in:
Dolan
2026-02-14 03:54:25 +00:00
committed by GitHub
parent 3b280589c2
commit 3539c06e92
339 changed files with 15680 additions and 1343 deletions
+19 -3
View File
@@ -4,7 +4,13 @@
"version": "0.2", "version": "0.2",
// language - current active spelling language // language - current active spelling language
"language": "en_US", "language": "en_US",
"dictionaries": ["en_US", "typescript", "softwareTerms", "fonts", "npm"], "dictionaries": [
"en_US",
"typescript",
"softwareTerms",
"fonts",
"npm"
],
// words - list of words to be always considered correct // words - list of words to be always considered correct
"words": [ "words": [
"Abjad", "Abjad",
@@ -14,6 +20,7 @@
"chosung", "chosung",
"clippy", "clippy",
"datas", "datas",
"DCMI",
"dcmitype", "dcmitype",
"dcterms", "dcterms",
"docsify", "docsify",
@@ -55,19 +62,28 @@
"/[^\\s]{40,}/", "/[^\\s]{40,}/",
"/<xsd:.+/>/", "/<xsd:.+/>/",
"/[A-Z_]+ = \".+\"/", "/[A-Z_]+ = \".+\"/",
"/[a-zA-Z0-9]+:[a-zA-Z0-9]+/gi",
"/XmlAttributeComponent<{[^}]+}>/g", "/XmlAttributeComponent<{[^}]+}>/g",
"/xmlKeys = {[^}]+}/g", "/xmlKeys = {[^}]+}/g",
"/\\.to\\.deep\\.equal\\({[^)]+}\\)/g", "/\\.to\\.deep\\.equal\\({[^)]+}\\)/g",
"\\.to\\.include\\.members\\(\\[[^\\]]+]\\)", "\\.to\\.include\\.members\\(\\[[^\\]]+]\\)",
"/new [a-zA-Z]+\\({[^£]+}\\)/g", "/new [a-zA-Z]+\\({[^£]+}\\)/g",
"/<element name=\"[a-z]+\"/gi", "/<element name=\"[a-z]+\"/gi",
"/<xsd:complexType name=\".+\">/",
"/<attribute name=\"[a-z]+\"/gi", "/<attribute name=\"[a-z]+\"/gi",
"/key: \".+\"/" "/key: \".+\"/"
], ],
"ignorePaths": ["package.json", "docs/api", "*.docx", "build"], "ignorePaths": [
"package.json",
"docs/api",
"*.docx",
"build"
],
"allowCompoundWords": true, "allowCompoundWords": true,
// flagWords - list of words to be always considered incorrect // flagWords - list of words to be always considered incorrect
// This is useful for offensive words and common spelling errors. // This is useful for offensive words and common spelling errors.
// For example "hte" should be "the" // For example "hte" should be "the"
"flagWords": ["hte"] "flagWords": [
"hte"
]
} }
+32
View File
@@ -0,0 +1,32 @@
You are a senior TypeScript developer
## Project
TypeScript library for generating .docx files. Declarative API, works in Node.js and browsers.
## OOXML Specification
The `ooxml-schemas/` directory contains the official ISO-IEC29500 OOXML XSD schemas. These are the **golden source of truth** for all OOXML element names, attributes, and structure. Always consult these schemas when implementing or modifying XML generation.
Key schemas:
- `wml.xsd` - WordprocessingML (main document structure)
- `dml-main.xsd` - DrawingML (images, shapes)
- `shared-math.xsd` - Math equations
## Code Style
- TypeScript with strict mode
- Path aliases: `@file/`, `@export/`, `@util/`
- Functional style preferred (see eslint-plugin-functional)
- Classes extend `XmlComponent` for XML elements
## Testing
Uses **Vitest**. Tests are co-located with source files as `*.spec.ts`.
**Requirements:**
- Test the XML output structure, not just that code runs
- Cover edge cases and option combinations
- Use descriptive test names that explain expected behavior
+1 -1
View File
@@ -41,7 +41,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
with: with:
node-version: "22.x" node-version: "24.x"
registry-url: https://registry.npmjs.org/ registry-url: https://registry.npmjs.org/
- run: npm ci --force - run: npm ci --force
- run: npm publish - run: npm publish
+2 -1
View File
@@ -2,4 +2,5 @@ trailingComma: all
printWidth: 140 printWidth: 140
tabWidth: 4 tabWidth: 4
arrowParens: always arrowParens: always
bracketSpacing: true bracketSpacing: true
proseWrap: preserve
+25
View File
@@ -0,0 +1,25 @@
You are a senior TypeScript developer.
## Project
TypeScript library for generating .docx files. Declarative API, works in Node.js and browsers.
## OOXML Specification
`ooxml-schemas/` contains official ISO-IEC29500 OOXML XSD schemas - the **golden source of truth**. Always reference these when implementing XML elements.
- `wml.xsd` - WordprocessingML (documents)
- `dml-main.xsd` - DrawingML (images/shapes)
- `shared-math.xsd` - Math
## Code Conventions
- Path aliases: `@file/`, `@export/`, `@util/`
- Classes extend `XmlComponent` for XML elements
- Use `Formatter` to convert components to XML tree
**Best practices:**
- Verify XML output structure matches OOXML spec
- Test option combinations and edge cases
- Descriptive test names explaining behavior
-6
View File
@@ -3,8 +3,6 @@
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, Tab, TabStopPosition, TabStopType, TextRun } from "docx"; import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, Tab, TabStopPosition, TabStopType, TextRun } from "docx";
// tslint:disable:no-shadowed-variable
const PHONE_NUMBER = "07534563401"; const PHONE_NUMBER = "07534563401";
const PROFILE_URL = "https://www.linkedin.com/in/dolan1"; const PROFILE_URL = "https://www.linkedin.com/in/dolan1";
const EMAIL = "docx@com"; const EMAIL = "docx@com";
@@ -165,7 +163,6 @@ const achievements: Achievement[] = [
]; ];
class DocumentCreator { class DocumentCreator {
// tslint:disable-next-line: typedef
public create([experiences, educations, skills, achievements]: [Experience[], Education[], Skill[], Achievement[]]): Document { public create([experiences, educations, skills, achievements]: [Experience[], Education[], Skill[], Achievement[]]): Document {
const document = new Document({ const document = new Document({
sections: [ sections: [
@@ -311,14 +308,12 @@ class DocumentCreator {
}); });
} }
// tslint:disable-next-line:no-any
public createSkillList(skills: any[]): Paragraph { public createSkillList(skills: any[]): Paragraph {
return new Paragraph({ return new Paragraph({
children: [new TextRun(skills.map((skill) => skill.name).join(", ") + ".")], children: [new TextRun(skills.map((skill) => skill.name).join(", ") + ".")],
}); });
} }
// tslint:disable-next-line:no-any
public createAchievementsList(achievements: any[]): Paragraph[] { public createAchievementsList(achievements: any[]): Paragraph[] {
return achievements.map( return achievements.map(
(achievement) => (achievement) =>
@@ -341,7 +336,6 @@ class DocumentCreator {
return text.split("\n\n"); return text.split("\n\n");
} }
// tslint:disable-next-line:no-any
public createPositionDateText(startDate: any, endDate: any, isCurrent: boolean): string { public createPositionDateText(startDate: any, endDate: any, isCurrent: boolean): string {
const startDateText = this.getMonthFromInt(startDate.month) + ". " + startDate.year; const startDateText = this.getMonthFromInt(startDate.month) + ". " + startDate.year;
const endDateText = isCurrent ? "Present" : `${this.getMonthFromInt(endDate.month)}. ${endDate.year}`; const endDateText = isCurrent ? "Present" : `${this.getMonthFromInt(endDate.month)}. ${endDate.year}`;
+25 -13
View File
@@ -1,4 +1,26 @@
# Welcome # Welcome to docx
## What is docx?
**docx** is a TypeScript/JavaScript library for generating Word documents (.docx files) programmatically. It provides a declarative API that works seamlessly in both Node.js and browser environments.
## Why docx?
- **Declarative API** - Define what you want (objects/config), not how to build it step-by-step
- **TypeScript First** - Full type definitions with IntelliSense support
- **Universal** - Works in Node.js, browsers, and serverless environments
- **No Dependencies** - Zero external runtime dependencies
- **Full Featured** - Tables, images, headers, footers, styles, and more
## Quick Navigation
| I want to... | Go to... |
| ------------------------- | --------------------------------------------------------------- |
| Get started quickly | [Quickstart Guide](quickstart.md) |
| Learn a specific feature | [Usage Guides](#usage-guides) |
| See working examples | [Demo Files](https://github.com/dolanmiu/docx/tree/master/demo) |
| Browse the API | [API Documentation](https://docx.js.org/api/) |
| Modify existing documents | [Patcher](usage/patcher.md) |
## Installation ## Installation
@@ -15,7 +37,7 @@ const docx = require("docx");
```ts ```ts
import * as docx from "docx"; import * as docx from "docx";
// or // or
import { ... } from "docx"; import { Document, Packer, Paragraph, TextRun } from "docx";
``` ```
## Basic Usage ## Basic Usage
@@ -24,22 +46,15 @@ import { ... } from "docx";
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, TextRun } from "docx"; import { Document, Packer, Paragraph, TextRun } from "docx";
// Documents contain sections, you can have multiple sections per document, go here to learn more about sections
// This simple example will only contain one section
const doc = new Document({ const doc = new Document({
sections: [ sections: [
{ {
properties: {},
children: [ children: [
new Paragraph({ new Paragraph({
children: [ children: [
new TextRun("Hello World"), new TextRun("Hello World"),
new TextRun({ new TextRun({
text: "Foo Bar", text: " - Bold text",
bold: true,
}),
new TextRun({
text: "\tGithub is the best",
bold: true, bold: true,
}), }),
], ],
@@ -49,12 +64,9 @@ const doc = new Document({
], ],
}); });
// Used to export the file into a .docx file
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer); fs.writeFileSync("My Document.docx", buffer);
}); });
// Done! A file called 'My Document.docx' will be in your file system.
``` ```
<p align="center"> <p align="center">
+3 -3
View File
@@ -2,9 +2,9 @@
> Easily generate and modify .docx files with JS/TS. Works for Node and on the Browser. :100: > Easily generate and modify .docx files with JS/TS. Works for Node and on the Browser. :100:
- Simple, declarative API - Simple, declarative API
- 80+ usage examples - 80+ usage examples
- Battle tested, mature, 100% coverage (yes, every line is tested) - Battle tested, mature, 100% coverage (yes, every line is tested)
[GitHub](https://github.com/dolanmiu/docx) [GitHub](https://github.com/dolanmiu/docx)
[Get Started](#Welcome) [Get Started](#Welcome)
+50 -39
View File
@@ -1,49 +1,60 @@
- [Getting Started](/) - Getting Started
- [Home](/)
- [Quickstart Guide](quickstart.md)
- Examples - Examples
- [Demos](https://github.com/dolanmiu/docx/tree/master/demo)
- [Demos](https://github.com/dolanmiu/docx/tree/master/demo) - API
- [Documentation](https://docx.js.org/api/)
- API - Core Concepts
- [Document](usage/document.md)
- [Sections](usage/sections.md)
- [Convenience Functions](usage/convenience-functions.md)
- [Documentation](https://docx.js.org/api/) - Content Elements
- [Paragraph](usage/paragraph.md)
- [Text Frames](usage/text-frames.md)
- [Symbols](usage/symbols.md)
- [Text](usage/text.md)
- [Images](usage/images.md)
- [Tables](usage/tables.md)
- [Bullet Points](usage/bullet-points.md)
- [Numbering](usage/numbering.md)
- [Hyperlinks](usage/hyperlinks.md)
- [Bookmarks](usage/bookmarks.md)
- [Checkboxes](usage/checkboxes.md)
- [Text Box](usage/text-box.md)
- Usage - Page Layout
- [Page Layout](usage/page-layout.md)
- [Headers & Footers](usage/headers-and-footers.md)
- [Page Numbers](usage/page-numbers.md)
- [Columns](usage/columns.md)
- [Line Numbers](usage/line-numbers.md)
- [Document](usage/document.md) - Advanced Features
- [Sections](usage/sections.md) - [Table of Contents](usage/table-of-contents.md)
- [Paragraph](usage/paragraph.md) - [Tabs](usage/tabs.md)
- [Text Frames](usage/text-frames.md) - [Change Tracking](usage/change-tracking.md)
- [Symbols](usage/symbols.md) - [Math](usage/math.md)
- [Text](usage/text.md) - [Comments](usage/comments.md)
- [Images](usage/images.md) - [Footnotes](usage/footnotes.md)
- [Headers & Footers](usage/headers-and-footers.md) - [Fields](usage/fields.md)
- [Bullet Points](usage/bullet-points.md) - [Fonts](usage/fonts.md)
- [Hyperlinks](usage/hyperlinks.md) - Styling
- [Numbering](usage/numbering.md) - [Styling with JS](usage/styling-with-js.md)
- [Tables](usage/tables.md) - [Styling with XML](usage/styling-with-xml.md)
- [Tabs](usage/tabs.md)
- [Table of Contents](usage/table-of-contents.md)
- [Page Numbers](usage/page-numbers.md)
- [Change Tracking](usage/change-tracking.md)
- [Math](usage/math.md)
- [Comments](usage/comments.md)
- [Footnotes](usage/footnotes.md)
- [Fields](usage/fields.md)
- Styling
- [Styling with JS](usage/styling-with-js.md)
- [Styling with XML](usage/styling-with-xml.md)
- Exporting - Exporting
- [Packers](usage/packers.md)
- [Packers](usage/packers.md) - Templates & Patching
- [Patcher](usage/patcher.md)
- [Templates](usage/templates.md)
- Modifying Existing Documents - Practical Guides
- [Troubleshooting](troubleshooting.md)
- [Patcher](usage/patcher.md) - [Contribution Guidelines](contribution-guidelines.md)
- Utility
- [Convenience functions](usage/convenience-functions.md)
- [Contribution Guidelines](contribution-guidelines.md)
+5 -7
View File
@@ -6,9 +6,7 @@
// http://officeopenxml.com/WPdocument.php // http://officeopenxml.com/WPdocument.php
``` ```
<!-- cSpell:ignore datypic --> It can be a link to `officeopenxml.com` etc.
It can be a link to `officeopenxml.com` or `datypic.com` etc.
It could also be a reference to the official ECMA-376 standard: https://www.ecma-international.org/publications-and-standards/standards/ecma-376/ It could also be a reference to the official ECMA-376 standard: https://www.ecma-international.org/publications-and-standards/standards/ecma-376/
- Include a portion of the schema as a comment for cross reference. For example: - Include a portion of the schema as a comment for cross reference. For example:
@@ -113,10 +111,10 @@ Using `type` aliases in TypeScript offers several advantages over `interfaces`:
- **Flexibility with Complex Types**: `type` supports defining unions, intersections, and other complex type constructs that `interfaces` cannot handle. For example: - **Flexibility with Complex Types**: `type` supports defining unions, intersections, and other complex type constructs that `interfaces` cannot handle. For example:
```typescript ```typescript
type StringOrNumber = string | number; type StringOrNumber = string | number;
type Combined = TypeA & TypeB; type Combined = TypeA & TypeB;
``` ```
- **Support for Primitive Types**: `type` can alias primitive types (e.g., `type ID = string`), while `interfaces` are limited to object shapes. - **Support for Primitive Types**: `type` can alias primitive types (e.g., `type ID = string`), while `interfaces` are limited to object shapes.
- **Tuple and Array Types**: `type` allows defining tuples and specific array types easily (e.g., `type Point = [number, number]`), which `interfaces` cannot represent. - **Tuple and Array Types**: `type` allows defining tuples and specific array types easily (e.g., `type Point = [number, number]`), which `interfaces` cannot represent.
+1 -1
View File
@@ -1,4 +1,4 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
+191
View File
@@ -0,0 +1,191 @@
# Quickstart Guide
Get up and running with docx in under 5 minutes.
**In this guide:**
- Install docx
- Create your first document
- Add text, tables, and images
- Export in multiple formats
## Installation
```terminal
npm install --save docx
```
## Your First Document
Create a "Hello World" document in just a few lines:
```ts
import { Document, Packer, Paragraph, TextRun } from "docx";
import * as fs from "fs";
const doc = new Document({
sections: [
{
// Documents are organized into sections
children: [
new Paragraph({
children: [new TextRun("Hello World!")],
}),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
```
That's it! Run this code to create your first Word document.
## Adding Common Elements
### 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,
}),
],
});
```
See the [Text guide](usage/text.md) for all formatting options.
### Headings
```ts
import { HeadingLevel } from "docx";
new Paragraph({
text: "My Heading",
heading: HeadingLevel.HEADING_1,
});
```
### 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 },
}),
];
```
See the [Bullet Points guide](usage/bullet-points.md) for more options.
### Tables
```ts
import { Table, TableRow, TableCell } from "docx";
new Table({
rows: [
new TableRow({
children: [new TableCell({ children: [new Paragraph("Cell 1")] }), new TableCell({ children: [new Paragraph("Cell 2")] })],
}),
],
});
```
See the [Tables guide](usage/tables.md) for advanced table features.
### Images
```ts
import { ImageRun } from "docx";
new Paragraph({
children: [
new ImageRun({
type: "png",
data: fs.readFileSync("./image.png"),
transformation: {
width: 200,
height: 200,
},
}),
],
});
```
See the [Images guide](usage/images.md) for positioning and wrapping options.
## Export Options
### Node.js - Save to File
```ts
import * as fs from "fs";
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("document.docx", buffer);
});
```
### Node.js - Stream
```ts
import * as fs from "fs";
Packer.toStream(doc).then((stream) => {
stream.pipe(fs.createWriteStream("document.docx"));
});
```
### Browser - Download
```ts
import { saveAs } from "file-saver";
Packer.toBlob(doc).then((blob) => {
saveAs(blob, "document.docx");
});
```
### Base64 String
```ts
Packer.toBase64String(doc).then((base64) => {
console.log(base64);
});
```
See the [Packers guide](usage/packers.md) for all export options.
## Next Steps
Now that you've created your first document, explore these guides:
- **[Document](usage/document.md)** - Document properties and settings
- **[Sections](usage/sections.md)** - Page layouts and breaks
- **[Paragraph](usage/paragraph.md)** - Text formatting and alignment
- **[Tables](usage/tables.md)** - Complex table layouts
- **[Images](usage/images.md)** - Image positioning and wrapping
- **[Headers & Footers](usage/headers-and-footers.md)** - Page headers and footers
- **[Styling](usage/styling-with-js.md)** - Reusable styles
?> Check out the [demo folder](https://github.com/dolanmiu/docx/tree/master/demo) for 90+ working examples covering every feature.
+415
View File
@@ -0,0 +1,415 @@
# Troubleshooting
This guide covers common issues and their solutions when working with docx.
## Quick Index
| Symptom | Go to |
| ------------------------ | ------------------------------------------ |
| File corrupt/won't open | [Document Won't Open](#document-wont-open) |
| Images appear blank | [Images Not Showing](#images-not-showing) |
| Buffer not defined error | [Browser Issues](#browser-issues) |
| Table cells misaligned | [Table Issues](#table-issues) |
| Styles not applying | [Styling Issues](#styling-issues) |
| Memory errors | [Memory Issues](#memory-issues) |
## Document Won't Open
### "The file is corrupt and cannot be opened"
**Cause:** The document was not written correctly, often due to not waiting for the document to finish generating.
**Solutions:**
1. Ensure you're using `await` or `.then()` with `Packer` methods:
```ts
// Correct - using await
const buffer = await Packer.toBuffer(doc);
fs.writeFileSync("document.docx", buffer);
// Correct - using .then()
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("document.docx", buffer);
});
// Wrong - missing await
const buffer = Packer.toBuffer(doc); // Returns a Promise, not a buffer!
fs.writeFileSync("document.docx", buffer);
```
2. In Express.js, ensure the response completes:
```ts
app.get("/download", async (req, res) => {
const doc = new Document({
/* ... */
});
const buffer = await Packer.toBuffer(doc);
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
res.setHeader("Content-Disposition", "attachment; filename=document.docx");
res.send(buffer);
});
```
### "We're sorry. We can't open document.docx"
**Cause:** Invalid XML structure in the document.
**Solutions:**
1. Check for invalid characters in text content:
```ts
// Remove control characters
const cleanText = text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "");
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!
});
```
## Images Not Showing
### Image appears as blank or broken
**Cause:** Incorrect image data or type.
**Solutions:**
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 },
});
```
2. In browsers, ensure proper data conversion:
```ts
// Convert fetch response to ArrayBuffer
const response = await fetch(imageUrl);
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
new ImageRun({
type: "png",
data: buffer,
transformation: { width: 100, height: 100 },
});
```
3. Check image dimensions are specified:
```ts
// Both width and height are required
transformation: {
width: 100, // Required
height: 100, // Required
}
```
## Browser Issues
### "Buffer is not defined"
**Cause:** Node.js `Buffer` is not available in browsers.
**Solutions:**
1. Use a polyfill (a library that provides missing browser functionality) like `buffer`:
```ts
import { Buffer } from "buffer";
window.Buffer = Buffer;
```
2. Or configure your bundler (Webpack/Vite) to include polyfills
3. For Vite, use `vite-plugin-node-polyfills`
### Blob download not working
**Cause:** Incorrect blob handling.
**Solution:**
```ts
import { saveAs } from "file-saver";
Packer.toBlob(doc).then((blob) => {
saveAs(blob, "document.docx");
});
```
## Table Issues
### Table cells not aligning
**Cause:** Missing or inconsistent column widths.
**Solution:**
```ts
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")],
}),
],
}),
],
});
```
### Merged cells not working
**Cause:** Incorrect merge configuration.
**Solution:**
```ts
// Horizontal merge
new TableCell({
columnSpan: 2, // Span 2 columns
children: [new Paragraph("Merged horizontally")],
}),
// Vertical merge
new TableCell({
rowSpan: 2, // Span 2 rows
children: [new Paragraph("Merged vertically")],
}),
```
## Styling Issues
### Styles not applying
**Cause:** Style not defined in the document styles.
**Solution:**
```ts
const doc = new Document({
styles: {
paragraphStyles: [
{
id: "MyStyle",
name: "My Custom Style",
basedOn: "Normal",
next: "Normal",
run: {
bold: true,
color: "FF0000",
},
},
],
},
sections: [
{
children: [
new Paragraph({
text: "Styled text",
style: "MyStyle", // Reference by id
}),
],
},
],
});
```
### Font not displaying
**Cause:** Font not available on the target system.
**Solution:** Embed the font:
```ts
import { CharacterSet, Document } from "docx";
const doc = new Document({
fonts: [
{
name: "CustomFont",
data: fs.readFileSync("./font.ttf"),
characterSet: CharacterSet.ANSI,
},
],
// ...
});
```
## Headers and Footers
### Header/footer not appearing on all pages
**Cause:** Multiple sections with different headers.
**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: [
/* ... */
],
},
];
```
### Different first page header not working
**Cause:** Missing `titlePage` property.
**Solution:**
```ts
sections: [
{
properties: {
titlePage: true, // Required for different first page
},
headers: {
default: normalHeader,
first: firstPageHeader, // Only shows with titlePage: true
},
children: [
/* ... */
],
},
];
```
## Page Numbers
### Page numbers not updating
**Cause:** Page numbers are fields that update when the document opens.
**Note:** This is expected behavior. Page numbers will update when opened in Word.
### Page X of Y not working
**Solution:**
```ts
import { PageNumber, NumberFormat } from "docx";
new Paragraph({
children: [
new TextRun("Page "),
new TextRun({
children: [PageNumber.CURRENT],
}),
new TextRun(" of "),
new TextRun({
children: [PageNumber.TOTAL_PAGES],
}),
],
});
```
## Table of Contents
### TOC shows "Update this table"
**Cause:** TOC fields need updating in Word.
**Solution:**
1. Set `updateFields: true` in document features:
```ts
const doc = new Document({
features: {
updateFields: true,
},
// ...
});
```
2. When opening in Word, right-click the TOC and select "Update Field"
## Memory Issues
### "JavaScript heap out of memory"
**Cause:** Processing very large documents or many images.
**Solutions:**
1. Increase Node.js memory:
```bash
node --max-old-space-size=4096 script.js
```
2. Process images before embedding:
```ts
// Resize images before adding to document
const sharp = require("sharp");
const resized = await sharp(imagePath).resize(800, 600).toBuffer();
```
3. Generate documents in batches
## TypeScript Errors
### "Property does not exist on type"
**Cause:** Using incorrect property names or types.
**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
});
```
## Getting Help
If you can't find a solution here:
1. Check the [Demo files](https://github.com/dolanmiu/docx/tree/master/demo) for working examples
2. Search [GitHub Issues](https://github.com/dolanmiu/docx/issues) for similar problems
3. Open a new issue with:
- docx version number
- Node.js version
- Minimal reproducible code example
- Expected vs actual behavior
+188
View File
@@ -0,0 +1,188 @@
# Bookmarks
!> Bookmarks require an understanding of [Paragraphs](usage/paragraph.md) and [Hyperlinks](usage/hyperlinks.md).
Bookmarks allow you to create anchors within a document that can be referenced by internal hyperlinks, enabling navigation within the same document.
## Creating Bookmarks
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";
const bookmarkedHeading = new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [
new Bookmark({
id: "chapter1",
children: [new TextRun("Chapter 1: Introduction")],
}),
],
});
```
### Bookmark Options
| Property | Type | Notes | Description |
| -------- | ----------- | -------- | ---------------------------------- |
| id | `string` | Required | Unique identifier for the anchor |
| children | `TextRun[]` | Required | Content to display at the bookmark |
## Internal Hyperlinks
Use `InternalHyperlink` to create clickable links that navigate to bookmarks:
```ts
import { InternalHyperlink, Paragraph, TextRun } from "docx";
const linkToChapter = new Paragraph({
children: [
new InternalHyperlink({
children: [
new TextRun({
text: "Go to Chapter 1",
style: "Hyperlink",
}),
],
anchor: "chapter1",
}),
],
});
```
?> Use `style: "Hyperlink"` on your TextRun to apply the default hyperlink styling (blue text, underlined).
## Page References
Get the page number where a bookmark appears using `PageReference`:
```ts
import { PageReference, Paragraph, TextRun } from "docx";
const pageRef = new Paragraph({
children: [new TextRun("See Chapter 1 on page "), new PageReference("chapter1")],
});
```
This creates dynamic text like "See Chapter 1 on page 5" that updates automatically.
## Complete Example
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";
const doc = new Document({
sections: [
{
children: [
// Table of Contents
new Paragraph({
text: "Table of Contents",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph({
children: [
new InternalHyperlink({
children: [new TextRun({ text: "Chapter 1", style: "Hyperlink" })],
anchor: "chapter1",
}),
new TextRun(" - page "),
new PageReference("chapter1"),
],
}),
new Paragraph({
children: [
new InternalHyperlink({
children: [new TextRun({ text: "Chapter 2", style: "Hyperlink" })],
anchor: "chapter2",
}),
new TextRun(" - page "),
new PageReference("chapter2"),
],
}),
// Page break to Chapter 1
new Paragraph({ children: [new PageBreak()] }),
// Chapter 1
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [
new Bookmark({
id: "chapter1",
children: [new TextRun("Chapter 1: Getting Started")],
}),
],
}),
new Paragraph("Content of chapter 1..."),
// Page break to Chapter 2
new Paragraph({ children: [new PageBreak()] }),
// Chapter 2
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [
new Bookmark({
id: "chapter2",
children: [new TextRun("Chapter 2: Advanced Topics")],
}),
],
}),
new Paragraph("Content of chapter 2..."),
],
},
],
});
```
## Using in Headers and Footers
Bookmarks and internal hyperlinks work in headers and footers too:
```ts
import { Footer, InternalHyperlink, Paragraph, TextRun } from "docx";
const footer = new Footer({
children: [
new Paragraph({
children: [
new InternalHyperlink({
children: [new TextRun({ text: "Back to Top", style: "Hyperlink" })],
anchor: "documentStart",
}),
],
}),
],
});
```
## 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",
}),
],
anchor: "myBookmark",
});
```
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/21-bookmarks.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/21-bookmarks.ts_
+208 -22
View File
@@ -1,32 +1,218 @@
# Bullet Points # Bullet Points
!> Bullet Points requires an understanding of [Paragraphs](usage/paragraph.md). !> Bullet Points require an understanding of [Paragraphs](usage/paragraph.md).
## Example
To make a bullet point, simply make a paragraph into a bullet point: ## Basic Bullet Points
Create bullet points by adding the `bullet` property to paragraphs:
```ts ```ts
const doc = new Document({ const doc = new Document({
sections: [{ sections: [
children: [ {
new Paragraph({ children: [
text: "Bullet points", new Paragraph({
bullet: { text: "First item",
level: 0 // How deep you want the bullet to be. Maximum level is 9 bullet: {
} level: 0,
}), },
new Paragraph({ }),
text: "Are awesome", new Paragraph({
bullet: { text: "Second item",
level: 0 bullet: {
} level: 0,
}) },
], }),
}] new Paragraph({
text: "Third item",
bullet: {
level: 0,
},
}),
],
},
],
}); });
``` ```
### This will produce: ### Output:
- Bullet points - First item
- Are awesome - Second item
- Third item
## Multi-Level Lists
Create nested lists using different `level` values (0-9):
```ts
const doc = new Document({
sections: [
{
children: [
new Paragraph({
text: "Main item 1",
bullet: { level: 0 },
}),
new Paragraph({
text: "Sub-item 1.1",
bullet: { level: 1 },
}),
new Paragraph({
text: "Sub-item 1.2",
bullet: { level: 1 },
}),
new Paragraph({
text: "Deep item 1.2.1",
bullet: { level: 2 },
}),
new Paragraph({
text: "Main item 2",
bullet: { level: 0 },
}),
],
},
],
});
```
### Output:
- Main item 1
- Sub-item 1.1
- Sub-item 1.2
- Deep item 1.2.1
- Main item 2
## Bullet Options
| Property | Type | Notes | Description |
| -------- | -------- | -------- | ----------------------- |
| level | `number` | Required | Indentation level (0-9) |
## Programmatic List Generation
Generate bullet lists from data:
```ts
const items = ["Apple", "Banana", "Cherry", "Date"];
const doc = new Document({
sections: [
{
children: items.map(
(item) =>
new Paragraph({
text: item,
bullet: { level: 0 },
}),
),
},
],
});
```
## Nested Data Structures
Create hierarchical lists from nested data:
```ts
interface MenuItem {
name: string;
children?: MenuItem[];
}
const menu: MenuItem[] = [
{
name: "Fruits",
children: [{ name: "Apple" }, { name: "Orange" }],
},
{
name: "Vegetables",
children: [{ name: "Carrot" }, { name: "Broccoli" }],
},
];
function createBulletItems(items: MenuItem[], level: number = 0): Paragraph[] {
const paragraphs: Paragraph[] = [];
for (const item of items) {
paragraphs.push(
new Paragraph({
text: item.name,
bullet: { level },
}),
);
if (item.children) {
paragraphs.push(...createBulletItems(item.children, level + 1));
}
}
return paragraphs;
}
const doc = new Document({
sections: [
{
children: createBulletItems(menu),
},
],
});
```
## Mixing Bullets with Other Content
Combine bullet points with regular paragraphs:
```ts
const doc = new Document({
sections: [
{
children: [
new Paragraph({
text: "Shopping List",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph("Items to buy:"),
new Paragraph({
text: "Milk",
bullet: { level: 0 },
}),
new Paragraph({
text: "Bread",
bullet: { level: 0 },
}),
new Paragraph({
text: "Eggs",
bullet: { level: 0 },
}),
new Paragraph("Remember to check expiration dates!"),
],
},
],
});
```
## Styled Bullet Items
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")],
});
```
## Related Topics
- **[Numbering](usage/numbering.md)** - For numbered lists with custom formats
- **[Paragraph](usage/paragraph.md)** - For paragraph formatting options
- **[Styling with JS](usage/styling-with-js.md)** - For custom bullet styles
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/3-numbering-and-bullet-points.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/3-numbering-and-bullet-points.ts_
+6 -6
View File
@@ -9,7 +9,7 @@ const paragraph = new Paragraph({
children: [ children: [
new TextRun("This is a simple demo "), new TextRun("This is a simple demo "),
new TextRun({ new TextRun({
text: "on how to " text: "on how to ",
}), }),
new InsertedTextRun({ new InsertedTextRun({
text: "mark a text as an insertion ", text: "mark a text as an insertion ",
@@ -22,7 +22,7 @@ const paragraph = new Paragraph({
id: 1, id: 1,
author: "Firstname Lastname", author: "Firstname Lastname",
date: "2020-10-06T09:00:00Z", date: "2020-10-06T09:00:00Z",
}) }),
], ],
}); });
``` ```
@@ -43,7 +43,7 @@ const paragraph = new Paragraph({
id: 0, id: 0,
author: "Firstname Lastname", author: "Firstname Lastname",
date: "2020-10-06T09:00:00Z", date: "2020-10-06T09:00:00Z",
}) }),
], ],
}); });
``` ```
@@ -71,6 +71,6 @@ new TextRun({
author: "Firstname Lastname", author: "Firstname Lastname",
date: "2020-10-06T09:05:00Z", date: "2020-10-06T09:05:00Z",
bold: false, bold: false,
} },
}).break() }).break();
```` ```
+168
View File
@@ -0,0 +1,168 @@
# Checkboxes
!> Checkboxes require an understanding of [Paragraphs](usage/paragraph.md).
Checkboxes allow you to add interactive checkbox controls to your Word documents. These are commonly used in forms, checklists, and surveys.
?> These checkboxes are interactive in Word - users can click to toggle them on and off.
## Basic Checkbox
Create a simple checkbox:
```ts
import { CheckBox, Document, Paragraph, TextRun } from "docx";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [new CheckBox(), new TextRun(" Unchecked item")],
}),
],
},
],
});
```
## Checked Checkbox
Create a pre-checked checkbox:
```ts
new Paragraph({
children: [new CheckBox({ checked: true }), new TextRun(" Completed task")],
});
```
## Custom Checkbox Symbols
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",
},
});
```
### Common Unicode Values
| Symbol | Unicode | Description |
| -------- | ------- | --------------------- |
| &#x2610; | `2610` | Ballot Box |
| &#x2611; | `2611` | Ballot Box with Check |
| &#x2612; | `2612` | Ballot Box with X |
| &#x2713; | `2713` | Check Mark |
| &#x2717; | `2717` | Ballot X |
## Checkbox Options
| Property | Type | Notes | Description |
| -------------- | ------------- | -------- | ------------------------------------ |
| checked | `boolean` | Optional | Whether the checkbox is checked |
| checkedState | `SymbolState` | Optional | Symbol and font for checked state |
| uncheckedState | `SymbolState` | Optional | Symbol and font for unchecked state |
| alias | `string` | Optional | Accessibility label for the checkbox |
### SymbolState Options
| Property | Type | Notes | Description |
| -------- | -------- | -------- | -------------------------- |
| value | `string` | Required | Unicode hex value |
| font | `string` | Optional | Font to use for the symbol |
## Accessibility
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"),
],
});
```
## Building a Checklist
Create a complete checklist:
```ts
import { CheckBox, Document, Paragraph, TextRun } from "docx";
const tasks = [
{ text: "Review documentation", done: true },
{ text: "Write unit tests", done: true },
{ text: "Deploy to production", done: false },
{ text: "Update README", done: false },
];
const doc = new Document({
sections: [
{
children: tasks.map(
(task) =>
new Paragraph({
children: [new CheckBox({ checked: task.done }), new TextRun(` ${task.text}`)],
}),
),
},
],
});
```
## Form with Multiple Checkboxes
```ts
import { CheckBox, Document, HeadingLevel, Paragraph, TextRun } from "docx";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
text: "Survey Form",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph({
text: "Which features do you use?",
heading: HeadingLevel.HEADING_2,
}),
new Paragraph({
children: [new CheckBox(), new TextRun(" Tables")],
}),
new Paragraph({
children: [new CheckBox(), new TextRun(" Images")],
}),
new Paragraph({
children: [new CheckBox(), new TextRun(" Headers/Footers")],
}),
new Paragraph({
children: [new CheckBox(), new TextRun(" Styles")],
}),
],
},
],
});
```
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/90-check-boxes.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/90-check-boxes.ts_
+223
View File
@@ -0,0 +1,223 @@
# Columns
!> Columns require an understanding of [Sections](usage/sections.md).
Create multi-column layouts like newspapers or newsletters by configuring columns in your section properties.
## Basic Columns
Create equal-width columns:
```ts
import { Document, Paragraph } from "docx";
const doc = new Document({
sections: [
{
properties: {
column: {
count: 2,
space: 708, // Space between columns (~0.5 inches in twips; 1440 twips = 1 inch)
},
},
children: [new Paragraph("This text will flow across two columns...")],
},
],
});
```
## Column Options
| Property | Type | Notes | Description |
| ---------- | ---------- | -------- | -------------------------------- |
| count | `number` | Required | Number of columns |
| space | `number` | Optional | Space between columns (twips) |
| separate | `boolean` | Optional | Draw a line between columns |
| equalWidth | `boolean` | Optional | Whether columns have equal width |
| children | `Column[]` | Optional | Individual column definitions |
## Column Separator
Add a vertical line between columns:
```ts
properties: {
column: {
count: 2,
space: 708,
separate: true, // Adds a line between columns
},
}
```
## Different Width Columns
Create columns with custom widths:
```ts
import { Column, Document, Paragraph } from "docx";
const doc = new Document({
sections: [
{
properties: {
column: {
count: 2,
space: 720,
equalWidth: false,
children: [
new Column({ width: 2880, space: 720 }), // Narrow column
new Column({ width: 5760 }), // Wide column
],
},
},
children: [new Paragraph("Content flows through unequal columns...")],
},
],
});
```
### Column Class Options
| Property | Type | Notes | Description |
| -------- | -------- | -------- | ----------------------- |
| width | `number` | Required | Column width (twips) |
| space | `number` | Optional | Space after this column |
## Column Breaks
Force content to the next column using `ColumnBreak`:
```ts
import { ColumnBreak, Document, Paragraph, TextRun } from "docx";
const doc = new Document({
sections: [
{
properties: {
column: {
count: 2,
space: 708,
},
},
children: [
new Paragraph({
children: [new TextRun("This text is in column 1."), new ColumnBreak(), new TextRun("This text is in column 2.")],
}),
],
},
],
});
```
## Three Columns
```ts
properties: {
column: {
count: 3,
space: 708,
},
}
```
## Mixing Column Layouts
Use multiple sections to mix column layouts:
```ts
import { Document, Paragraph, SectionType } from "docx";
const doc = new Document({
sections: [
// Single column section
{
children: [new Paragraph("This is a full-width introduction paragraph.")],
},
// Two column section
{
properties: {
type: SectionType.CONTINUOUS, // Don't start new page
column: {
count: 2,
space: 708,
},
},
children: [new Paragraph("This content flows in two columns...")],
},
// Back to single column
{
properties: {
type: SectionType.CONTINUOUS,
},
children: [new Paragraph("This is a full-width conclusion.")],
},
],
});
```
## Complete Example
Newsletter-style layout with unequal columns:
```ts
import { Column, ColumnBreak, Document, HeadingLevel, Paragraph, TextRun } from "docx";
const doc = new Document({
sections: [
{
properties: {
column: {
count: 2,
space: 720, // 0.5 inches between columns (1440 twips = 1 inch)
separate: true,
equalWidth: false,
children: [
new Column({ width: 3600, space: 720 }), // Narrow column (~2.5 inches)
new Column({ width: 5040 }), // Wide column (~3.5 inches)
],
},
},
children: [
new Paragraph({
text: "Newsletter Title",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph({
children: [
new TextRun("First column content goes here. "),
new TextRun("It will flow naturally within the column width. "),
new TextRun("Add more content as needed."),
],
}),
new Paragraph({
children: [new ColumnBreak()],
}),
new Paragraph({
children: [new TextRun("Second column content starts here. "), new TextRun("This appears in the right column.")],
}),
],
},
],
});
```
## Demos
### Multiple Columns
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/44-multiple-columns.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/44-multiple-columns.ts_
### Column Break
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/67-column-break.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/67-column-break.ts_
### Different Width Columns
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/69-different-width-columns.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/69-different-width-columns.ts_
+221 -7
View File
@@ -1,17 +1,231 @@
# Comments # Comments
!> Comments requires an understanding of [Sections](usage/sections.md) and [Paragraphs](usage/paragraph.md). !> Comments require an understanding of [Sections](usage/sections.md) and [Paragraphs](usage/paragraph.md).
## Intro Comments allow you to add annotations to specific parts of your document, similar to the review feature in Microsoft Word.
To add comments in `docx`, a `comments` block is specified in the `Document`. This block defines all the comments in your document. Each comment has an `id`, which you then reference later. ## Overview
In the spot you want to add a comment, you simply add a `CommentRangeStart` and a `CommentRangeEnd` to specify where the comment starts and ends. To add comments in `docx`:
Alternatively, you can use `CommentReference` to specify a comment at a specific singular point. 1. Define all comments in the `comments` block of the `Document`
2. Each comment has a unique `id`
3. Mark where comments appear using `CommentRangeStart`, `CommentRangeEnd`, and `CommentReference`
### Example ## Basic Comment
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/73-comments.ts ':include') Add a comment to a range of text:
```ts
import { Comment, 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: [
{
children: [
new Paragraph({
children: [
new TextRun("This is normal text. "),
new CommentRangeStart("0"),
new TextRun("This text has a comment."),
new CommentRangeEnd("0"),
new CommentReference("0"),
],
}),
],
},
],
});
```
## Comment Options
| Property | Type | Notes | Description |
| -------- | ------------- | -------- | ------------------- |
| id | `string` | Required | Unique identifier |
| author | `string` | Optional | Comment author name |
| date | `Date` | Optional | Comment timestamp |
| initials | `string` | Optional | Author initials |
| children | `Paragraph[]` | Required | Comment content |
## 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
],
});
```
## Multiple Comments
Add several comments to a document:
```ts
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: [
{
children: [
new Paragraph({
children: [
new CommentRangeStart("0"),
new TextRun("Text with first comment."),
new CommentRangeEnd("0"),
new CommentReference("0"),
new TextRun(" "),
new CommentRangeStart("1"),
new TextRun("Text with second comment."),
new CommentRangeEnd("1"),
new CommentReference("1"),
],
}),
],
},
],
});
```
## Reply Threads
Create comment replies using the `parentId` property to build a thread:
```ts
comments: {
children: [
new Comment({
id: "0",
author: "Alice",
date: new Date("2024-01-15"),
children: [new Paragraph("Is this correct?")],
}),
new Comment({
id: "1",
author: "Bob",
date: new Date("2024-01-16"),
parentId: "0", // This is a reply to comment "0"
children: [new Paragraph("Yes, I verified it.")],
}),
new Comment({
id: "2",
author: "Alice",
date: new Date("2024-01-17"),
parentId: "0", // Another reply to comment "0"
children: [new Paragraph("Thanks for checking!")],
}),
],
}
```
## 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."),
],
});
```
## Complete Example
Document with review comments:
```ts
import { Comment, CommentRangeEnd, CommentRangeStart, CommentReference, Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx";
import * as fs from "fs";
const doc = new Document({
comments: {
children: [
new Comment({
id: "suggestion",
author: "Editor",
date: new Date(),
children: [new Paragraph("Consider rephrasing this for clarity.")],
}),
new Comment({
id: "fact-check",
author: "Fact Checker",
date: new Date(),
children: [
new Paragraph({
children: [new TextRun({ text: "Verified ", bold: true }), new TextRun("- Source: Annual Report 2023")],
}),
],
}),
],
},
sections: [
{
children: [
new Paragraph({
text: "Quarterly Report",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph({
children: [
new TextRun("Our "),
new CommentRangeStart("suggestion"),
new TextRun("company achieved remarkable growth"),
new CommentRangeEnd("suggestion"),
new CommentReference("suggestion"),
new TextRun(" this quarter. "),
new CommentRangeStart("fact-check"),
new TextRun("Revenue increased by 25%"),
new CommentRangeEnd("fact-check"),
new CommentReference("fact-check"),
new TextRun(" compared to last year."),
],
}),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("document.docx", buffer);
});
```
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/73-comments.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/73-comments.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/73-comments.ts_
+161 -8
View File
@@ -1,22 +1,175 @@
# Convenience functions # Convenience Functions
OOXML and this library mainly uses a unit called twentieths of a point or `twip` for short. a twip is a typographical measurement, defined as 1/20 of a typographical point. One twip is 1/1440 inch, or 17.64 μm. This unit is not intuitive for many users, so some functions were created to help OOXML and this library mainly uses a unit called twentieths of a point or `twip` for short. A twip is a typographical measurement, defined as 1/20 of a typographical point. One twip is 1/1440 inch, or 17.64 micrometers.
More info here: https://en.wikipedia.org/wiki/Twip These functions help convert familiar units to twips.
## Convert Inches to Twip More info: https://en.wikipedia.org/wiki/Twip
## Unit Conversion Functions
### Convert Inches to Twip
```ts ```ts
import { convertInchesToTwip } from "docx"; import { convertInchesToTwip } from "docx";
const twip = convertInchesToTwip(1); // returns 1440 convertInchesToTwip(1); // returns 1440
const twip = convertInchesToTwip(0.5); // returns 720 convertInchesToTwip(0.5); // returns 720
convertInchesToTwip(2); // returns 2880
``` ```
## Convert Millimeters to Twip ### Convert Millimeters to Twip
```ts ```ts
import { convertMillimetersToTwip } from "docx"; import { convertMillimetersToTwip } from "docx";
const twip = convertMillimetersToTwip(50); // returns 2834 convertMillimetersToTwip(25.4); // returns 1440 (1 inch = 25.4mm)
convertMillimetersToTwip(50); // returns 2834
convertMillimetersToTwip(10); // returns 567
``` ```
## Common Use Cases
### Setting Page Margins
```ts
import { Document, convertInchesToTwip } from "docx";
const doc = new Document({
sections: [
{
properties: {
page: {
margin: {
top: convertInchesToTwip(1), // 1 inch
right: convertInchesToTwip(1),
bottom: convertInchesToTwip(1),
left: convertInchesToTwip(1.5), // 1.5 inches for binding
},
},
},
children: [
/* ... */
],
},
],
});
```
### Setting Page Size
```ts
import { Document, convertMillimetersToTwip, PageOrientation } from "docx";
// A4 paper size
const doc = new Document({
sections: [
{
properties: {
page: {
size: {
width: convertMillimetersToTwip(210), // A4 width
height: convertMillimetersToTwip(297), // A4 height
orientation: PageOrientation.PORTRAIT,
},
},
},
children: [
/* ... */
],
},
],
});
```
### Column Spacing
```ts
import { Document, convertMillimetersToTwip } from "docx";
const doc = new Document({
sections: [
{
properties: {
column: {
count: 2,
space: convertMillimetersToTwip(10), // 10mm between columns
},
},
children: [
/* ... */
],
},
],
});
```
### Table Cell Width
```ts
import { Table, TableCell, TableRow, WidthType, convertInchesToTwip } from "docx";
new Table({
rows: [
new TableRow({
children: [
new TableCell({
width: {
size: convertInchesToTwip(2), // 2 inch wide cell
type: WidthType.DXA,
},
children: [new Paragraph("Cell content")],
}),
],
}),
],
});
```
## Quick Reference
### Inches to Twips
| Inches | Twips |
| ------ | ----- |
| 0.25 | 360 |
| 0.5 | 720 |
| 0.75 | 1080 |
| 1 | 1440 |
| 1.5 | 2160 |
| 2 | 2880 |
### Millimeters to Twips (approximate)
| Millimeters | Twips |
| ----------- | ----- |
| 5 | 283 |
| 10 | 567 |
| 15 | 850 |
| 20 | 1134 |
| 25 | 1417 |
| 50 | 2834 |
## EMUs (English Metric Units)
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,
},
}
```
?> Unlike twips, there are currently no built-in conversion functions for EMUs. You can calculate them manually: `inches * 914400` or `mm * 36000`.
## Related Documentation
- [Understanding Units in OOXML](https://startbigthinksmall.wordpress.com/2010/01/04/points-inches-and-emus-measuring-units-in-office-open-xml/)
- [Document](usage/document.md) - Document-level options
- [Page Layout](usage/page-layout.md) - Page size and margins
+118 -3
View File
@@ -5,21 +5,82 @@
To create a new document, it is very easy: To create a new document, it is very easy:
```ts ```ts
const doc = new docx.Document(); const doc = new docx.Document({
sections: [
{
children: [new Paragraph("Hello World")],
},
],
});
``` ```
## Document properties ## Document Properties
You can add properties to the Word document by specifying options, for example: You can add metadata properties to the Word document:
```ts ```ts
const doc = new docx.Document({ const doc = new docx.Document({
creator: "Dolan Miu", creator: "Dolan Miu",
description: "My extremely interesting document", description: "My extremely interesting document",
title: "My Document", title: "My Document",
subject: "Report",
keywords: "report, annual, finance",
sections: [
/* ... */
],
}); });
``` ```
These properties appear in Word's File > Info panel and in file properties.
## Options by Category
### Metadata Properties
| Property | Type | Description |
| -------------- | -------- | ----------------------------- |
| title | `string` | Document title |
| subject | `string` | Document subject |
| creator | `string` | Author name |
| keywords | `string` | Keywords for searching |
| description | `string` | Document description/comments |
| lastModifiedBy | `string` | Last person to modify |
| revision | `number` | Revision number |
### Content Options
| Property | Type | Description |
| --------- | ------------------------------------------- | ----------------- |
| sections | `ISectionOptions[]` | Document sections |
| comments | `ICommentsOptions` | Document comments |
| footnotes | `Record<string, { children: Paragraph[] }>` | Footnotes |
### Styling Options
| Property | Type | Description |
| -------------- | ------------------- | ------------------------ |
| styles | `IStylesOptions` | Custom styles |
| externalStyles | `string` | External XML styles |
| numbering | `INumberingOptions` | Numbering definitions |
| fonts | `FontOptions[]` | Embedded fonts |
| defaultTabStop | `number` | Default tab stop (twips) |
### Document Behavior
| Property | Type | Description |
| -------------------------- | ------------------------------------------------------ | -------------------------- |
| background | `IDocumentBackgroundOptions` | Document background |
| features | `{ trackRevisions?: boolean; updateFields?: boolean }` | Feature flags |
| evenAndOddHeaderAndFooters | `boolean` | Different odd/even headers |
| hyphenation | `IHyphenationOptions` | Hyphenation settings |
### Compatibility
| Property | Type | Description |
| ------------------------ | ----------------------- | -------------------------- |
| compatibility | `ICompatibilityOptions` | Compatibility settings |
| compatabilityModeVersion | `number` | Word version compatibility |
### Full list of options: ### Full list of options:
| Property | Type | Notes | | Property | Type | Notes |
@@ -61,6 +122,60 @@ const doc = new docx.Document({
You can mix and match whatever properties you want, or provide no properties. You can mix and match whatever properties you want, or provide no properties.
### Custom Properties
Add custom metadata properties that appear in Word's document properties:
```ts
const doc = new docx.Document({
customProperties: [
{
name: "Department",
value: "Engineering",
},
{
name: "Project Code",
value: "PRJ-2024-001",
},
{
name: "Approved",
value: true,
},
{
name: "Version",
value: 2.5,
},
],
sections: [
/* ... */
],
});
```
Custom properties support these value types:
- `string` - Text values
- `number` - Numeric values
- `boolean` - True/false values
### Document Features
Enable special features like track changes or field updating:
```ts
const doc = new docx.Document({
features: {
trackRevisions: true, // Enable track changes
updateFields: true, // Update fields (like TOC) when opened
},
sections: [
/* ... */
],
});
```
?> Set `updateFields: true` when using Table of Contents so it updates automatically when the document is opened.
### Units for positioning ### Units for positioning
Various parts of the API require positioning arguments. The units are "20ths of a point" from the [OOXML](http://officeopenxml.com/index.php) specification. Various parts of the API require positioning arguments. The units are "20ths of a point" from the [OOXML](http://officeopenxml.com/index.php) specification.
+12 -12
View File
@@ -8,16 +8,16 @@ There are very complicated fields like the table of contents, but in many cases
Word uses field codes to identify what the result of the field should be. You can find these field codes by adding a field in a document (`Insert -> Quick Parts -> Field...`) and clicking the 'Field codes'-button. Some examples include: Word uses field codes to identify what the result of the field should be. You can find these field codes by adding a field in a document (`Insert -> Quick Parts -> Field...`) and clicking the 'Field codes'-button. Some examples include:
Field type | Example | Description | Field type | Example | Description |
----------- | --------------- | --------------------------------------------------------- | ----------- | --------------- | --------------------------------------------------------------------------------------- |
= (Formula) | `=2*21` | Calculates the result of a formula. You can also use bookmarks as variables, see below. | = (Formula) | `=2*21` | Calculates the result of a formula. You can also use bookmarks as variables, see below. |
Author | `AUTHOR` | Includes the author mentioned in the document properties. | Author | `AUTHOR` | Includes the author mentioned in the document properties. |
CreateDate | `CREATEDATE` | Date the document was created. | CreateDate | `CREATEDATE` | Date the document was created. |
Date | `DATE` | Today's date. | Date | `DATE` | Today's date. |
FileName | `FILENAME \p` | The name of the document. Add `\p` for the complete path. | FileName | `FILENAME \p` | The name of the document. Add `\p` for the complete path. |
Info | `INFO NumWords` | Data from the document properties, e.g. the number of words in the document. | Info | `INFO NumWords` | Data from the document properties, e.g. the number of words in the document. |
NumPages | `NUMPAGES` | Number of pages in the document. | NumPages | `NUMPAGES` | Number of pages in the document. |
UserName | `USERNAME` | Your user name from the Office personalization settings. | UserName | `USERNAME` | Your user name from the Office personalization settings. |
Fields can be added as a child of a paragraph: Fields can be added as a child of a paragraph:
@@ -43,9 +43,9 @@ One type of field is the formula that can be used to do some basic calculations.
const paragraph = new Paragraph({ const paragraph = new Paragraph({
children: [ children: [
new TextRun("Value one is: "), new TextRun("Value one is: "),
new Bookmark({ id: "One", children: [new TextRun("451")]}), new Bookmark({ id: "One", children: [new TextRun("451")] }),
new TextRun(". The second value is: "), new TextRun(". The second value is: "),
new Bookmark({ id: "Two", children: [new TextRun("886")]}), new Bookmark({ id: "Two", children: [new TextRun("886")] }),
new TextRun(". The sum of these values is: "), new TextRun(". The sum of these values is: "),
new SimpleField("=One+Two"), new SimpleField("=One+Two"),
], ],
+239
View File
@@ -0,0 +1,239 @@
# Custom Fonts
Custom fonts allow you to embed fonts directly into your document, ensuring consistent appearance across different systems.
## Embedding Fonts
Embed a font by providing the font data in the `Document` constructor:
```ts
import * as fs from "fs";
import { CharacterSet, Document, Paragraph, TextRun } from "docx";
const fontData = fs.readFileSync("./fonts/MyCustomFont.ttf");
const doc = new Document({
fonts: [
{
name: "MyCustomFont",
data: fontData,
characterSet: CharacterSet.ANSI,
},
],
sections: [
{
children: [
new Paragraph({
children: [
new TextRun({
text: "This text uses a custom font",
font: "MyCustomFont",
}),
],
}),
],
},
],
});
```
## Font Options
| Property | Type | Notes | Description |
| ------------ | -------------- | -------- | -------------------------- |
| name | `string` | Required | Font name to reference |
| data | `Buffer` | Required | Font file data |
| characterSet | `CharacterSet` | Optional | Character set for the font |
## Character Sets
Available character sets:
| Value | Description |
| -------------------------- | ------------------------ |
| `CharacterSet.ANSI` | Standard ANSI characters |
| `CharacterSet.DEFAULT` | Default character set |
| `CharacterSet.SYMBOL` | Symbol characters |
| `CharacterSet.MAC` | Macintosh characters |
| `CharacterSet.SHIFTJIS` | Japanese Shift-JIS |
| `CharacterSet.HANGUL` | Korean Hangul |
| `CharacterSet.JOHAB` | Korean Johab |
| `CharacterSet.GB2312` | Simplified Chinese |
| `CharacterSet.CHINESEBIG5` | Traditional Chinese |
| `CharacterSet.GREEK` | Greek characters |
| `CharacterSet.TURKISH` | Turkish characters |
| `CharacterSet.VIETNAMESE` | Vietnamese characters |
| `CharacterSet.HEBREW` | Hebrew characters |
| `CharacterSet.ARABIC` | Arabic characters |
| `CharacterSet.BALTIC` | Baltic characters |
| `CharacterSet.RUSSIAN` | Cyrillic characters |
| `CharacterSet.THAI` | Thai characters |
| `CharacterSet.EASTEUROPE` | Eastern European |
## Using Custom Fonts
### In TextRun
```ts
new TextRun({
text: "Custom font text",
font: "MyCustomFont",
});
```
### In Paragraph Style
```ts
new Paragraph({
run: {
font: "MyCustomFont",
},
children: [new TextRun("All text in this paragraph uses the custom font")],
});
```
### In Document Styles
```ts
const doc = new Document({
fonts: [{ name: "CustomFont", data: fontData, characterSet: CharacterSet.ANSI }],
styles: {
default: {
document: {
run: {
font: "CustomFont",
},
},
},
},
sections: [
/* ... */
],
});
```
## Multiple Fonts
Embed multiple fonts:
```ts
const doc = new Document({
fonts: [
{
name: "HeadingFont",
data: fs.readFileSync("./fonts/Heading.ttf"),
characterSet: CharacterSet.ANSI,
},
{
name: "BodyFont",
data: fs.readFileSync("./fonts/Body.ttf"),
characterSet: CharacterSet.ANSI,
},
],
sections: [
{
children: [
new Paragraph({
children: [
new TextRun({
text: "Heading",
font: "HeadingFont",
size: 48,
}),
],
}),
new Paragraph({
children: [
new TextRun({
text: "Body text with a different font",
font: "BodyFont",
}),
],
}),
],
},
],
});
```
## Mixing System and Custom Fonts
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",
}),
],
});
```
## Browser Usage
In browsers, convert your font file to a base64 string or ArrayBuffer:
```ts
import { CharacterSet, Document, Packer, Paragraph, TextRun } from "docx";
import { saveAs } from "file-saver";
// Fetch the font file and convert to ArrayBuffer
const response = await fetch("./fonts/MyFont.ttf");
const fontData = await response.arrayBuffer();
const doc = new Document({
fonts: [
{
name: "MyFont",
data: Buffer.from(fontData),
characterSet: CharacterSet.ANSI,
},
],
sections: [
{
children: [
new Paragraph({
children: [
new TextRun({
text: "Text with embedded font",
font: "MyFont",
}),
],
}),
],
},
],
});
// Export the document
Packer.toBlob(doc).then((blob) => {
saveAs(blob, "document.docx");
});
```
## Supported Font Formats
- **TTF** (TrueType Font) - Most common, widely supported
- **OTF** (OpenType Font) - Also supported
?> For best compatibility, use TTF fonts when possible.
## Demo
### Embedding Custom Fonts
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/91-custom-fonts.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/91-custom-fonts.ts_
### Declarative Custom Fonts
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/92-declarative-custom-fonts.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/92-declarative-custom-fonts.ts_
+393 -39
View File
@@ -1,58 +1,412 @@
# Headers and Footers # Headers and Footers
!> Headers and Footers requires an understanding of [Sections](usage/sections.md). !> Headers and Footers require an understanding of [Sections](usage/sections.md).
Every Section has a sections which you can define its Headers and Footers: Every section has headers and footers that appear on each page within that section.
## Basic Headers and Footers
```ts ```ts
import { Document, Footer, Header, Paragraph } from "docx";
const doc = new Document({ const doc = new Document({
sections: [{ sections: [
headers: { {
default: new Header({ // The standard default header on every page or header on odd pages when the 'Different Odd & Even Pages' option is activated headers: {
children: [], default: new Header({
}), children: [new Paragraph("Header text")],
first: new Header({ // The header on first page when the 'Different First Page' option is activated }),
children: [], },
}), footers: {
even: new Header({ // The header on even pages when the 'Different Odd & Even Pages' option is activated default: new Footer({
children: [], children: [new Paragraph("Footer text")],
}), }),
},
children: [new Paragraph("Document content")],
}, },
footers: { ],
default: new Footer({ // The standard default footer on every page or footer on odd pages when the 'Different Odd & Even Pages' option is activated
children: [],
}),
first: new Footer({ // The footer on first page when the 'Different First Page' option is activated
children: [],
}),
even: new Footer({ // The footer on even pages when the 'Different Odd & Even Pages' option is activated
children: [],
}),
},
children: [],
}];
}); });
``` ```
## Example ## Header/Footer Types
Example showing basic header and footer | Type | Description | Requires |
| --------- | --------------------------------------------------- | ---------------------------------- |
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/8-header-footer.ts ':include') | `default` | Standard header/footer on every page (or odd pages) | - |
| `first` | Header/footer on the first page only | `titlePage: true` |
_Source: https://github.com/dolanmiu/docx/blob/master/demo/8-header-footer.ts_ | `even` | Header/footer on even pages | `evenAndOddHeaderAndFooters: true` |
## Different First Page ## Different First Page
To specify `'Different First Page'`, set `titlePage: true` in the sections array as shown below. To have a different header/footer on the first page:
``` ```ts
sections: [ const doc = new Document({
sections: [
{ {
properties: { properties: {
titlePage: true, titlePage: true, // Enable different first page
},
headers: {
default: new Header({
children: [new Paragraph("Header on all pages except first")],
}),
first: new Header({
children: [new Paragraph("Special first page header")],
}),
},
footers: {
default: new Footer({
children: [new Paragraph("Footer on all pages except first")],
}),
first: new Footer({
children: [], // No footer on first page
}),
},
children: [
/* ... */
],
},
],
});
``` ```
## Multiple Headers and Footers ## Different Odd and Even Pages
More headers and footers can be accomplished by creating more `Section`. New headers and footers can be set per `Section` For documents like books with different left/right pages:
```ts
const doc = new Document({
evenAndOddHeaderAndFooters: true, // Enable at document level
sections: [
{
headers: {
default: new Header({
children: [
new Paragraph({
text: "Chapter Title",
alignment: AlignmentType.RIGHT, // Right on odd pages
}),
],
}),
even: new Header({
children: [
new Paragraph({
text: "Book Title",
alignment: AlignmentType.LEFT, // Left on even pages
}),
],
}),
},
children: [
/* ... */
],
},
],
});
```
## Page Numbers in Headers/Footers
Add page numbers using the `PageNumber` class:
```ts
import { AlignmentType, Footer, PageNumber, Paragraph, TextRun } from "docx";
const footer = new Footer({
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new TextRun("Page "),
new TextRun({
children: [PageNumber.CURRENT],
}),
new TextRun(" of "),
new TextRun({
children: [PageNumber.TOTAL_PAGES],
}),
],
}),
],
});
```
### Common Page Number Patterns
**Centered page number:**
```ts
new Footer({
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [new TextRun({ children: [PageNumber.CURRENT] })],
}),
],
});
```
**Right-aligned page number:**
```ts
new Footer({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [new TextRun("Page "), new TextRun({ children: [PageNumber.CURRENT] })],
}),
],
});
```
## Images in Headers/Footers
Add logos or images:
```ts
import { Header, ImageRun, Paragraph } from "docx";
const header = new Header({
children: [
new Paragraph({
children: [
new ImageRun({
type: "png",
data: fs.readFileSync("./logo.png"),
transformation: {
width: 100,
height: 50,
},
}),
],
}),
],
});
```
## Header/Footer Margins
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
},
},
},
headers: {
/* ... */
},
footers: {
/* ... */
},
children: [
/* ... */
],
},
];
```
## Multiple Elements in Headers/Footers
Headers and footers can contain multiple paragraphs, tables, and images:
```ts
const header = new Header({
children: [
new Paragraph({
children: [
new ImageRun({
type: "png",
data: fs.readFileSync("./logo.png"),
transformation: { width: 80, height: 40 },
}),
],
}),
new Paragraph({
text: "Company Name",
alignment: AlignmentType.CENTER,
}),
new Paragraph({
text: "Confidential Document",
alignment: AlignmentType.RIGHT,
}),
],
});
```
## Using Tables for Layout
Create complex header layouts with tables:
```ts
import { AlignmentType, BorderStyle, Header, Paragraph, Table, TableCell, TableRow, WidthType } from "docx";
// Helper to create invisible borders for layout tables
const noBorders = {
top: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
bottom: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
left: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
right: { style: BorderStyle.NONE, size: 0, color: "FFFFFF" },
};
const header = new Header({
children: [
new Table({
width: { size: 100, type: WidthType.PERCENTAGE },
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Left content")],
borders: noBorders,
}),
new TableCell({
children: [
new Paragraph({
text: "Center content",
alignment: AlignmentType.CENTER,
}),
],
borders: noBorders,
}),
new TableCell({
children: [
new Paragraph({
text: "Right content",
alignment: AlignmentType.RIGHT,
}),
],
borders: noBorders,
}),
],
}),
],
}),
],
});
```
## Multiple Sections with Different Headers
Each section can have its own headers and footers:
```ts
const doc = new Document({
sections: [
{
headers: {
default: new Header({
children: [new Paragraph("Chapter 1")],
}),
},
children: [new Paragraph("Chapter 1 content...")],
},
{
headers: {
default: new Header({
children: [new Paragraph("Chapter 2")],
}),
},
children: [new Paragraph("Chapter 2 content...")],
},
],
});
```
## Complete Example
Professional document with company header:
```ts
import { AlignmentType, Document, Footer, Header, ImageRun, PageNumber, Packer, Paragraph, TextRun } from "docx";
import * as fs from "fs";
const doc = new Document({
sections: [
{
properties: {
titlePage: true,
},
headers: {
first: new Header({
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new ImageRun({
type: "png",
data: fs.readFileSync("./logo.png"),
transformation: { width: 150, height: 75 },
}),
],
}),
],
}),
default: new Header({
children: [
new Paragraph({
children: [new TextRun({ text: "Company Name", bold: true }), new TextRun(" | Confidential")],
}),
],
}),
},
footers: {
first: new Footer({
children: [], // No footer on cover page
}),
default: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new TextRun("Page "),
new TextRun({ children: [PageNumber.CURRENT] }),
new TextRun(" of "),
new TextRun({ children: [PageNumber.TOTAL_PAGES] }),
],
}),
],
}),
},
children: [new Paragraph("Document content...")],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("document.docx", buffer);
});
```
## Demos
### Basic Header and Footer
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/8-header-footer.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/8-header-footer.ts_
### Odd/Even Headers and Footers
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/63-odd-even-header-footer.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/63-odd-even-header-footer.ts_
### Header and Footer Margins
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/59-header-footer-margins.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/59-header-footer-margins.ts_
### Images in Header and Footer
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/9-images-in-header-and-footer.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/9-images-in-header-and-footer.ts_
+4
View File
@@ -79,6 +79,10 @@ const paragraph = new Paragraph({
}); });
``` ```
## Related Topics
- **[Bookmarks](usage/bookmarks.md)** - For detailed coverage of bookmarks, internal hyperlinks, and page references
## Styling hyperlinks ## Styling hyperlinks
It is possible to set the style of the text of both internal and external hyperlinks. This can be done applying run formatting on any of the `TextRun` children of the hyperlink. Use the `style: "Hyperlink"` property to show the default link styles, which can be combined with any other style. It is possible to set the style of the text of both internal and external hyperlinks. This can be done applying run formatting on any of the `TextRun` children of the hyperlink. Use the `style: "Hyperlink"` property to show the default link styles, which can be combined with any other style.
+36 -8
View File
@@ -2,6 +2,34 @@
!> Images requires an understanding of [Sections](usage/sections.md) and [Paragraphs](usage/paragraph.md). !> Images requires an understanding of [Sections](usage/sections.md) and [Paragraphs](usage/paragraph.md).
## Common Use Cases
| I want to... | Use | Example |
| -------------------------------------- | ----------------------- | ---------------------------- |
| Insert an image inline with text | Inline (default) | Logo next to company name |
| Position image at specific coordinates | Floating with offset | Letterhead logo at top-right |
| Have text wrap around an image | Floating with wrap | Magazine-style layout |
| Put an image in a table cell | Inline in TableCell | Product catalog |
| Add image to header/footer | Inline in Header/Footer | Company letterhead |
## Inline vs Floating: When to Use Which
**Use Inline when:**
- Image should flow with text
- Image is part of content (diagrams, screenshots)
- Image goes inside tables
- Image in headers/footers
**Use Floating when:**
- Image needs precise positioning
- Text should wrap around image
- Image overlays content (watermarks)
- Complex page layouts
---
To create a `floating` image on top of text: To create a `floating` image on top of text:
```ts ```ts
@@ -27,7 +55,7 @@ By default with no arguments, its an `inline` image:
```ts ```ts
const image = new ImageRun({ const image = new ImageRun({
type: 'gif', type: "gif",
data: fs.readFileSync("./demo/images/pizza.gif"), data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: { transformation: {
width: 100, width: 100,
@@ -85,8 +113,8 @@ const doc = new Document({
Three types of image positioning is supported: Three types of image positioning is supported:
- Floating - Floating
- Inline - Inline
By default, images are exported as `Inline` elements. By default, images are exported as `Inline` elements.
@@ -100,7 +128,7 @@ To change the position the image to be on top of the text, simply add the `float
```ts ```ts
const image = new ImageRun({ const image = new ImageRun({
type: 'png', type: "png",
data: buffer, data: buffer,
transformation: { transformation: {
width: 903, width: 903,
@@ -119,7 +147,7 @@ const image = new ImageRun({
```ts ```ts
const image = new ImageRun({ const image = new ImageRun({
type: 'png', type: "png",
data: buffer, data: buffer,
transformation: { transformation: {
width: 903, width: 903,
@@ -185,7 +213,7 @@ For example:
```ts ```ts
const image = new ImageRun({ const image = new ImageRun({
type: 'gif', type: "gif",
data: fs.readFileSync("./demo/images/pizza.gif"), data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: { transformation: {
width: 200, width: 200,
@@ -234,7 +262,7 @@ For example:
```ts ```ts
const image = new ImageRun({ const image = new ImageRun({
type: 'gif', type: "gif",
data: fs.readFileSync("./demo/images/pizza.gif"), data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: { transformation: {
width: 200, width: 200,
@@ -265,7 +293,7 @@ Specifies common non-visual DrawingML properties. A name, title and description
```ts ```ts
const image = new ImageRun({ const image = new ImageRun({
type: 'gif', type: "gif",
data: fs.readFileSync("./demo/images/pizza.gif"), data: fs.readFileSync("./demo/images/pizza.gif"),
altText: { altText: {
title: "This is an ultimate title", title: "This is an ultimate title",
+178
View File
@@ -0,0 +1,178 @@
# Line Numbers
!> Line Numbers require an understanding of [Sections](usage/sections.md).
Line numbers are useful for legal documents, code listings, scripts, and any document where referencing specific lines is important.
## Basic Line Numbers
Add line numbers to a section:
```ts
import { Document, LineNumberRestartFormat, Paragraph } from "docx";
const doc = new Document({
sections: [
{
properties: {
lineNumbers: {
countBy: 1,
restart: LineNumberRestartFormat.CONTINUOUS,
},
},
children: [new Paragraph("Line 1"), new Paragraph("Line 2"), new Paragraph("Line 3")],
},
],
});
```
## Line Number Options
| Property | Type | Notes | Description |
| -------- | ------------------------- | -------- | -------------------------- |
| countBy | `number` | Optional | Show number every N lines |
| start | `number` | Optional | Starting line number |
| restart | `LineNumberRestartFormat` | Optional | When to restart numbering |
| distance | `number` | Optional | Distance from text (twips) |
## Restart Options
Control when line numbers restart:
```ts
import { LineNumberRestartFormat } 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,
}
```
## Count Interval
Show line numbers at specific intervals:
```ts
// Show every 5th line number (5, 10, 15...)
lineNumbers: {
countBy: 5,
restart: LineNumberRestartFormat.CONTINUOUS,
}
```
## Starting Number
Start from a specific line number:
```ts
lineNumbers: {
countBy: 1,
start: 100, // First line is 100
restart: LineNumberRestartFormat.CONTINUOUS,
}
```
## Suppressing Line Numbers
Suppress line numbers for specific paragraphs:
```ts
new Paragraph({
text: "This paragraph will not have a line number",
suppressLineNumbers: true,
});
```
This is useful for headings, titles, or any content that shouldn't be numbered.
## Complete Example
Legal document with line numbers:
```ts
import { Document, HeadingLevel, LineNumberRestartFormat, Packer, Paragraph } from "docx";
const doc = new Document({
sections: [
{
properties: {
lineNumbers: {
countBy: 1,
restart: LineNumberRestartFormat.NEW_PAGE,
},
},
children: [
new Paragraph({
text: "AGREEMENT",
heading: HeadingLevel.HEADING_1,
suppressLineNumbers: true, // Don't number the title
}),
new Paragraph("This Agreement is entered into as of the date last signed below."),
new Paragraph("WHEREAS, Party A desires to engage Party B for services;"),
new Paragraph("WHEREAS, Party B has the expertise to provide such services;"),
new Paragraph({
text: "TERMS AND CONDITIONS",
heading: HeadingLevel.HEADING_2,
suppressLineNumbers: true, // Don't number section headers
}),
new Paragraph("1. Party B shall provide consulting services as requested by Party A."),
new Paragraph("2. Payment shall be made within 30 days of invoice receipt."),
new Paragraph("3. This agreement may be terminated by either party with 30 days notice."),
],
},
],
});
```
## Multiple Sections with Different Settings
```ts
import { Document, LineNumberRestartFormat, Paragraph, SectionType } from "docx";
const doc = new Document({
sections: [
// First section - no line numbers
{
children: [new Paragraph("Introduction without line numbers...")],
},
// Second section - numbered lines
{
properties: {
type: SectionType.NEXT_PAGE,
lineNumbers: {
countBy: 1,
restart: LineNumberRestartFormat.CONTINUOUS,
},
},
children: [new Paragraph("This section has line numbers...")],
},
],
});
```
## Demos
### Basic Line Numbers
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/40-line-numbers.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/40-line-numbers.ts_
### Line Number Suppression
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/70-line-numbers-suppression.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/70-line-numbers-suppression.ts_
+1 -3
View File
@@ -95,7 +95,7 @@ Along with `reference` and `level`, the `numbering` object supports an optional
| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| reference | `string` | The numbering style reference, must match a defined config | | reference | `string` | The numbering style reference, must match a defined config |
| level | `number` | The list level (0 = top-level, 1 = sub-list, etc.) | | level | `number` | The list level (0 = top-level, 1 = sub-list, etc.) |
| instance | `number` | *(Optional)* Identifies the instance of the list. Lists with the same `instance` (or none) continue numbering across paragraphs. A new `instance` value restarts numbering from `1`. | | instance | `number` | _(Optional)_ Identifies the instance of the list. Lists with the same `instance` (or none) continue numbering across paragraphs. A new `instance` value restarts numbering from `1`. |
Example: Example:
@@ -116,8 +116,6 @@ new Paragraph({
}); });
``` ```
## Un-ordered lists / Bullet points ## 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`:
+1 -1
View File
@@ -79,7 +79,7 @@ Packer.toString(doc, true, overrides).then((string) => {
You can also use the lower-level `Packer.pack` method to export to any specified type. You can also use the lower-level `Packer.pack` method to export to any specified type.
```ts ```ts
Packer.pack(doc, 'string').then((string) => { Packer.pack(doc, "string").then((string) => {
console.log(string); console.log(string);
}); });
``` ```
+264
View File
@@ -0,0 +1,264 @@
# Page Layout
!> Page Layout requires an understanding of [Sections](usage/sections.md).
Page layout options control the physical appearance of your document pages, including size, margins, orientation, and borders.
## Page Size
Set custom page dimensions:
```ts
import { Document, PageOrientation, Paragraph, convertMillimetersToTwip } from "docx";
const doc = new Document({
sections: [
{
properties: {
page: {
size: {
width: convertMillimetersToTwip(210), // A4 width
height: convertMillimetersToTwip(297), // A4 height
},
},
},
children: [new Paragraph("A4 sized page")],
},
],
});
```
### Common Page Sizes
| Size | Width (mm) | Height (mm) |
| ------ | ---------- | ----------- |
| Letter | 216 | 279 |
| Legal | 216 | 356 |
| A4 | 210 | 297 |
| A3 | 297 | 420 |
| A5 | 148 | 210 |
## Page Orientation
Set portrait or landscape orientation:
```ts
import { Document, PageOrientation, Paragraph, convertMillimetersToTwip } from "docx";
// Landscape A4
// Note: For landscape, swap width and height values so the larger dimension becomes the width
const doc = new Document({
sections: [
{
properties: {
page: {
size: {
orientation: PageOrientation.LANDSCAPE,
width: convertMillimetersToTwip(297), // A4 height becomes landscape width
height: convertMillimetersToTwip(210), // A4 width becomes landscape height
},
},
},
children: [new Paragraph("Landscape page")],
},
],
});
```
?> 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.
## Page Margins
Set margins for the page:
```ts
import { Document, Paragraph, convertInchesToTwip } from "docx";
const doc = new Document({
sections: [
{
properties: {
page: {
margin: {
top: convertInchesToTwip(1),
right: convertInchesToTwip(1),
bottom: convertInchesToTwip(1),
left: convertInchesToTwip(1.5), // Extra for binding
},
},
},
children: [new Paragraph("Page with custom margins")],
},
],
});
```
### Margin Options
| Property | Type | Description |
| -------- | -------- | ---------------------------------------------------------------- |
| top | `number` | Top margin (twips) |
| right | `number` | Right margin |
| bottom | `number` | Bottom margin |
| left | `number` | Left margin |
| header | `number` | Header margin |
| footer | `number` | Footer margin |
| gutter | `number` | Gutter margin (extra space for binding in double-sided printing) |
## Page Borders
Add borders around pages:
```ts
import { BorderStyle, Document, PageBorderDisplay, PageBorderOffsetFrom, Paragraph } from "docx";
// Note: Border size is measured in 1/8 points (so size: 8 = 1pt, size: 16 = 2pt)
const doc = new Document({
sections: [
{
properties: {
page: {
borders: {
pageBorderTop: {
style: BorderStyle.SINGLE,
size: 8, // 1pt (8 eighths of a point)
color: "000000",
},
pageBorderRight: {
style: BorderStyle.SINGLE,
size: 8,
color: "000000",
},
pageBorderBottom: {
style: BorderStyle.DOUBLE,
size: 16, // 2pt
color: "FF0000",
},
pageBorderLeft: {
style: BorderStyle.SINGLE,
size: 8,
color: "000000",
},
},
},
},
children: [new Paragraph("Page with borders")],
},
],
});
```
### Border Options
| Property | Type | Description |
| -------- | ------------- | ---------------------------------------------------- |
| style | `BorderStyle` | Border style |
| size | `number` | Border width in 1/8 points (e.g., 8 = 1pt, 16 = 2pt) |
| color | `string` | Hex color code |
| space | `number` | Space from text (points) |
### Border Styles
Common border styles include:
- `BorderStyle.SINGLE` - Single line
- `BorderStyle.DOUBLE` - Double line
- `BorderStyle.DASHED` - Dashed line
- `BorderStyle.DOTTED` - Dotted line
- `BorderStyle.THICK` - Thick line
- `BorderStyle.WAVE` - Wavy line
### Page Border Display Options
Control when and how borders appear:
```ts
import { PageBorderDisplay, PageBorderOffsetFrom, PageBorderZOrder } 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
},
// ... individual border definitions
},
}
```
## Complete Example
Combining multiple layout options:
```ts
import { BorderStyle, Document, PageBorderDisplay, PageOrientation, Paragraph, convertInchesToTwip, convertMillimetersToTwip } from "docx";
const doc = new Document({
sections: [
{
properties: {
page: {
size: {
orientation: PageOrientation.PORTRAIT,
width: convertMillimetersToTwip(210),
height: convertMillimetersToTwip(297),
},
margin: {
top: convertInchesToTwip(1),
right: convertInchesToTwip(1),
bottom: convertInchesToTwip(1),
left: convertInchesToTwip(1.25),
},
borders: {
pageBorderTop: {
style: BorderStyle.SINGLE,
size: 8,
color: "4472C4",
},
pageBorderRight: {
style: BorderStyle.SINGLE,
size: 8,
color: "4472C4",
},
pageBorderBottom: {
style: BorderStyle.SINGLE,
size: 8,
color: "4472C4",
},
pageBorderLeft: {
style: BorderStyle.SINGLE,
size: 8,
color: "4472C4",
},
pageBorders: {
display: PageBorderDisplay.ALL_PAGES,
},
},
},
},
children: [new Paragraph("This page has A4 size, 1-inch margins, and blue borders.")],
},
],
});
```
## Demos
### Page Borders
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/71-page-borders-2.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/71-page-borders-2.ts_
### Page Sizes
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/65-page-sizes.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/65-page-sizes.ts_
### Landscape Orientation
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/7-landscape.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/7-landscape.ts_
+12 -13
View File
@@ -9,15 +9,15 @@ new Paragraph({
children: [ children: [
new TextRun({ new TextRun({
children: ["Page #: ", PageNumber.CURRENT], children: ["Page #: ", PageNumber.CURRENT],
}) }),
] ],
}) });
``` ```
## Current page number ## Current page number
```ts ```ts
PageNumber.CURRENT PageNumber.CURRENT;
``` ```
For example: For example:
@@ -27,15 +27,15 @@ new Paragraph({
children: [ children: [
new TextRun({ new TextRun({
children: ["Page Number ", PageNumber.CURRENT], children: ["Page Number ", PageNumber.CURRENT],
}) }),
] ],
}) });
``` ```
## Total number of pages ## Total number of pages
```ts ```ts
PageNumber.TOTAL_PAGES PageNumber.TOTAL_PAGES;
``` ```
For example: For example:
@@ -45,12 +45,11 @@ new Paragraph({
children: [ children: [
new TextRun({ new TextRun({
children: ["Total Pages Number: ", PageNumber.TOTAL_PAGES], children: ["Total Pages Number: ", PageNumber.TOTAL_PAGES],
}) }),
] ],
}) });
``` ```
## Both ## Both
You can combine the two to get "Page 2 of 10" effect: You can combine the two to get "Page 2 of 10" effect:
@@ -72,6 +71,6 @@ new Paragraph({
Adding page numbers to Header and Footer Adding page numbers to Header and Footer
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/39-page-numbers.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/39-page-numbers.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/39-page-numbers.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/39-page-numbers.ts_
+1 -1
View File
@@ -64,7 +64,7 @@ This is the list of options for a paragraph. A detailed explanation is below:
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [text](#text) | `string` | Optional | | | [text](#text) | `string` | Optional | |
| [heading](#heading) | `HeadingLevel` | Optional | `HEADING_1`, `HEADING_2`, `HEADING_3`, `HEADING_4`, `HEADING_5`, `HEADING_6`, `TITLE` | | [heading](#heading) | `HeadingLevel` | Optional | `HEADING_1`, `HEADING_2`, `HEADING_3`, `HEADING_4`, `HEADING_5`, `HEADING_6`, `TITLE` |
| [border](#border) | `IBorderOptions` | Optional | `top`, `bottom`, `left`, `right`, `between`. Each of these are of type IBorderPropertyOptions. Click here for Example | | [border](#border) | `IBorderOptions` | Optional | `top`, `bottom`, `left`, `right`, `between`. Each of these are of type IBorderPropertyOptions. Click here for Example |
| [spacing](#spacing) | `ISpacingProperties` | Optional | See below for ISpacingProperties | | [spacing](#spacing) | `ISpacingProperties` | Optional | See below for ISpacingProperties |
| [outlineLevel](#outline-level) | `number` | Optional | | | [outlineLevel](#outline-level) | `number` | Optional | |
| alignment | `AlignmentType` | Optional | `START`, `CENTER`, `END`, `BOTH`, `MEDIUM_KASHIDA`, `DISTRIBUTE`, `NUM_TAB`, `HIGH_KASHIDA`, `LOW_KASHIDA`, `THAI_DISTRIBUTE`, `LEFT`, `RIGHT`, `JUSTIFIED` | | alignment | `AlignmentType` | Optional | `START`, `CENTER`, `END`, `BOTH`, `MEDIUM_KASHIDA`, `DISTRIBUTE`, `NUM_TAB`, `HIGH_KASHIDA`, `LOW_KASHIDA`, `THAI_DISTRIBUTE`, `LEFT`, `RIGHT`, `JUSTIFIED` |
+5 -2
View File
@@ -35,7 +35,6 @@ interface Patch {
| type | `PatchType` | Required | `DOCUMENT`, `PARAGRAPH` | | type | `PatchType` | Required | `DOCUMENT`, `PARAGRAPH` |
| children | `FileChild[] or ParagraphChild[]` | Required | The contents to replace with. A `FileChild` is a `Paragraph` or `Table`, whereas a `ParagraphChild` is typical `Paragraph` children. | | children | `FileChild[] or ParagraphChild[]` | Required | The contents to replace with. A `FileChild` is a `Paragraph` or `Table`, whereas a `ParagraphChild` is typical `Paragraph` children. |
The patcher also takes in a `keepOriginalStyles` boolean, which will preserve the styles of the patched text when set to true. The patcher also takes in a `keepOriginalStyles` boolean, which will preserve the styles of the patched text when set to true.
### How to patch existing document ### How to patch existing document
@@ -79,7 +78,11 @@ patchDocument(fs.readFileSync("My Document.docx"), {
], ],
link: "https://www.google.co.uk", link: "https://www.google.co.uk",
}), }),
new ImageRun({ type: 'png', data: fs.readFileSync("./demo/images/dog.png"), transformation: { width: 100, height: 100 } }), new ImageRun({
type: "png",
data: fs.readFileSync("./demo/images/dog.png"),
transformation: { width: 100, height: 100 },
}),
], ],
}), }),
], ],
+195 -30
View File
@@ -6,47 +6,212 @@ A section is a grouping of paragraphs that have a specific set of properties use
For example, you could have one section which is portrait with a header and footer, and another section in landscape with no footer, and a header showing the current page number. For example, you could have one section which is portrait with a header and footer, and another section in landscape with no footer, and a header showing the current page number.
## Example ## Basic Example
This creates a simple section in a document with one paragraph inside: This creates a simple section in a document with one paragraph inside:
```ts ```ts
const doc = new Document({ const doc = new Document({
sections: [{ sections: [
children: [ {
new Paragraph({ children: [
children: [new TextRun("Hello World")], new Paragraph({
}), children: [new TextRun("Hello World")],
], }),
}]; ],
},
],
}); });
``` ```
## Properties ## Multiple Sections
You can specify additional properties to the section, by providing a `properties` attribute. Create documents with multiple sections for different layouts:
### Section Type
Setting the section type determines how the contents of the section will be placed relative to the previous section. E.g., There are five different types:
- `CONTINUOUS`
- `EVEN_PAGE`
- `NEXT_COLUMN`
- `NEXT_PAGE`
- `ODD_PAGE`
```ts ```ts
const doc = new Document({ const doc = new Document({
sections: [{ sections: [
properties: { {
type: SectionType.CONTINUOUS, // First section - portrait
} children: [new Paragraph("This is the first section in portrait.")],
children: [ },
new Paragraph({ {
children: [new TextRun("Hello World")], // Second section - landscape
}), properties: {
], page: {
}]; size: {
orientation: PageOrientation.LANDSCAPE,
},
},
},
children: [new Paragraph("This section is in landscape orientation.")],
},
],
}); });
``` ```
## Section Properties
You can specify additional properties to the section by providing a `properties` attribute.
### Section Type
Setting the section type determines how the contents of the section will be placed relative to the previous section:
| Type | Description |
| ------------- | ---------------------------------------------- |
| `CONTINUOUS` | Start on the same page as the previous section |
| `NEXT_PAGE` | Start on a new page (default) |
| `EVEN_PAGE` | Start on the next even-numbered page |
| `ODD_PAGE` | Start on the next odd-numbered page |
| `NEXT_COLUMN` | Start in the next column |
```ts
import { SectionType } from "docx";
const doc = new Document({
sections: [
{
children: [new Paragraph("First section content")],
},
{
properties: {
type: SectionType.CONTINUOUS, // Don't start new page
},
children: [new Paragraph("This continues on the same page")],
},
],
});
```
### When to Use Each Section Type
- **CONTINUOUS**: Multi-column layouts, changing headers without page breaks
- **NEXT_PAGE**: New chapters, distinct document parts
- **EVEN_PAGE/ODD_PAGE**: Books with content starting on specific sides
- **NEXT_COLUMN**: Newsletter-style column breaks
## Common Use Cases
### Different Headers Per Section
```ts
const doc = new Document({
sections: [
{
headers: {
default: new Header({
children: [new Paragraph("Chapter 1")],
}),
},
children: [new Paragraph("Chapter 1 content...")],
},
{
headers: {
default: new Header({
children: [new Paragraph("Chapter 2")],
}),
},
children: [new Paragraph("Chapter 2 content...")],
},
],
});
```
### Portrait and Landscape Mix
```ts
import { PageOrientation, convertMillimetersToTwip } from "docx";
const doc = new Document({
sections: [
{
// Portrait section for text
children: [new Paragraph("Introduction text...")],
},
{
// Landscape section for wide table
properties: {
page: {
size: {
orientation: PageOrientation.LANDSCAPE,
width: convertMillimetersToTwip(297),
height: convertMillimetersToTwip(210),
},
},
},
children: [
new Table({
// Wide table that needs landscape
rows: [
/* ... */
],
}),
],
},
],
});
```
### Multi-Column Section
```ts
const doc = new Document({
sections: [
{
// Single column intro
children: [new Paragraph("Introduction paragraph...")],
},
{
// Two-column body
properties: {
type: SectionType.CONTINUOUS,
column: {
count: 2,
space: 708,
},
},
children: [new Paragraph("Two-column content...")],
},
{
// Back to single column
properties: {
type: SectionType.CONTINUOUS,
},
children: [new Paragraph("Single column conclusion...")],
},
],
});
```
## Section Properties Reference
| Property | Type | Description |
| ------------- | ----------------------- | --------------------------------------- |
| type | `SectionType` | How section starts relative to previous |
| page | `IPageSizeAttributes` | Page size, margins, borders |
| column | `IColumnsAttributes` | Multi-column configuration |
| titlePage | `boolean` | Different first page header/footer |
| lineNumbers | `ILineNumberAttributes` | Line numbering configuration |
| verticalAlign | `VerticalAlign` | Vertical alignment of content |
## Related Topics
- **[Page Layout](usage/page-layout.md)** - Page size, margins, and borders
- **[Headers & Footers](usage/headers-and-footers.md)** - Section headers and footers
- **[Columns](usage/columns.md)** - Multi-column layouts
- **[Line Numbers](usage/line-numbers.md)** - Line numbering per section
## Demos
### Multiple Sections
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/16-multiple-sections.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/16-multiple-sections.ts_
### Section Types
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/58-section-types.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/58-section-types.ts_
+39 -39
View File
@@ -21,27 +21,27 @@ const name = new TextRun({
### Run formatting ### Run formatting
- `bold`, `italics`, `smallCaps`, `allCaps`, `strike`, `doubleStrike`, `subScript`, `superScript`: Set the formatting property to true - `bold`, `italics`, `smallCaps`, `allCaps`, `strike`, `doubleStrike`, `subScript`, `superScript`: Set the formatting property to true
- `underline({type="single", color=null})`: Set the underline style and color - `underline({type="single", color=null})`: Set the underline style and color
- `emphasisMark({type="dot"})`: Set the emphasis mark style - `emphasisMark({type="dot"})`: Set the emphasis mark style
- `color(color)`: Set the text color, using 6 hex characters for RRGGBB (no leading `#`) - `color(color)`: Set the text color, using 6 hex characters for RRGGBB (no leading `#`)
- `size(halfPts)`: Set the font size, measured in half-points - `size(halfPts)`: Set the font size, measured in half-points
- `font(name)` or `font({ascii, cs, eastAsia, hAnsi, hint})`: Set the run's font - `font(name)` or `font({ascii, cs, eastAsia, hAnsi, hint})`: Set the run's font
- `style(name)`: Apply a named run style - `style(name)`: Apply a named run style
- `characterSpacing(value)`: Set the character spacing adjustment (in TWIPs) - `characterSpacing(value)`: Set the character spacing adjustment (in TWIPs)
### Paragraph formatting ### Paragraph formatting
- `heading1`, `heading2`, `heading3`, `heading4`, `heading5`, `title`: apply the appropriate style to the paragraph - `heading1`, `heading2`, `heading3`, `heading4`, `heading5`, `title`: apply the appropriate style to the paragraph
- `left`, `center`, `right`, `justified`: set the paragraph's alignment - `left`, `center`, `right`, `justified`: set the paragraph's alignment
- `thematicBreak`, `pageBreak`: Insert a thick rule or a page break beneath the paragraph - `thematicBreak`, `pageBreak`: Insert a thick rule or a page break beneath the paragraph
- `leftTabStop(position)`: Add a left tab stop (measured in TWIPs from the left) - `leftTabStop(position)`: Add a left tab stop (measured in TWIPs from the left)
- `maxRightTabStop`: Add a right tab stop at the far right - `maxRightTabStop`: Add a right tab stop at the far right
- `bullet`: Use the default bullet style - `bullet`: Use the default bullet style
- `setNumbering(numbering, indentLevel)`: Use a custom numbering format for the paragraph - `setNumbering(numbering, indentLevel)`: Use a custom numbering format for the paragraph
- `style(name)`: Apply a named paragraph style - `style(name)`: Apply a named paragraph style
- `indent(start, hanging=0)`: Set the paragraph's indent level (in TWIPs) - `indent(start, hanging=0)`: Set the paragraph's indent level (in TWIPs)
- `spacing({before=0, after=0, line=0})`: Set the line and before/after on the paragraph. Before/after is measured in TWIPs, line is measured in 240ths of a line - `spacing({before=0, after=0, line=0})`: Set the line and before/after on the paragraph. Before/after is measured in TWIPs, line is measured in 240ths of a line
Paragraph styles have all the run formatting methods, except `style()`, and `left()`, `center()`, `right()`, `justified()`, `thematicBreak()`, `leftTabStop(position)`, `maxRightTabStop()`, `indent(start, hanging=0)`, and `spacing({before=0, after=0, line=0})` methods. Paragraph styles have all the run formatting methods, except `style()`, and `left()`, `center()`, `right()`, `justified()`, `thematicBreak()`, `leftTabStop(position)`, `maxRightTabStop()`, `indent(start, hanging=0)`, and `spacing({before=0, after=0, line=0})` methods.
@@ -49,10 +49,10 @@ Paragraph styles have all the run formatting methods, except `style()`, and `lef
There are 4 items in `docx` that can be styled: There are 4 items in `docx` that can be styled:
- Characters: Attributes that can change within a paragraph. e.g., bold, italics, etc. - Characters: Attributes that can change within a paragraph. e.g., bold, italics, etc.
- Paragraphs: Attributes like indent, text alignment, line spacing, etc. - Paragraphs: Attributes like indent, text alignment, line spacing, etc.
- Tables: Border styles, table formats, etc. - Tables: Border styles, table formats, etc.
- List items: These are the numbers and bullets that are automatically inserted - List items: These are the numbers and bullets that are automatically inserted
There are a few different ways of styling this content in `docx`, which somewhat resemble the HTML/CSS approach. In order of greatest to lowest priority: There are a few different ways of styling this content in `docx`, which somewhat resemble the HTML/CSS approach. In order of greatest to lowest priority:
@@ -137,12 +137,12 @@ const doc = new Document({
paragraph: { paragraph: {
spacing: { spacing: {
before: 240, before: 240,
after: 120 after: 120,
}, },
}, },
}, },
] ],
} },
}); });
``` ```
@@ -180,22 +180,22 @@ To determine the value of a styling property, you must first identify whether it
The following properties are treated in a special manner; they're called toggle properties: The following properties are treated in a special manner; they're called toggle properties:
- Bold - Bold
- All caps - All caps
- Small caps - Small caps
- Italics - Italics
- Single strike-through - Single strike-through
- Hidden - Hidden
- Imprint - Imprint
- Emboss - Emboss
- Character outline - Character outline
- Character shadow - Character shadow
For these properties, the rules state the following conflict resolution in case the property is specified at multiple points for the same item: For these properties, the rules state the following conflict resolution in case the property is specified at multiple points for the same item:
- Direct formatting trumps all if specified (either true or false) - Direct formatting trumps all if specified (either true or false)
- Otherwise, if the property is true in document defaults, the property is set to true - Otherwise, if the property is true in document defaults, the property is set to true
- Otherwise, the property's value is an XOR of its effective table, paragraph, and character values. (So specifying bold `true` on a table style and a paragraph style would result in non-bold text if a paragraph inside the table had that style) - Otherwise, the property's value is an XOR of its effective table, paragraph, and character values. (So specifying bold `true` on a table style and a paragraph style would result in non-bold text if a paragraph inside the table had that style)
## Examples ## Examples
@@ -203,6 +203,6 @@ For these properties, the rules state the following conflict resolution in case
Importing Images from file system path Importing Images from file system path
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/2-declaritive-styles.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/2-declaritive-styles.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/2-declaritive-styles.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/2-declaritive-styles.ts_
+2 -3
View File
@@ -9,15 +9,14 @@
![image](https://user-images.githubusercontent.com/2917613/41195113-65edebfa-6c1f-11e8-97b4-77de2d60044a.png) ![image](https://user-images.githubusercontent.com/2917613/41195113-65edebfa-6c1f-11e8-97b4-77de2d60044a.png)
![image](https://user-images.githubusercontent.com/2917613/41195126-ca99c36c-6c1f-11e8-9e58-19e5f69b3b87.png) ![image](https://user-images.githubusercontent.com/2917613/41195126-ca99c36c-6c1f-11e8-9e58-19e5f69b3b87.png)
*Note*: Font and color selection from the theme are currently not supported. _Note_: Font and color selection from the theme are currently not supported.
3. You can even create a totally new `Style`: 3. You can even create a totally new `Style`:
![image](https://user-images.githubusercontent.com/2917613/41195135-f0f7862a-6c1f-11e8-8be4-dd6d8fe5be03.png) ![image](https://user-images.githubusercontent.com/2917613/41195135-f0f7862a-6c1f-11e8-8be4-dd6d8fe5be03.png)
![image](https://user-images.githubusercontent.com/2917613/41195139-0ec52130-6c20-11e8-8fae-f6b44b43fdf8.png) ![image](https://user-images.githubusercontent.com/2917613/41195139-0ec52130-6c20-11e8-8fae-f6b44b43fdf8.png)
*Note*: When selecting the style type, it is important to consider the component being used. _Note_: When selecting the style type, it is important to consider the component being used.
4. Save 4. Save
5. Re-name the saved `.docx` file to `.zip` and un-zip 5. Re-name the saved `.docx` file to `.zip` and un-zip
+1 -4
View File
@@ -8,10 +8,7 @@ You can add multiple `symbol runs` in `Paragraphs` along with [text runs](usage/
import { Paragraph, TextRun, SymbolRun } from "docx"; import { Paragraph, TextRun, SymbolRun } from "docx";
const paragraph = new Paragraph({ const paragraph = new Paragraph({
children: [ children: [new TextRun("This is a checkbox: "), new SymbolRun("F071")],
new TextRun("This is a checkbox: "),
new SymbolRun("F071")
],
}); });
``` ```
+4 -4
View File
@@ -31,9 +31,9 @@ const doc = new Document({
heading: HeadingLevel.HEADING_1, heading: HeadingLevel.HEADING_1,
pageBreakBefore: true, pageBreakBefore: true,
}), }),
] ],
} },
] ],
}); });
``` ```
@@ -62,6 +62,6 @@ Here is the list of all options that you can use to generate your tables of cont
## Examples ## Examples
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/28-table-of-contents.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/28-table-of-contents.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/28-table-of-contents.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/28-table-of-contents.ts_
+33 -31
View File
@@ -4,9 +4,9 @@
## Intro ## Intro
- `Tables` contain a list of `Rows` - `Tables` contain a list of `Rows`
- `Rows` contain a list of `TableCells` - `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 - `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 like so:
@@ -20,9 +20,11 @@ Then add the table in the `section`
```ts ```ts
const doc = new Document({ const doc = new Document({
sections: [{ sections: [
children: [table], {
}], children: [table],
},
],
}); });
``` ```
@@ -99,12 +101,12 @@ const table = new Table({
Here is a list of options you can add to the `table row`: Here is a list of options you can add to the `table row`:
| Property | Type | Notes | | Property | Type | Notes |
| ----------- | -------------------------------------- | -------- | | ----------- | ------------------------------------- | -------- |
| children | `Array<TableCell>` | Required | | children | `Array<TableCell>` | Required |
| cantSplit | `boolean` | Optional | | cantSplit | `boolean` | Optional |
| tableHeader | `boolean` | Optional | | tableHeader | `boolean` | Optional |
| height | `{ value: number, rule: HeightRule }` | Optional | | height | `{ value: number, rule: HeightRule }` | Optional |
### Repeat row ### Repeat row
@@ -154,16 +156,16 @@ const tableRow = new TableRow({
### Options ### Options
| Property | Type | Notes | | Property | Type | Notes |
| ------------- | ----------------------------------- | ----------------------------------------------------------- | | ------------- | ---------------------------------- | ----------------------------------------------------------- |
| children | `Array<Paragraph or Table>` | Required. You can nest tables by adding a table into a cell | | children | `Array<Paragraph or Table>` | Required. You can nest tables by adding a table into a cell |
| shading | `IShadingAttributesProperties` | Optional | | shading | `IShadingAttributesProperties` | Optional |
| margins | `ITableCellMarginOptions` | Optional | | margins | `ITableCellMarginOptions` | Optional |
| verticalAlign | `VerticalAlignTable` | Optional | | verticalAlign | `VerticalAlignTable` | Optional |
| columnSpan | `number` | Optional | | columnSpan | `number` | Optional |
| rowSpan | `number` | Optional | | rowSpan | `number` | Optional |
| borders | `BorderOptions` | Optional | | borders | `BorderOptions` | Optional |
| width | `{ size: number type: WidthType }` | Optional | | width | `{ size: number type: WidthType }` | Optional |
#### Border Options #### Border Options
@@ -346,7 +348,7 @@ const table = new Table({
## Examples ## Examples
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/4-basic-table.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/4-basic-table.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/4-basic-table.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/4-basic-table.ts_
@@ -354,7 +356,7 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/4-basic-table.ts_
Example showing how to add colorful borders to tables Example showing how to add colorful borders to tables
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/20-table-cell-borders.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/20-table-cell-borders.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/20-table-cell-borders.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/20-table-cell-borders.ts_
@@ -362,11 +364,11 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/20-table-cell-borders
Example showing how to add images to tables Example showing how to add images to tables
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/24-images-to-table-cell.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/24-images-to-table-cell.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/24-images-to-table-cell.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/24-images-to-table-cell.ts_
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/36-image-to-table-cell.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/36-image-to-table-cell.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/36-image-to-table-cell.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/36-image-to-table-cell.ts_
@@ -374,7 +376,7 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/36-image-to-table-cel
Example showing how align text in a table cell Example showing how align text in a table cell
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/31-tables.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/31-tables.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/31-tables.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/31-tables.ts_
@@ -382,11 +384,11 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/31-tables.ts_
Example showing merging of columns and rows and shading Example showing merging of columns and rows and shading
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/32-merge-and-shade-table-cells.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/32-merge-and-shade-table-cells.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/32-merge-and-shade-table-cells.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/32-merge-and-shade-table-cells.ts_
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/41-merge-table-cells-2.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/41-merge-table-cells-2.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/41-merge-table-cells-2.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/41-merge-table-cells-2.ts_
@@ -394,12 +396,12 @@ _Source: https://github.com/dolanmiu/docx/blob/master/demo/41-merge-table-cells-
Example showing merging of columns and rows Example showing merging of columns and rows
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/43-images-to-table-cell-2.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/43-images-to-table-cell-2.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/43-images-to-table-cell-2.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/43-images-to-table-cell-2.ts_
### Floating tables ### Floating tables
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/34-floating-tables.ts ':include') [Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/34-floating-tables.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/34-floating-tables.ts_ _Source: https://github.com/dolanmiu/docx/blob/master/demo/34-floating-tables.ts_
+283
View File
@@ -0,0 +1,283 @@
# Templates
Templates allow you to modify existing Word documents by replacing placeholder text with dynamic content. This is useful for generating documents from pre-designed layouts.
!> For detailed information on the `patchDocument` function, see the [Patcher](usage/patcher.md) guide.
## Overview
The template workflow consists of:
1. Create a Word document (.docx) with placeholder tags like `{{placeholder}}`
2. Use `patchDocument` to replace the placeholders with content
3. Export the modified document
## Creating a Template
Open your Word processor and create a document with placeholders:
```
Dear {{customer_name}},
Thank you for your order #{{order_number}}.
Your items will ship on {{ship_date}}.
Best regards,
{{company_name}}
```
?> Use double curly braces `{{}}` for placeholders. These will be replaced at runtime.
## Basic Usage
```ts
import * as fs from "fs";
import { patchDocument, PatchType, TextRun } from "docx";
patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("template.docx"),
patches: {
customer_name: {
type: PatchType.PARAGRAPH,
children: [new TextRun("John Smith")],
},
order_number: {
type: PatchType.PARAGRAPH,
children: [new TextRun("12345")],
},
ship_date: {
type: PatchType.PARAGRAPH,
children: [new TextRun("January 15, 2024")],
},
company_name: {
type: PatchType.PARAGRAPH,
children: [new TextRun("Acme Corp")],
},
},
}).then((doc) => {
fs.writeFileSync("output.docx", doc);
});
```
## Patch Types
### 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 }),
],
}
```
### 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: [/* ... */],
}),
],
}
```
## Advanced Patches
### Images
```ts
import { ImageRun, PatchType } from "docx";
image_placeholder: {
type: PatchType.PARAGRAPH,
children: [
new ImageRun({
type: "png",
data: fs.readFileSync("./logo.png"),
transformation: { width: 100, height: 50 },
}),
],
}
```
### Hyperlinks
```ts
import { ExternalHyperlink, PatchType, TextRun } from "docx";
link_placeholder: {
type: PatchType.PARAGRAPH,
children: [
new ExternalHyperlink({
children: [
new TextRun({
text: "Visit our website",
style: "Hyperlink",
}),
],
link: "https://example.com",
}),
],
}
```
### Tables
```ts
import { Paragraph, 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")] }),
],
}),
],
}),
],
}
```
## Preserving Styles
Set `keepOriginalStyles: true` to preserve the formatting of the placeholder text:
```ts
patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("template.docx"),
keepOriginalStyles: true, // Preserve template formatting
patches: {
// ...
},
});
```
## 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")],
}
```
## Complete Example
Invoice template:
```ts
import * as fs from "fs";
import { ExternalHyperlink, ImageRun, Paragraph, patchDocument, PatchType, Table, TableCell, TableRow, TextRun } from "docx";
// Invoice data
const invoice = {
number: "INV-2024-001",
date: "January 10, 2024",
customer: "Acme Corporation",
items: [
{ name: "Widget A", qty: 5, price: 10.0 },
{ name: "Widget B", qty: 3, price: 15.0 },
],
total: 95.0,
};
patchDocument({
outputType: "nodebuffer",
data: fs.readFileSync("invoice-template.docx"),
patches: {
invoice_number: {
type: PatchType.PARAGRAPH,
children: [new TextRun(invoice.number)],
},
invoice_date: {
type: PatchType.PARAGRAPH,
children: [new TextRun(invoice.date)],
},
customer_name: {
type: PatchType.PARAGRAPH,
children: [new TextRun(invoice.customer)],
},
line_items: {
type: PatchType.DOCUMENT,
children: [
new Table({
rows: [
new TableRow({
children: [
new TableCell({ children: [new Paragraph("Item")] }),
new TableCell({ children: [new Paragraph("Qty")] }),
new TableCell({ children: [new Paragraph("Price")] }),
],
}),
...invoice.items.map(
(item) =>
new TableRow({
children: [
new TableCell({ children: [new Paragraph(item.name)] }),
new TableCell({ children: [new Paragraph(String(item.qty))] }),
new TableCell({ children: [new Paragraph(`$${item.price.toFixed(2)}`)] }),
],
}),
),
],
}),
],
},
total: {
type: PatchType.PARAGRAPH,
children: [
new TextRun({
text: `$${invoice.total.toFixed(2)}`,
bold: true,
}),
],
},
},
}).then((doc) => {
fs.writeFileSync("invoice-output.docx", doc);
});
```
## Tips
- **Placeholder naming**: Use descriptive names like `customer_name` instead of `x1`
- **Testing**: Open the template in Word to verify placeholders are formatted as plain text
- **Complex layouts**: Design the layout in Word, then add placeholders where content varies
- **Reusable templates**: Store templates in a dedicated folder for easy access
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/85-template-document.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/85-template-document.ts_
+192 -10
View File
@@ -1,26 +1,208 @@
# Text Box # Text Box
Similar `Text Frames`, but the difference being that it is `VML` `Shape` based. Similar to `Text Frames`, but the difference being that it is `VML` `Shape` based.
!> `Text Boxes` requires an understanding of [Paragraphs](usage/paragraph.md). !> `Text Boxes` require an understanding of [Paragraphs](usage/paragraph.md).
> `Text boxes` are paragraphs of text in a document which are positioned in a separate region or frame in the document, and can be positioned with a specific size and position relative to non-frame paragraphs in the current document. > `Text boxes` are paragraphs of text in a document which are positioned in a separate region or frame in the document, and can be positioned with a specific size and position relative to non-frame paragraphs in the current document.
## Intro ## Basic Text Box
To make a `Text Box`, simply create a `Textbox` object inside the `Document`: Create a text box with basic content:
```ts
import { Document, Paragraph, TextRun, Textbox } from "docx";
const doc = new Document({
sections: [
{
children: [
new Textbox({
children: [
new Paragraph({
children: [new TextRun("Hello from a textbox!")],
}),
],
style: {
width: "200pt",
height: "100pt",
},
}),
],
},
],
});
```
## Textbox Options
| Property | Type | Notes | Description |
| --------- | --------------- | -------- | ---------------------------- |
| children | `Paragraph[]` | Required | Content inside the textbox |
| style | `ITextboxStyle` | Optional | Positioning and size options |
| alignment | `string` | Optional | Horizontal alignment |
## Sizing
### Fixed Size
```ts ```ts
new Textbox({ new Textbox({
alignment: "center", children: [new Paragraph("Fixed size textbox")],
children: [ style: {
new Paragraph({ width: "200pt",
children: [new TextRun("Hi i'm a textbox!")], height: "100pt",
}), },
], });
```
### Auto Height
```ts
new Textbox({
children: [new Paragraph("Auto height based on content")],
style: { style: {
width: "200pt", width: "200pt",
height: "auto", height: "auto",
}, },
}); });
``` ```
## Alignment
Align the textbox horizontally:
```ts
new Textbox({
alignment: "center",
children: [new Paragraph("Centered textbox")],
style: {
width: "200pt",
height: "auto",
},
});
```
Available alignment values:
- `"left"` - Align to left margin
- `"center"` - Center on page
- `"right"` - Align to right margin
## Multiple Paragraphs
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."),
],
style: {
width: "300pt",
height: "auto",
},
});
```
## Styled Content
Apply formatting to text within the textbox:
```ts
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",
},
});
```
## Complete Example
Sidebar callout box:
```ts
import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TextRun, Textbox } from "docx";
import * as fs from "fs";
const doc = new Document({
sections: [
{
children: [
new Paragraph("Main document content goes here..."),
new Textbox({
alignment: "right",
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new TextRun({
text: "Did You Know?",
bold: true,
color: "2F5496",
}),
],
}),
new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new TextRun({
text: "docx can generate Word documents in both Node.js and browsers!",
italics: true,
}),
],
}),
],
style: {
width: "180pt",
height: "auto",
},
}),
new Paragraph("More document content continues..."),
],
},
],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("document.docx", buffer);
});
```
## Text Box vs Text Frame
| Feature | Text Box | Text Frame |
| ------------- | ------------------- | ----------------- |
| Based on | VML Shape | Paragraph framing |
| Positioning | More flexible | Limited |
| Compatibility | Older Word versions | Modern Word |
For most use cases, **Text Frames** are recommended. See [Text Frames](usage/text-frames.md) for more information.
## Demo
[Example](https://raw.githubusercontent.com/dolanmiu/docx/master/demo/94-texbox.ts ":include")
_Source: https://github.com/dolanmiu/docx/blob/master/demo/94-texbox.ts_
+1 -1
View File
@@ -30,7 +30,7 @@
"predemo": "npm run build", "predemo": "npm run build",
"demo": "tsx ./demo/index.ts", "demo": "tsx ./demo/index.ts",
"typedoc": "typedoc src/index.ts --tsconfig tsconfig.typedoc.json", "typedoc": "typedoc src/index.ts --tsconfig tsconfig.typedoc.json",
"prettier": "prettier -l \"{src,scripts,demo}/**/*.{ts,html}\"", "prettier": "prettier -l \"{src,scripts,demo,docs}/**/*.{ts,html,md}\"",
"prettier:fix": "npm run prettier -- --write", "prettier:fix": "npm run prettier -- --write",
"cspell": "cspell \"{src,demo,docs,scripts}/**/*.{ts,scss,html,md}\" && cspell \"./*.*\"", "cspell": "cspell \"{src,demo,docs,scripts}/**/*.{ts,scss,html,md}\" && cspell \"./*.*\"",
"serve.docs": "cd docs && docsify serve", "serve.docs": "cd docs && docsify serve",
+27
View File
@@ -1,6 +1,33 @@
/**
* Formatter module for converting XML components to serializable objects.
*
* @module
*/
import { BaseXmlComponent, IContext, IXmlableObject } from "@file/xml-components"; import { BaseXmlComponent, IContext, IXmlableObject } from "@file/xml-components";
/**
* Converts XML components into serializable objects ready for XML generation.
*
* The Formatter is responsible for preparing XML components for serialization by calling
* their prepForXml method with the appropriate context. This is a critical step in the
* export pipeline that transforms the declarative API objects into XML-compatible structures.
*
* @example
* ```typescript
* const formatter = new Formatter();
* const paragraph = new Paragraph("Hello World");
* const xmlObject = formatter.format(paragraph, context);
* ```
*/
export class Formatter { export class Formatter {
/**
* Formats an XML component into a serializable object.
*
* @param input - The XML component to format
* @param context - The context containing file state and relationships
* @returns A serializable XML object structure
* @throws Error if the component cannot be formatted correctly
*/
public format(input: BaseXmlComponent, context: IContext = { stack: [] } as unknown as IContext): IXmlableObject { public format(input: BaseXmlComponent, context: IContext = { stack: [] } as unknown as IContext): IXmlableObject {
const output = input.prepForXml(context); const output = input.prepForXml(context);
+5
View File
@@ -1 +1,6 @@
/**
* Export module exports.
*
* @module
*/
export * from "./packer/packer"; export * from "./packer/packer";
+34
View File
@@ -1,6 +1,33 @@
/**
* Image replacer module for substituting image placeholders in XML.
*
* @module
*/
import { IMediaData, Media } from "@file/media"; import { IMediaData, Media } from "@file/media";
/**
* Replaces image placeholders with relationship IDs in XML content.
*
* During document compilation, images are referenced using placeholder tokens
* like {image1.png}. This class replaces those placeholders with the actual
* relationship IDs used in the OOXML structure.
*
* @example
* ```typescript
* const replacer = new ImageReplacer();
* const mediaData = replacer.getMediaData(xmlString, media);
* const updatedXml = replacer.replace(xmlString, mediaData, 1);
* ```
*/
export class ImageReplacer { export class ImageReplacer {
/**
* Replaces image placeholder tokens with relationship IDs.
*
* @param xmlData - The XML string containing image placeholders
* @param mediaData - Array of media data to replace
* @param offset - Starting offset for relationship IDs
* @returns XML string with placeholders replaced by relationship IDs
*/
public replace(xmlData: string, mediaData: readonly IMediaData[], offset: number): string { public replace(xmlData: string, mediaData: readonly IMediaData[], offset: number): string {
let currentXmlData = xmlData; let currentXmlData = xmlData;
@@ -11,6 +38,13 @@ export class ImageReplacer {
return currentXmlData; return currentXmlData;
} }
/**
* Extracts media data referenced in the XML content.
*
* @param xmlData - The XML string to search for media references
* @param media - The media collection to search within
* @returns Array of media data found in the XML
*/
public getMediaData(xmlData: string, media: Media): readonly IMediaData[] { public getMediaData(xmlData: string, media: Media): readonly IMediaData[] {
return media.Array.filter((image) => xmlData.search(`{${image.fileName}}`) > 0); return media.Array.filter((image) => xmlData.search(`{${image.fileName}}`) > 0);
} }
+70
View File
@@ -1,3 +1,8 @@
/**
* Compiler module for converting File objects into OOXML ZIP archives.
*
* @module
*/
import JSZip from "jszip"; import JSZip from "jszip";
import xml from "xml"; import xml from "xml";
@@ -9,45 +14,110 @@ import { ImageReplacer } from "./image-replacer";
import { NumberingReplacer } from "./numbering-replacer"; import { NumberingReplacer } from "./numbering-replacer";
import { PrettifyType } from "./packer"; import { PrettifyType } from "./packer";
/**
* Represents a serialized XML file with its path in the OOXML package.
*
* @property data - The XML content as a string
* @property path - The file path within the ZIP archive (e.g., "word/document.xml")
*/
export type IXmlifyedFile = { export type IXmlifyedFile = {
readonly data: string; readonly data: string;
readonly path: string; readonly path: string;
}; };
/**
* Complete mapping of all XML files in an OOXML document package.
*
* This type represents the full structure of a .docx file, including the main
* document, styles, relationships, headers, footers, and metadata files.
*/
type IXmlifyedFileMapping = { type IXmlifyedFileMapping = {
/** Main document content (word/document.xml) */
readonly Document: IXmlifyedFile; readonly Document: IXmlifyedFile;
/** Style definitions (word/styles.xml) */
readonly Styles: IXmlifyedFile; readonly Styles: IXmlifyedFile;
/** Core document properties (docProps/core.xml) */
readonly Properties: IXmlifyedFile; readonly Properties: IXmlifyedFile;
/** Numbering definitions (word/numbering.xml) */
readonly Numbering: IXmlifyedFile; readonly Numbering: IXmlifyedFile;
/** Document relationships (word/_rels/document.xml.rels) */
readonly Relationships: IXmlifyedFile; readonly Relationships: IXmlifyedFile;
/** Package-level relationships (_rels/.rels) */
readonly FileRelationships: IXmlifyedFile; readonly FileRelationships: IXmlifyedFile;
/** Header content files */
readonly Headers: readonly IXmlifyedFile[]; readonly Headers: readonly IXmlifyedFile[];
/** Footer content files */
readonly Footers: readonly IXmlifyedFile[]; readonly Footers: readonly IXmlifyedFile[];
/** Header relationship files */
readonly HeaderRelationships: readonly IXmlifyedFile[]; readonly HeaderRelationships: readonly IXmlifyedFile[];
/** Footer relationship files */
readonly FooterRelationships: readonly IXmlifyedFile[]; readonly FooterRelationships: readonly IXmlifyedFile[];
/** Content types mapping ([Content_Types].xml) */
readonly ContentTypes: IXmlifyedFile; readonly ContentTypes: IXmlifyedFile;
/** Custom document properties (docProps/custom.xml) */
readonly CustomProperties: IXmlifyedFile; readonly CustomProperties: IXmlifyedFile;
/** Application properties (docProps/app.xml) */
readonly AppProperties: IXmlifyedFile; readonly AppProperties: IXmlifyedFile;
/** Footnotes content (word/footnotes.xml) */
readonly FootNotes: IXmlifyedFile; readonly FootNotes: IXmlifyedFile;
/** Footnotes relationships (word/_rels/footnotes.xml.rels) */
readonly FootNotesRelationships: IXmlifyedFile; readonly FootNotesRelationships: IXmlifyedFile;
/** Document settings (word/settings.xml) */
readonly Settings: IXmlifyedFile; readonly Settings: IXmlifyedFile;
/** Comments content (word/comments.xml) */
readonly Comments?: IXmlifyedFile; readonly Comments?: IXmlifyedFile;
/** Comments relationships (word/_rels/comments.xml.rels) */
readonly CommentsRelationships?: IXmlifyedFile; readonly CommentsRelationships?: IXmlifyedFile;
/** Font table (word/fontTable.xml) */
readonly FontTable?: IXmlifyedFile; readonly FontTable?: IXmlifyedFile;
/** Font table relationships (word/_rels/fontTable.xml.rels) */
readonly FontTableRelationships?: IXmlifyedFile; readonly FontTableRelationships?: IXmlifyedFile;
}; };
/**
* Compiles File objects into OOXML-compliant ZIP archives.
*
* The Compiler is responsible for converting the internal document representation
* into the complete set of XML files required for a .docx document, managing
* relationships, images, fonts, and all other document components.
*
* @example
* ```typescript
* const compiler = new Compiler();
* const zip = compiler.compile(file, PrettifyType.WITH_2_BLANKS);
* ```
*/
export class Compiler { export class Compiler {
private readonly formatter: Formatter; private readonly formatter: Formatter;
private readonly imageReplacer: ImageReplacer; private readonly imageReplacer: ImageReplacer;
private readonly numberingReplacer: NumberingReplacer; private readonly numberingReplacer: NumberingReplacer;
/**
* Creates a new Compiler instance.
*
* Initializes the formatter and replacer utilities used during compilation.
*/
public constructor() { public constructor() {
this.formatter = new Formatter(); this.formatter = new Formatter();
this.imageReplacer = new ImageReplacer(); this.imageReplacer = new ImageReplacer();
this.numberingReplacer = new NumberingReplacer(); this.numberingReplacer = new NumberingReplacer();
} }
/**
* Compiles a File object into a JSZip archive containing the complete OOXML package.
*
* This method orchestrates the entire compilation process:
* - Converts all document components to XML
* - Manages image and numbering placeholder replacements
* - Creates relationship files
* - Packages fonts and media files
* - Assembles everything into a ZIP archive
*
* @param file - The document to compile
* @param prettifyXml - Optional XML formatting style
* @param overrides - Optional custom XML file overrides
* @returns A JSZip instance containing the complete .docx package
*/
public compile( public compile(
file: File, file: File,
prettifyXml?: (typeof PrettifyType)[keyof typeof PrettifyType], prettifyXml?: (typeof PrettifyType)[keyof typeof PrettifyType],
+28
View File
@@ -1,6 +1,34 @@
/**
* Numbering replacer module for substituting numbering placeholders in XML.
*
* @module
*/
import { ConcreteNumbering } from "@file/numbering"; import { ConcreteNumbering } from "@file/numbering";
/**
* Replaces numbering instance placeholders with actual numbering IDs in XML content.
*
* Numbering instances (for bullets and numbered lists) use placeholder tokens during
* compilation. This class replaces those placeholders with the final numbering IDs
* that reference the numbering definitions in numbering.xml.
*
* @example
* ```typescript
* const replacer = new NumberingReplacer();
* const updatedXml = replacer.replace(xmlString, concreteNumberings);
* ```
*/
export class NumberingReplacer { export class NumberingReplacer {
/**
* Replaces numbering placeholder tokens with actual numbering IDs.
*
* Placeholder format: {reference-instance} where reference identifies the
* numbering definition and instance is the specific usage.
*
* @param xmlData - The XML string containing numbering placeholders
* @param concreteNumberings - Array of concrete numbering instances to replace
* @returns XML string with placeholders replaced by numbering IDs
*/
public replace(xmlData: string, concreteNumberings: readonly ConcreteNumbering[]): string { public replace(xmlData: string, concreteNumberings: readonly ConcreteNumbering[]): string {
let currentXmlData = xmlData; let currentXmlData = xmlData;
+89 -2
View File
@@ -1,3 +1,8 @@
/**
* Packer module for exporting documents to various output formats.
*
* @module
*/
import { Stream } from "stream"; import { Stream } from "stream";
import { File } from "@file/file"; import { File } from "@file/file";
@@ -6,13 +11,19 @@ import { OutputByType, OutputType } from "@util/output-type";
import { Compiler, IXmlifyedFile } from "./next-compiler"; import { Compiler, IXmlifyedFile } from "./next-compiler";
/** /**
* Use blanks to prettify * Prettify options for formatting XML output.
*
* Controls the indentation style used when formatting the generated XML.
* Prettified output is more human-readable but results in larger file sizes.
*/ */
export const PrettifyType = { export const PrettifyType = {
/** No prettification (smallest file size) */
NONE: "", NONE: "",
/** Indent with 2 spaces */
WITH_2_BLANKS: " ", WITH_2_BLANKS: " ",
/** Indent with 4 spaces */
WITH_4_BLANKS: " ", WITH_4_BLANKS: " ",
/** Indent with tab character */
WITH_TAB: "\t", WITH_TAB: "\t",
} as const; } as const;
@@ -21,7 +32,35 @@ const convertPrettifyType = (
): (typeof PrettifyType)[keyof typeof PrettifyType] | undefined => ): (typeof PrettifyType)[keyof typeof PrettifyType] | undefined =>
prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify; prettify === true ? PrettifyType.WITH_2_BLANKS : prettify === false ? undefined : prettify;
/**
* Exports documents to various output formats.
*
* The Packer class provides static methods to convert a File object into different
* output formats such as Buffer, Blob, string, or stream. It handles the compilation
* of the document structure into OOXML format and compression into a .docx ZIP archive.
*
* @example
* ```typescript
* // Export to buffer (Node.js)
* const buffer = await Packer.toBuffer(doc);
*
* // Export to blob (browser)
* const blob = await Packer.toBlob(doc);
*
* // Export with prettified XML
* const buffer = await Packer.toBuffer(doc, PrettifyType.WITH_2_BLANKS);
* ```
*/
export class Packer { export class Packer {
/**
* Exports a document to the specified output format.
*
* @param file - The document to export
* @param type - The output format type (e.g., "nodebuffer", "blob", "string")
* @param prettify - Whether to prettify the XML output (boolean or PrettifyType)
* @param overrides - Optional array of file overrides for custom XML content
* @returns A promise resolving to the exported document in the specified format
*/
// eslint-disable-next-line require-await // eslint-disable-next-line require-await
public static async pack<T extends OutputType>( public static async pack<T extends OutputType>(
file: File, file: File,
@@ -37,6 +76,14 @@ export class Packer {
}); });
} }
/**
* Exports a document to a string representation.
*
* @param file - The document to export
* @param prettify - Whether to prettify the XML output
* @param overrides - Optional array of file overrides
* @returns A promise resolving to the document as a string
*/
public static toString( public static toString(
file: File, file: File,
prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType],
@@ -45,6 +92,14 @@ export class Packer {
return Packer.pack(file, "string", prettify, overrides); return Packer.pack(file, "string", prettify, overrides);
} }
/**
* Exports a document to a Node.js Buffer.
*
* @param file - The document to export
* @param prettify - Whether to prettify the XML output
* @param overrides - Optional array of file overrides
* @returns A promise resolving to the document as a Buffer
*/
public static toBuffer( public static toBuffer(
file: File, file: File,
prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType],
@@ -53,6 +108,14 @@ export class Packer {
return Packer.pack(file, "nodebuffer", prettify, overrides); return Packer.pack(file, "nodebuffer", prettify, overrides);
} }
/**
* Exports a document to a base64-encoded string.
*
* @param file - The document to export
* @param prettify - Whether to prettify the XML output
* @param overrides - Optional array of file overrides
* @returns A promise resolving to the document as a base64 string
*/
public static toBase64String( public static toBase64String(
file: File, file: File,
prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType],
@@ -61,6 +124,14 @@ export class Packer {
return Packer.pack(file, "base64", prettify, overrides); return Packer.pack(file, "base64", prettify, overrides);
} }
/**
* Exports a document to a Blob (for browser environments).
*
* @param file - The document to export
* @param prettify - Whether to prettify the XML output
* @param overrides - Optional array of file overrides
* @returns A promise resolving to the document as a Blob
*/
public static toBlob( public static toBlob(
file: File, file: File,
prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType],
@@ -69,6 +140,14 @@ export class Packer {
return Packer.pack(file, "blob", prettify, overrides); return Packer.pack(file, "blob", prettify, overrides);
} }
/**
* Exports a document to an ArrayBuffer.
*
* @param file - The document to export
* @param prettify - Whether to prettify the XML output
* @param overrides - Optional array of file overrides
* @returns A promise resolving to the document as an ArrayBuffer
*/
public static toArrayBuffer( public static toArrayBuffer(
file: File, file: File,
prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType],
@@ -77,6 +156,14 @@ export class Packer {
return Packer.pack(file, "arraybuffer", prettify, overrides); return Packer.pack(file, "arraybuffer", prettify, overrides);
} }
/**
* Exports a document to a Node.js Stream.
*
* @param file - The document to export
* @param prettify - Whether to prettify the XML output
* @param overrides - Optional array of file overrides
* @returns A readable stream containing the document data
*/
public static toStream( public static toStream(
file: File, file: File,
prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType], prettify?: boolean | (typeof PrettifyType)[keyof typeof PrettifyType],
@@ -1,7 +1,24 @@
/**
* App Properties Attributes module for WordprocessingML documents.
*
* Provides namespace attributes for extended document properties.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesExtended.xsd
*
* @module
*/
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
/**
* XML namespace attributes for the app properties element.
*
* @property xmlns - Main namespace for extended properties
* @property vt - Namespace for variant types
*/
export class AppPropertiesAttributes extends XmlAttributeComponent<{ export class AppPropertiesAttributes extends XmlAttributeComponent<{
/** Main namespace for extended properties */
readonly xmlns: string; readonly xmlns: string;
/** Namespace for variant types */
readonly vt: string; readonly vt: string;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
+42
View File
@@ -1,7 +1,49 @@
/**
* App Properties module for WordprocessingML documents.
*
* Provides support for extended document properties specific to Office applications.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesExtended.xsd
*
* @module
*/
import { XmlComponent } from "@file/xml-components"; import { XmlComponent } from "@file/xml-components";
import { AppPropertiesAttributes } from "./app-properties-attributes"; import { AppPropertiesAttributes } from "./app-properties-attributes";
/**
* Represents the extended application properties of a WordprocessingML document.
*
* Extended properties contain application-specific metadata such as total editing time,
* word count, character count, and other Office-specific information.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesExtended.xsd
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_Properties">
* <xsd:sequence>
* <xsd:element name="Template" type="xsd:string" minOccurs="0"/>
* <xsd:element name="Manager" type="xsd:string" minOccurs="0"/>
* <xsd:element name="Company" type="xsd:string" minOccurs="0"/>
* <xsd:element name="Pages" type="xsd:int" minOccurs="0"/>
* <xsd:element name="Words" type="xsd:int" minOccurs="0"/>
* <xsd:element name="Characters" type="xsd:int" minOccurs="0"/>
* <xsd:element name="PresentationFormat" type="xsd:string" minOccurs="0"/>
* <xsd:element name="Lines" type="xsd:int" minOccurs="0"/>
* <xsd:element name="Paragraphs" type="xsd:int" minOccurs="0"/>
* <xsd:element name="CharactersWithSpaces" type="xsd:int" minOccurs="0"/>
* <xsd:element name="Application" type="xsd:string" minOccurs="0"/>
* <xsd:element name="DocSecurity" type="xsd:int" minOccurs="0"/>
* </xsd:sequence>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* const appProps = new AppProperties();
* ```
*/
export class AppProperties extends XmlComponent { export class AppProperties extends XmlComponent {
public constructor() { public constructor() {
super("Properties"); super("Properties");
+56 -21
View File
@@ -1,27 +1,44 @@
// Note that the border type is identical in all places, /**
// regardless of where it's used like paragraph/table/etc. * Border module for WordprocessingML documents.
// PageBorders are a superset, but we're not using any of those extras. *
// * Borders are used in multiple contexts (paragraphs, tables, table cells, sections)
// http://officeopenxml.com/WPborders.php * and share the same CT_Border type definition. This module provides the BorderElement
// http://officeopenxml.com/WPtableBorders.php * class and BorderStyle constants used throughout the document structure.
// http://officeopenxml.com/WPtableCellProperties-Borders.php *
// http://officeopenxml.com/WPsectionBorders.php * Reference: http://officeopenxml.com/WPborders.php
// *
// This describes the CT_Border type. * @see http://officeopenxml.com/WPtableBorders.php
// <xsd:complexType name="CT_Border"> * @see http://officeopenxml.com/WPtableCellProperties-Borders.php
// <xsd:attribute name="val" type="ST_Border" use="required"/> * @see http://officeopenxml.com/WPsectionBorders.php
// <xsd:attribute name="color" type="ST_HexColor" use="optional" default="auto"/> *
// <xsd:attribute name="themeColor" type="ST_ThemeColor" use="optional"/> * ## XSD Schema
// <xsd:attribute name="themeTint" type="ST_UcharHexNumber" use="optional"/> * ```xml
// <xsd:attribute name="themeShade" type="ST_UcharHexNumber" use="optional"/> * <xsd:complexType name="CT_Border">
// <xsd:attribute name="sz" type="ST_EighthPointMeasure" use="optional"/> * <xsd:attribute name="val" type="ST_Border" use="required"/>
// <xsd:attribute name="space" type="ST_PointMeasure" use="optional" default="0"/> * <xsd:attribute name="color" type="ST_HexColor" use="optional" default="auto"/>
// <xsd:attribute name="shadow" type="s:ST_OnOff" use="optional"/> * <xsd:attribute name="themeColor" type="ST_ThemeColor" use="optional"/>
// <xsd:attribute name="frame" type="s:ST_OnOff" use="optional"/> * <xsd:attribute name="themeTint" type="ST_UcharHexNumber" use="optional"/>
// </xsd:complexType> * <xsd:attribute name="themeShade" type="ST_UcharHexNumber" use="optional"/>
* <xsd:attribute name="sz" type="ST_EighthPointMeasure" use="optional"/>
* <xsd:attribute name="space" type="ST_PointMeasure" use="optional" default="0"/>
* <xsd:attribute name="shadow" type="s:ST_OnOff" use="optional"/>
* <xsd:attribute name="frame" type="s:ST_OnOff" use="optional"/>
* </xsd:complexType>
* ```
*
* @module
*/
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { eighthPointMeasureValue, hexColorValue, pointMeasureValue } from "@util/values"; import { eighthPointMeasureValue, hexColorValue, pointMeasureValue } from "@util/values";
/**
* Options for configuring a border element.
*
* @property style - The border style (single, dashed, dotted, etc.)
* @property color - Border color in hex format (e.g., "FF00AA" for purple)
* @property size - Border thickness in eighths of a point (1/8 pt)
* @property space - Spacing offset from the content in points
*/
export type IBorderOptions = { export type IBorderOptions = {
readonly style: (typeof BorderStyle)[keyof typeof BorderStyle]; readonly style: (typeof BorderStyle)[keyof typeof BorderStyle];
/** Border color, in hex (eg 'FF00AA') */ /** Border color, in hex (eg 'FF00AA') */
@@ -32,6 +49,24 @@ export type IBorderOptions = {
readonly space?: number; readonly space?: number;
}; };
/**
* Represents a border element in a WordprocessingML document.
*
* BorderElement is used to create border specifications for paragraphs,
* tables, table cells, and sections. The element name is specified
* during construction to create different border types (top, bottom, left, right, etc.).
*
* @example
* ```typescript
* // Create a top border
* new BorderElement("w:top", {
* style: BorderStyle.SINGLE,
* color: "FF0000",
* size: 24,
* space: 1,
* });
* ```
*/
export class BorderElement extends XmlComponent { export class BorderElement extends XmlComponent {
public constructor(elementName: string, { color, size, space, style }: IBorderOptions) { public constructor(elementName: string, { color, size, space, style }: IBorderOptions) {
super(elementName); super(elementName);
+5
View File
@@ -1 +1,6 @@
/**
* Border module exports.
*
* @module
*/
export * from "./border"; export * from "./border";
+43 -6
View File
@@ -1,14 +1,25 @@
// This represents element type CT_SdtCheckboxSymbol element /**
// <xsd:complexType name="CT_SdtCheckboxSymbol"> * CheckBox symbol module for WordprocessingML documents.
// <xsd:attribute name="font" type="w:ST_String"/> *
// <xsd:attribute name="val" type="w:ST_ShortHexNumber"/> * Provides XML components for checkbox symbol states.
// </xsd:complexType> *
* @module
*/
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { shortHexNumber } from "@util/values"; import { shortHexNumber } from "@util/values";
/**
* Attributes for a checkbox symbol element.
*
* Represents the font and value attributes for checkbox states.
*
* @property val - Hexadecimal character code for the symbol
* @property symbolfont - Font family for rendering the symbol
*/
class CheckboxSymbolAttributes extends XmlAttributeComponent<{ class CheckboxSymbolAttributes extends XmlAttributeComponent<{
/** Hexadecimal character code for the symbol. */
readonly val?: string | number | boolean; readonly val?: string | number | boolean;
/** Font family for rendering the symbol. */
readonly symbolfont?: string; readonly symbolfont?: string;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
@@ -17,6 +28,32 @@ class CheckboxSymbolAttributes extends XmlAttributeComponent<{
}; };
} }
/**
* Represents a checkbox symbol element (checked or unchecked state).
*
* This element defines the appearance of a checkbox in a particular state,
* specifying the Unicode character and font to render.
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_SdtCheckboxSymbol">
* <xsd:attribute name="font" type="w:ST_String"/>
* <xsd:attribute name="val" type="w:ST_ShortHexNumber"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* // Checked state symbol
* new CheckBoxSymbolElement("w14:checkedState", "2612", "MS Gothic");
*
* // Unchecked state symbol
* new CheckBoxSymbolElement("w14:uncheckedState", "2610", "MS Gothic");
*
* // Symbol without explicit font
* new CheckBoxSymbolElement("w14:checked", "1");
* ```
*/
export class CheckBoxSymbolElement extends XmlComponent { export class CheckBoxSymbolElement extends XmlComponent {
public constructor(name: string, val: string, font?: string) { public constructor(name: string, val: string, font?: string) {
super(name); super(name);
+61 -9
View File
@@ -1,27 +1,79 @@
// <xsd:complexType name="CT_SdtCheckbox"> /**
// <xsd:sequence> * CheckBox utility module for WordprocessingML documents.
// <xsd:element name="checked" type="CT_OnOff" minOccurs="0"/> *
// <xsd:element name="checkedState" type="CT_SdtCheckboxSymbol" minOccurs="0"/> * Provides the internal XML structure for checkbox content controls.
// <xsd:element name="uncheckedState" type="CT_SdtCheckboxSymbol" minOccurs="0"/> *
// </xsd:sequence> * @module
// </xsd:complexType> */
// <xsd:element name="checkbox" type="CT_SdtCheckbox"/>
import { CheckBoxSymbolElement } from "@file/checkbox/checkbox-symbol"; import { CheckBoxSymbolElement } from "@file/checkbox/checkbox-symbol";
import { XmlComponent } from "@file/xml-components"; import { XmlComponent } from "@file/xml-components";
/**
* Configuration for a checkbox symbol state (checked or unchecked).
*
* @property value - Hexadecimal character code for the symbol (e.g., "2612" for ☒)
* @property font - Font family to use for rendering the symbol
*/
export type ICheckboxSymbolProperties = { export type ICheckboxSymbolProperties = {
/** Hexadecimal character code for the symbol (e.g., "2612" for ☒). */
readonly value?: string; readonly value?: string;
/** Font family to use for rendering the symbol. */
readonly font?: string; readonly font?: string;
}; };
/**
* Options for configuring a checkbox control.
*
* @property alias - Display name for the checkbox control
* @property checked - Whether the checkbox is initially checked
* @property checkedState - Symbol properties for the checked state
* @property uncheckedState - Symbol properties for the unchecked state
*/
export type ICheckboxSymbolOptions = { export type ICheckboxSymbolOptions = {
/** Display name for the checkbox control. */
readonly alias?: string; readonly alias?: string;
/** Whether the checkbox is initially checked. */
readonly checked?: boolean; readonly checked?: boolean;
/** Symbol properties for the checked state. */
readonly checkedState?: ICheckboxSymbolProperties; readonly checkedState?: ICheckboxSymbolProperties;
/** Symbol properties for the unchecked state. */
readonly uncheckedState?: ICheckboxSymbolProperties; readonly uncheckedState?: ICheckboxSymbolProperties;
}; };
/**
* Represents the checkbox element within a structured document tag.
*
* This class generates the w14:checkbox element that defines the checkbox behavior,
* including its checked state and the symbols used for checked and unchecked states.
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_SdtCheckbox">
* <xsd:sequence>
* <xsd:element name="checked" type="CT_OnOff" minOccurs="0"/>
* <xsd:element name="checkedState" type="CT_SdtCheckboxSymbol" minOccurs="0"/>
* <xsd:element name="uncheckedState" type="CT_SdtCheckboxSymbol" minOccurs="0"/>
* </xsd:sequence>
* </xsd:complexType>
* <xsd:element name="checkbox" type="CT_SdtCheckbox"/>
* ```
*
* @example
* ```typescript
* // Default checkbox (unchecked with default symbols)
* new CheckBoxUtil();
*
* // Checked checkbox with defaults
* new CheckBoxUtil({ checked: true });
*
* // Custom symbols
* new CheckBoxUtil({
* checked: false,
* checkedState: { value: "2611", font: "Wingdings" },
* uncheckedState: { value: "2610", font: "Wingdings" },
* });
* ```
*/
export class CheckBoxUtil extends XmlComponent { export class CheckBoxUtil extends XmlComponent {
private readonly DEFAULT_UNCHECKED_SYMBOL: string = "2610"; private readonly DEFAULT_UNCHECKED_SYMBOL: string = "2610";
private readonly DEFAULT_CHECKED_SYMBOL: string = "2612"; private readonly DEFAULT_CHECKED_SYMBOL: string = "2612";
+27 -2
View File
@@ -17,13 +17,38 @@ import { CheckBoxUtil, ICheckboxSymbolOptions } from "./checkbox-util";
* Represents an interactive checkbox in a WordprocessingML document. * Represents an interactive checkbox in a WordprocessingML document.
* *
* CheckBox creates a content control with checkbox functionality, * CheckBox creates a content control with checkbox functionality,
* displaying a checked or unchecked symbol based on its state. * displaying a checked or unchecked symbol based on its state. The checkbox
* is implemented using structured document tags (w:sdt) with checkbox-specific
* properties.
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_SdtCheckbox">
* <xsd:sequence>
* <xsd:element name="checked" type="CT_OnOff" minOccurs="0"/>
* <xsd:element name="checkedState" type="CT_SdtCheckboxSymbol" minOccurs="0"/>
* <xsd:element name="uncheckedState" type="CT_SdtCheckboxSymbol" minOccurs="0"/>
* </xsd:sequence>
* </xsd:complexType>
* <xsd:element name="checkbox" type="CT_SdtCheckbox"/>
* ```
* *
* @example * @example
* ```typescript * ```typescript
* // Simple checkbox
* new CheckBox({ checked: true });
*
* // Checkbox with custom alias
* new CheckBox({
* checked: false,
* alias: "Accept Terms",
* });
*
* // Checkbox with custom symbols
* new CheckBox({ * new CheckBox({
* checked: true, * checked: true,
* alias: "Accept Terms", * checkedState: { value: "2611", font: "Wingdings" },
* uncheckedState: { value: "2610", font: "Wingdings" },
* }); * });
* ``` * ```
*/ */
+5
View File
@@ -1,3 +1,8 @@
/**
* CheckBox module exports for WordprocessingML documents.
*
* @module
*/
export * from "./checkbox-util"; export * from "./checkbox-util";
export * from "./checkbox-symbol"; export * from "./checkbox-symbol";
export * from "./checkbox"; export * from "./checkbox";
@@ -1,6 +1,19 @@
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
/**
* Attributes for the Types (Content Types) element.
*
* Defines the XML namespace for the content types part.
*
* @example
* ```typescript
* new ContentTypeAttributes({
* xmlns: "http://schemas.openxmlformats.org/package/2006/content-types"
* });
* ```
*/
export class ContentTypeAttributes extends XmlAttributeComponent<{ export class ContentTypeAttributes extends XmlAttributeComponent<{
/** XML namespace for content types */
readonly xmlns?: string; readonly xmlns?: string;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
+17
View File
@@ -21,6 +21,13 @@ import { Override } from "./override/override";
* MIME content types, enabling applications to process each part correctly. * MIME content types, enabling applications to process each part correctly.
* *
* Reference: http://officeopenxml.com/anatomyofOOXML.php * Reference: http://officeopenxml.com/anatomyofOOXML.php
*
* @example
* ```typescript
* const contentTypes = new ContentTypes();
* contentTypes.addHeader(1); // Add header1.xml
* contentTypes.addFooter(1); // Add footer1.xml
* ```
*/ */
export class ContentTypes extends XmlComponent { export class ContentTypes extends XmlComponent {
public constructor() { public constructor() {
@@ -57,12 +64,22 @@ export class ContentTypes extends XmlComponent {
this.root.push(new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", "/word/fontTable.xml")); this.root.push(new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", "/word/fontTable.xml"));
} }
/**
* Registers a footer part in the content types.
*
* @param index - Footer index number (e.g., 1 for footer1.xml)
*/
public addFooter(index: number): void { public addFooter(index: number): void {
this.root.push( this.root.push(
new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml", `/word/footer${index}.xml`), new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml", `/word/footer${index}.xml`),
); );
} }
/**
* Registers a header part in the content types.
*
* @param index - Header index number (e.g., 1 for header1.xml)
*/
public addHeader(index: number): void { public addHeader(index: number): void {
this.root.push( this.root.push(
new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml", `/word/header${index}.xml`), new Override("application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml", `/word/header${index}.xml`),
@@ -1,7 +1,22 @@
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
/**
* Attributes for a Default content type element.
*
* Defines the mapping between a file extension and its MIME content type.
*
* @example
* ```typescript
* new DefaultAttributes({
* contentType: "image/png",
* extension: "png"
* });
* ```
*/
export class DefaultAttributes extends XmlAttributeComponent<{ export class DefaultAttributes extends XmlAttributeComponent<{
/** MIME content type for files with this extension */
readonly contentType: string; readonly contentType: string;
/** File extension (without the dot) */
readonly extension?: string; readonly extension?: string;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
+16
View File
@@ -2,6 +2,22 @@ import { XmlComponent } from "@file/xml-components";
import { DefaultAttributes } from "./default-attributes"; import { DefaultAttributes } from "./default-attributes";
/**
* Represents a default content type mapping by file extension.
*
* Default elements map file extensions (e.g., "png", "xml") to MIME content types.
* This tells the package reader what type of content to expect for files with
* a given extension.
*
* @example
* ```typescript
* // Map .png files to image/png content type
* new Default("image/png", "png");
*
* // Map .xml files to application/xml content type
* new Default("application/xml", "xml");
* ```
*/
export class Default extends XmlComponent { export class Default extends XmlComponent {
public constructor(contentType: string, extension?: string) { public constructor(contentType: string, extension?: string) {
super("Default"); super("Default");
@@ -1,7 +1,22 @@
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
/**
* Attributes for an Override content type element.
*
* Defines the content type override for a specific part path.
*
* @example
* ```typescript
* new OverrideAttributes({
* contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
* partName: "/word/document.xml"
* });
* ```
*/
export class OverrideAttributes extends XmlAttributeComponent<{ export class OverrideAttributes extends XmlAttributeComponent<{
/** MIME content type for this specific part */
readonly contentType: string; readonly contentType: string;
/** Full path to the part in the package (e.g., "/word/document.xml") */
readonly partName?: string; readonly partName?: string;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
@@ -2,6 +2,28 @@ import { XmlComponent } from "@file/xml-components";
import { OverrideAttributes } from "./override-attributes"; import { OverrideAttributes } from "./override-attributes";
/**
* Represents a content type override for a specific part.
*
* Override elements map specific part paths to MIME content types,
* taking precedence over default extension mappings. This is used for
* important parts like document.xml, styles.xml, etc.
*
* @example
* ```typescript
* // Override content type for the main document part
* new Override(
* "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
* "/word/document.xml"
* );
*
* // Override for a header part
* new Override(
* "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
* "/word/header1.xml"
* );
* ```
*/
export class Override extends XmlComponent { export class Override extends XmlComponent {
public constructor(contentType: string, partName?: string) { public constructor(contentType: string, partName?: string) {
super("Override"); super("Override");
+5
View File
@@ -1 +1,6 @@
/**
* Core properties module exports.
*
* @module
*/
export * from "./properties"; export * from "./properties";
+87 -24
View File
@@ -1,3 +1,12 @@
/**
* Core Properties module for WordprocessingML documents.
*
* Provides support for document metadata based on Dublin Core properties.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCore.xsd
*
* @module
*/
import { FontOptions } from "@file/fonts/font-table"; import { FontOptions } from "@file/fonts/font-table";
import { ICommentsOptions } from "@file/paragraph/run/comment-run"; import { ICommentsOptions } from "@file/paragraph/run/comment-run";
import { IHyphenationOptions } from "@file/settings"; import { IHyphenationOptions } from "@file/settings";
@@ -13,6 +22,32 @@ import { INumberingOptions } from "../numbering";
import { Paragraph } from "../paragraph"; import { Paragraph } from "../paragraph";
import { IStylesOptions } from "../styles"; import { IStylesOptions } from "../styles";
/**
* Options for configuring document properties.
*
* @property sections - Document section configurations
* @property title - Document title
* @property subject - Document subject
* @property creator - Document creator/author
* @property keywords - Document keywords for searchability
* @property description - Document description
* @property lastModifiedBy - User who last modified the document
* @property revision - Revision number
* @property externalStyles - External stylesheet reference
* @property styles - Document styles configuration
* @property numbering - Numbering configuration
* @property comments - Document comments configuration
* @property footnotes - Document footnotes
* @property background - Document background settings
* @property features - Document features like track changes
* @property compatabilityModeVersion - Compatibility mode version
* @property compatibility - Compatibility settings
* @property customProperties - Custom document properties
* @property evenAndOddHeaderAndFooters - Enable different headers/footers for even/odd pages
* @property defaultTabStop - Default tab stop width
* @property fonts - Font configurations
* @property hyphenation - Hyphenation settings
*/
export type IPropertiesOptions = { export type IPropertiesOptions = {
readonly sections: readonly ISectionOptions[]; readonly sections: readonly ISectionOptions[];
readonly title?: string; readonly title?: string;
@@ -48,30 +83,50 @@ export type IPropertiesOptions = {
readonly hyphenation?: IHyphenationOptions; readonly hyphenation?: IHyphenationOptions;
}; };
// <xs:element name="coreProperties" type="CT_CoreProperties"/> /**
* Represents the core properties of a WordprocessingML document.
/* cSpell:disable */ *
// <xs:complexType name="CT_CoreProperties"> * Core properties contain document metadata based on Dublin Core elements,
// <xs:all> * including title, subject, creator, keywords, description, and modification tracking.
// <xs:element name="category" minOccurs="0" maxOccurs="1" type="xs:string"/> *
// <xs:element name="contentStatus" minOccurs="0" maxOccurs="1" type="xs:string"/> * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCore.xsd
// <xs:element ref="dcterms:created" minOccurs="0" maxOccurs="1"/> *
// <xs:element ref="dc:creator" minOccurs="0" maxOccurs="1"/> * ## XSD Schema
// <xs:element ref="dc:description" minOccurs="0" maxOccurs="1"/> * ```xml
// <xs:element ref="dc:identifier" minOccurs="0" maxOccurs="1"/> * <xs:complexType name="CT_CoreProperties">
// <xs:element name="keywords" minOccurs="0" maxOccurs="1" type="CT_Keywords"/> * <xs:all>
// <xs:element ref="dc:language" minOccurs="0" maxOccurs="1"/> * <xs:element name="category" minOccurs="0" maxOccurs="1" type="xs:string"/>
// <xs:element name="lastModifiedBy" minOccurs="0" maxOccurs="1" type="xs:string"/> * <xs:element name="contentStatus" minOccurs="0" maxOccurs="1" type="xs:string"/>
// <xs:element name="lastPrinted" minOccurs="0" maxOccurs="1" type="xs:dateTime"/> * <xs:element ref="dcterms:created" minOccurs="0" maxOccurs="1"/>
// <xs:element ref="dcterms:modified" minOccurs="0" maxOccurs="1"/> * <xs:element ref="dc:creator" minOccurs="0" maxOccurs="1"/>
// <xs:element name="revision" minOccurs="0" maxOccurs="1" type="xs:string"/> * <xs:element ref="dc:description" minOccurs="0" maxOccurs="1"/>
// <xs:element ref="dc:subject" minOccurs="0" maxOccurs="1"/> * <xs:element ref="dc:identifier" minOccurs="0" maxOccurs="1"/>
// <xs:element ref="dc:title" minOccurs="0" maxOccurs="1"/> * <xs:element name="keywords" minOccurs="0" maxOccurs="1" type="CT_Keywords"/>
// <xs:element name="version" minOccurs="0" maxOccurs="1" type="xs:string"/> * <xs:element ref="dc:language" minOccurs="0" maxOccurs="1"/>
// </xs:all> * <xs:element name="lastModifiedBy" minOccurs="0" maxOccurs="1" type="xs:string"/>
// </xs:complexType> * <xs:element name="lastPrinted" minOccurs="0" maxOccurs="1" type="xs:dateTime"/>
/* cSpell:enable */ * <xs:element ref="dcterms:modified" minOccurs="0" maxOccurs="1"/>
* <xs:element name="revision" minOccurs="0" maxOccurs="1" type="xs:string"/>
* <xs:element ref="dc:subject" minOccurs="0" maxOccurs="1"/>
* <xs:element ref="dc:title" minOccurs="0" maxOccurs="1"/>
* <xs:element name="version" minOccurs="0" maxOccurs="1" type="xs:string"/>
* </xs:all>
* </xs:complexType>
* ```
*
* @example
* ```typescript
* const coreProps = new CoreProperties({
* title: "My Document",
* subject: "Sample Document",
* creator: "John Doe",
* keywords: "docx, example",
* description: "A sample document",
* lastModifiedBy: "Jane Doe",
* revision: 1
* });
* ```
*/
export class CoreProperties extends XmlComponent { export class CoreProperties extends XmlComponent {
public constructor(options: Omit<IPropertiesOptions, "sections">) { public constructor(options: Omit<IPropertiesOptions, "sections">) {
super("cp:coreProperties"); super("cp:coreProperties");
@@ -102,10 +157,18 @@ export class CoreProperties extends XmlComponent {
} }
} }
/**
* Attributes for timestamp elements in core properties.
* Specifies the W3C DateTime Format type for timestamps.
*/
class TimestampElementProperties extends XmlAttributeComponent<{ readonly type: string }> { class TimestampElementProperties extends XmlAttributeComponent<{ readonly type: string }> {
protected readonly xmlKeys = { type: "xsi:type" }; protected readonly xmlKeys = { type: "xsi:type" };
} }
/**
* Represents a timestamp element (created or modified date).
* Uses W3C DateTime Format (dcterms:W3CDTF) for dates.
*/
class TimestampElement extends XmlComponent { class TimestampElement extends XmlComponent {
public constructor(name: string) { public constructor(name: string) {
super(name); super(name);
@@ -1,7 +1,24 @@
/**
* Custom Properties Attributes module for WordprocessingML documents.
*
* Provides namespace attributes for custom document properties.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd
*
* @module
*/
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
/**
* XML namespace attributes for the custom properties element.
*
* @property xmlns - Main namespace for custom properties
* @property vt - Namespace for variant types
*/
export class CustomPropertiesAttributes extends XmlAttributeComponent<{ export class CustomPropertiesAttributes extends XmlAttributeComponent<{
/** Main namespace for custom properties */
readonly xmlns: string; readonly xmlns: string;
/** Namespace for variant types */
readonly vt: string; readonly vt: string;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
@@ -1,8 +1,42 @@
/**
* Custom Properties module for WordprocessingML documents.
*
* Provides support for managing custom document properties collection.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd
*
* @module
*/
import { IContext, IXmlableObject, XmlComponent } from "@file/xml-components"; import { IContext, IXmlableObject, XmlComponent } from "@file/xml-components";
import { CustomPropertiesAttributes } from "./custom-properties-attributes"; import { CustomPropertiesAttributes } from "./custom-properties-attributes";
import { CustomProperty, ICustomPropertyOptions } from "./custom-property"; import { CustomProperty, ICustomPropertyOptions } from "./custom-property";
/**
* Represents the collection of custom document properties.
*
* Custom properties allow storing arbitrary metadata as name-value pairs.
* Each property is assigned a unique ID starting from 2 (per Office specification).
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_CustomProperties">
* <xsd:sequence>
* <xsd:element name="property" type="CT_Property" minOccurs="0" maxOccurs="unbounded"/>
* </xsd:sequence>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* const customProps = new CustomProperties([
* { name: "Department", value: "Engineering" },
* { name: "Project", value: "Alpha" }
* ]);
* ```
*/
export class CustomProperties extends XmlComponent { export class CustomProperties extends XmlComponent {
// eslint-disable-next-line functional/prefer-readonly-type // eslint-disable-next-line functional/prefer-readonly-type
private nextId: number; private nextId: number;
@@ -1,12 +1,31 @@
/**
* Custom Property Attributes module for WordprocessingML documents.
*
* Provides attributes for individual custom document properties.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd
*
* @module
*/
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
/**
* XML attributes for a custom property element.
*
* @property formatId - Format identifier (GUID)
* @property pid - Property identifier (unique ID)
* @property name - Property name
*/
export class CustomPropertyAttributes extends XmlAttributeComponent<{ export class CustomPropertyAttributes extends XmlAttributeComponent<{
readonly fmtid: string; /** Format identifier (GUID) */
readonly formatId: string;
/** Property identifier (unique ID) */
readonly pid: string; readonly pid: string;
/** Property name */
readonly name: string; readonly name: string;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
fmtid: "fmtid", formatId: "fmtid",
pid: "pid", pid: "pid",
name: "name", name: "name",
}; };
+50 -1
View File
@@ -1,18 +1,63 @@
/**
* Custom Property module for WordprocessingML documents.
*
* Provides support for individual custom document properties.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd
*
* @module
*/
import { XmlComponent } from "@file/xml-components"; import { XmlComponent } from "@file/xml-components";
import { CustomPropertyAttributes } from "./custom-property-attributes"; import { CustomPropertyAttributes } from "./custom-property-attributes";
/**
* Options for creating a custom property.
*
* @property name - The property name
* @property value - The property value (as string)
*/
export type ICustomPropertyOptions = { export type ICustomPropertyOptions = {
/** The property name */
readonly name: string; readonly name: string;
/** The property value (as string) */
readonly value: string; readonly value: string;
}; };
/**
* Represents a single custom document property.
*
* Custom properties allow storing arbitrary key-value pairs in the document metadata.
* Each property has a unique name and a string value.
*
* Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCustom.xsd
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_Property">
* <xsd:sequence>
* <xsd:element name="lpwstr" type="xsd:string" minOccurs="0"/>
* </xsd:sequence>
* <xsd:attribute name="fmtid" type="ST_Guid" use="required"/>
* <xsd:attribute name="pid" type="xsd:int" use="required"/>
* <xsd:attribute name="name" type="xsd:string"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* const customProp = new CustomProperty(2, {
* name: "Department",
* value: "Engineering"
* });
* ```
*/
export class CustomProperty extends XmlComponent { export class CustomProperty extends XmlComponent {
public constructor(id: number, properties: ICustomPropertyOptions) { public constructor(id: number, properties: ICustomPropertyOptions) {
super("property"); super("property");
this.root.push( this.root.push(
new CustomPropertyAttributes({ new CustomPropertyAttributes({
fmtid: "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", formatId: "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}",
pid: id.toString(), pid: id.toString(),
name: properties.name, name: properties.name,
}), }),
@@ -21,6 +66,10 @@ export class CustomProperty extends XmlComponent {
} }
} }
/**
* Represents the value of a custom property.
* Uses the variant type "long pointer to wide string" for string values.
*/
export class CustomPropertyValue extends XmlComponent { export class CustomPropertyValue extends XmlComponent {
public constructor(value: string) { public constructor(value: string) {
super("vt:lpwstr"); super("vt:lpwstr");
+5
View File
@@ -1,2 +1,7 @@
/**
* Custom properties module exports.
*
* @module
*/
export * from "./custom-properties"; export * from "./custom-properties";
export * from "./custom-property"; export * from "./custom-property";
+34
View File
@@ -1,3 +1,12 @@
/**
* Document wrapper module for WordprocessingML documents.
*
* This module provides wrappers that combine the main document/header/footer
* views with their associated relationships, enabling proper management of
* document parts and their references.
*
* @module
*/
import { Document, IDocumentOptions } from "./document"; import { Document, IDocumentOptions } from "./document";
import { Footer } from "./footer/footer"; import { Footer } from "./footer/footer";
import { FootNotes } from "./footnotes"; import { FootNotes } from "./footnotes";
@@ -5,11 +14,36 @@ import { Header } from "./header/header";
import { Relationships } from "./relationships"; import { Relationships } from "./relationships";
import { XmlComponent } from "./xml-components"; import { XmlComponent } from "./xml-components";
/**
* Interface for document view wrappers.
*
* ViewWrappers combine a document part (view) with its relationships,
* providing a unified interface for managing document components.
*
* @property View - The document part (Document, Header, Footer, etc.)
* @property Relationships - The relationships associated with this view
*/
export type IViewWrapper = { export type IViewWrapper = {
readonly View: Document | Footer | Header | FootNotes | XmlComponent; readonly View: Document | Footer | Header | FootNotes | XmlComponent;
readonly Relationships: Relationships; readonly Relationships: Relationships;
}; };
/**
* Wrapper for the main document body.
*
* DocumentWrapper combines the main Document view with its Relationships,
* managing the primary content of the .docx file along with references to
* images, hyperlinks, and other linked resources.
*
* @example
* ```typescript
* const wrapper = new DocumentWrapper({
* sections: [{
* children: [new Paragraph("Hello World")],
* }],
* });
* ```
*/
export class DocumentWrapper implements IViewWrapper { export class DocumentWrapper implements IViewWrapper {
private readonly document: Document; private readonly document: Document;
private readonly relationships: Relationships; private readonly relationships: Relationships;
+58 -6
View File
@@ -1,3 +1,10 @@
/**
* Document body module for WordprocessingML documents.
*
* Reference: http://officeopenxml.com/WPdocument.php
*
* @module
*/
import { Paragraph, ParagraphProperties } from "@file/paragraph"; import { Paragraph, ParagraphProperties } from "@file/paragraph";
import { IContext, IXmlableObject, XmlComponent } from "@file/xml-components"; import { IContext, IXmlableObject, XmlComponent } from "@file/xml-components";
@@ -9,6 +16,10 @@ import { ISectionPropertiesOptions, SectionProperties } from "./section-properti
* The body element is the container for all block-level content in the document. * The body element is the container for all block-level content in the document.
* This includes paragraphs, tables, and section properties that define page layout. * This includes paragraphs, tables, and section properties that define page layout.
* *
* The body supports multiple sections, where each section (except the last one) must
* have its section properties stored in a paragraph's properties at the end of that
* section. The last section's properties are stored as a direct child of the body element.
*
* Reference: http://officeopenxml.com/WPdocument.php * Reference: http://officeopenxml.com/WPdocument.php
* *
* ## XSD Schema * ## XSD Schema
@@ -20,6 +31,26 @@ import { ISectionPropertiesOptions, SectionProperties } from "./section-properti
* </xsd:sequence> * </xsd:sequence>
* </xsd:complexType> * </xsd:complexType>
* ``` * ```
*
* @example
* ```typescript
* // Body is typically created internally by the Document class
* const doc = new Document({});
* const body = doc.Body;
*
* // Add content to the body via Document.add()
* doc.add(new Paragraph("Content in first section"));
*
* // Add a new section
* body.addSection({
* page: {
* size: { width: 12240, height: 15840 },
* },
* });
*
* // Content after addSection belongs to the new section
* doc.add(new Paragraph("Content in second section"));
* ```
*/ */
export class Body extends XmlComponent { export class Body extends XmlComponent {
// eslint-disable-next-line functional/prefer-readonly-type // eslint-disable-next-line functional/prefer-readonly-type
@@ -30,13 +61,17 @@ export class Body extends XmlComponent {
} }
/** /**
* Adds new section properties. * Adds new section properties to the document body.
* Note: Previous section is created in paragraph after the current element, and then new section will be added.
* The spec says:
* - section element should be in the last paragraph of the section
* - last section should be direct child of body
* *
* @param options new section options * Creates a new section by moving the previous section's properties into a paragraph
* at the end of that section, and then adding the new section as the current section.
*
* According to the OOXML specification:
* - Section properties for all sections except the last must be stored in a paragraph's
* properties (pPr/sectPr) at the end of each section
* - The last section's properties are stored as a direct child of the body element (w:body/w:sectPr)
*
* @param options - Section properties configuration (page size, margins, headers, footers, etc.)
*/ */
public addSection(options: ISectionPropertiesOptions): void { public addSection(options: ISectionPropertiesOptions): void {
const currentSection = this.sections.pop() as SectionProperties; const currentSection = this.sections.pop() as SectionProperties;
@@ -45,6 +80,15 @@ export class Body extends XmlComponent {
this.sections.push(new SectionProperties(options)); this.sections.push(new SectionProperties(options));
} }
/**
* Prepares the body element for XML serialization.
*
* Ensures that the last section's properties are placed as a direct child of the body
* element, as required by the OOXML specification.
*
* @param context - The XML serialization context
* @returns The prepared XML object or undefined
*/
public prepForXml(context: IContext): IXmlableObject | undefined { public prepForXml(context: IContext): IXmlableObject | undefined {
if (this.sections.length === 1) { if (this.sections.length === 1) {
this.root.splice(0, 1); this.root.splice(0, 1);
@@ -54,6 +98,14 @@ export class Body extends XmlComponent {
return super.prepForXml(context); return super.prepForXml(context);
} }
/**
* Adds a block-level component to the body.
*
* This method is used internally by the Document class to add paragraphs,
* tables, and other block-level elements to the document body.
*
* @param component - The XML component to add (paragraph, table, etc.)
*/
public push(component: XmlComponent): void { public push(component: XmlComponent): void {
this.root.push(component); this.root.push(component);
} }
+5
View File
@@ -1,2 +1,7 @@
/**
* Document body module exports.
*
* @module
*/
export * from "./body"; export * from "./body";
export * from "./section-properties"; export * from "./section-properties";
@@ -1,2 +1,7 @@
/**
* Section properties module exports.
*
* @module
*/
export * from "./section-properties"; export * from "./section-properties";
export * from "./properties"; export * from "./properties";
@@ -1,16 +1,53 @@
/**
* Column module for WordprocessingML section properties.
*
* Defines individual column properties within multi-column layouts.
*
* Reference: http://officeopenxml.com/WPsectionPr.php
*
* @module
*/
import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { NextAttributeComponent, XmlComponent } from "@file/xml-components";
import { PositiveUniversalMeasure, twipsMeasureValue } from "@util/values"; import { PositiveUniversalMeasure, twipsMeasureValue } from "@util/values";
// <xsd:complexType name="CT_Column"> /**
// <xsd:attribute name="w" type="s:ST_TwipsMeasure" use="optional" /> * Options for configuring individual column properties.
// <xsd:attribute name="space" type="s:ST_TwipsMeasure" use="optional" default="0" /> *
// </xsd:complexType> * @property width - Column width in twips or universal measure
* @property space - Space after column in twips or universal measure (default: 0)
*/
type IColumnAttributes = { type IColumnAttributes = {
/** Column width in twips or universal measure */
readonly width: number | PositiveUniversalMeasure; readonly width: number | PositiveUniversalMeasure;
/** Space after column in twips or universal measure (default: 0) */
readonly space?: number | PositiveUniversalMeasure; readonly space?: number | PositiveUniversalMeasure;
}; };
/**
* Represents a column definition (col) in a multi-column section layout.
*
* This element defines the width and spacing for an individual column when
* using unequal column widths in a section.
*
* Reference: http://officeopenxml.com/WPsectionPr.php
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_Column">
* <xsd:attribute name="w" type="s:ST_TwipsMeasure" use="optional" />
* <xsd:attribute name="space" type="s:ST_TwipsMeasure" use="optional" default="0" />
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* // Create a column with specific width and spacing
* new Column({
* width: 3000,
* space: 720
* });
* ```
*/
export class Column extends XmlComponent { export class Column extends XmlComponent {
public constructor({ width, space }: IColumnAttributes) { public constructor({ width, space }: IColumnAttributes) {
super("w:col"); super("w:col");
@@ -1,25 +1,80 @@
/**
* Columns module for WordprocessingML section properties.
*
* Defines multi-column layouts within document sections.
*
* Reference: http://officeopenxml.com/WPsectionPr.php
*
* @module
*/
import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { NextAttributeComponent, XmlComponent } from "@file/xml-components";
import { PositiveUniversalMeasure, decimalNumber, twipsMeasureValue } from "@util/values"; import { PositiveUniversalMeasure, decimalNumber, twipsMeasureValue } from "@util/values";
import { Column } from "./column"; import { Column } from "./column";
// <xsd:complexType name="CT_Columns"> /**
// <xsd:sequence minOccurs="0"> * Options for configuring column layout in a section.
// <xsd:element name="col" type="CT_Column" maxOccurs="45"/> *
// </xsd:sequence> * @property space - Spacing between columns in twips (default: 720)
// <xsd:attribute name="equalWidth" type="s:ST_OnOff" use="optional"/> * @property count - Number of columns (default: 1)
// <xsd:attribute name="space" type="s:ST_TwipsMeasure" use="optional" default="720"/> * @property separate - Whether to draw vertical separator lines between columns
// <xsd:attribute name="num" type="ST_DecimalNumber" use="optional" default="1"/> * @property equalWidth - Whether all columns have equal width
// <xsd:attribute name="sep" type="s:ST_OnOff" use="optional"/> * @property children - Individual column definitions (used when equalWidth is false)
// </xsd:complexType> */
export type IColumnsAttributes = { export type IColumnsAttributes = {
/** Spacing between columns in twips (default: 720) */
readonly space?: number | PositiveUniversalMeasure; readonly space?: number | PositiveUniversalMeasure;
/** Number of columns (default: 1) */
readonly count?: number; readonly count?: number;
/** Whether to draw vertical separator lines between columns */
readonly separate?: boolean; readonly separate?: boolean;
/** Whether all columns have equal width */
readonly equalWidth?: boolean; readonly equalWidth?: boolean;
/** Individual column definitions (used when equalWidth is false, max: 45) */
readonly children?: readonly Column[]; readonly children?: readonly Column[];
}; };
/**
* Represents column layout settings (cols) for a document section.
*
* This element defines the multi-column layout properties for a section,
* including column count, spacing, and whether columns have equal or custom widths.
*
* Reference: http://officeopenxml.com/WPsectionPr.php
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_Columns">
* <xsd:sequence minOccurs="0">
* <xsd:element name="col" type="CT_Column" maxOccurs="45"/>
* </xsd:sequence>
* <xsd:attribute name="equalWidth" type="s:ST_OnOff" use="optional"/>
* <xsd:attribute name="space" type="s:ST_TwipsMeasure" use="optional" default="720"/>
* <xsd:attribute name="num" type="ST_DecimalNumber" use="optional" default="1"/>
* <xsd:attribute name="sep" type="s:ST_OnOff" use="optional"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* // Two equal-width columns with separator
* new Columns({
* count: 2,
* space: 720,
* separate: true,
* equalWidth: true
* });
*
* // Custom column widths
* new Columns({
* equalWidth: false,
* children: [
* new Column({ width: 3000, space: 720 }),
* new Column({ width: 4000, space: 0 })
* ]
* });
* ```
*/
export class Columns extends XmlComponent { export class Columns extends XmlComponent {
public constructor({ space, count, separate, equalWidth, children }: IColumnsAttributes) { public constructor({ space, count, separate, equalWidth, children }: IColumnsAttributes) {
super("w:cols"); super("w:cols");
@@ -1,3 +1,8 @@
/**
* Section properties components module exports.
*
* @module
*/
export * from "./column"; export * from "./column";
export * from "./columns"; export * from "./columns";
export * from "./doc-grid"; export * from "./doc-grid";
@@ -1,54 +1,113 @@
// http://officeopenxml.com/WPsectionBorders.php /**
* Page borders module for WordprocessingML section properties.
*
* Defines borders around pages in a document section.
*
* Reference: http://officeopenxml.com/WPsectionBorders.php
*
* @module
*/
import { BorderElement, IBorderOptions } from "@file/border"; import { BorderElement, IBorderOptions } from "@file/border";
import { IgnoreIfEmptyXmlComponent, XmlAttributeComponent } from "@file/xml-components"; import { IgnoreIfEmptyXmlComponent, XmlAttributeComponent } from "@file/xml-components";
// <xsd:simpleType name="ST_PageBorderDisplay"> /**
// <xsd:restriction base="xsd:string"> * Specifies which pages display the page border.
// <xsd:enumeration value="allPages"/> *
// <xsd:enumeration value="firstPage"/> * ## XSD Schema
// <xsd:enumeration value="notFirstPage"/> * ```xml
// </xsd:restriction> * <xsd:simpleType name="ST_PageBorderDisplay">
// </xsd:simpleType> * <xsd:restriction base="xsd:string">
* <xsd:enumeration value="allPages"/>
* <xsd:enumeration value="firstPage"/>
* <xsd:enumeration value="notFirstPage"/>
* </xsd:restriction>
* </xsd:simpleType>
* ```
*/
export const PageBorderDisplay = { export const PageBorderDisplay = {
/** Display border on all pages */
ALL_PAGES: "allPages", ALL_PAGES: "allPages",
/** Display border only on first page */
FIRST_PAGE: "firstPage", FIRST_PAGE: "firstPage",
/** Display border on all pages except first page */
NOT_FIRST_PAGE: "notFirstPage", NOT_FIRST_PAGE: "notFirstPage",
} as const; } as const;
// <xsd:simpleType name="ST_PageBorderOffset"> /**
// <xsd:restriction base="xsd:string"> * Specifies whether page border is positioned relative to page edge or text.
// <xsd:enumeration value="page"/> *
// <xsd:enumeration value="text"/> * ## XSD Schema
// </xsd:restriction> * ```xml
// </xsd:simpleType> * <xsd:simpleType name="ST_PageBorderOffset">
* <xsd:restriction base="xsd:string">
* <xsd:enumeration value="page"/>
* <xsd:enumeration value="text"/>
* </xsd:restriction>
* </xsd:simpleType>
* ```
*/
export const PageBorderOffsetFrom = { export const PageBorderOffsetFrom = {
/** Position border relative to page edge */
PAGE: "page", PAGE: "page",
/** Position border relative to text (default) */
TEXT: "text", TEXT: "text",
} as const; } as const;
// <xsd:simpleType name="ST_PageBorderZOrder"> /**
// <xsd:restriction base="xsd:string"> * Specifies z-order of page border relative to intersecting objects.
// <xsd:enumeration value="front"/> *
// <xsd:enumeration value="back"/> * ## XSD Schema
// </xsd:restriction> * ```xml
// </xsd:simpleType> * <xsd:simpleType name="ST_PageBorderZOrder">
* <xsd:restriction base="xsd:string">
* <xsd:enumeration value="front"/>
* <xsd:enumeration value="back"/>
* </xsd:restriction>
* </xsd:simpleType>
* ```
*/
export const PageBorderZOrder = { export const PageBorderZOrder = {
/** Display border behind page contents */
BACK: "back", BACK: "back",
/** Display border in front of page contents (default) */
FRONT: "front", FRONT: "front",
} as const; } as const;
/**
* Attributes for configuring page border behavior.
*
* @property display - Which pages display the border
* @property offsetFrom - Whether border is positioned relative to page or text
* @property zOrder - Whether border appears in front or behind page contents
*/
export type IPageBorderAttributes = { export type IPageBorderAttributes = {
/** Which pages display the border */
readonly display?: (typeof PageBorderDisplay)[keyof typeof PageBorderDisplay]; readonly display?: (typeof PageBorderDisplay)[keyof typeof PageBorderDisplay];
/** Whether border is positioned relative to page or text (default: text) */
readonly offsetFrom?: (typeof PageBorderOffsetFrom)[keyof typeof PageBorderOffsetFrom]; readonly offsetFrom?: (typeof PageBorderOffsetFrom)[keyof typeof PageBorderOffsetFrom];
/** Whether border appears in front or behind page contents (default: front) */
readonly zOrder?: (typeof PageBorderZOrder)[keyof typeof PageBorderZOrder]; readonly zOrder?: (typeof PageBorderZOrder)[keyof typeof PageBorderZOrder];
}; };
/**
* Options for configuring page borders.
*
* @property pageBorders - General page border attributes (display, offset, z-order)
* @property pageBorderTop - Top border styling
* @property pageBorderRight - Right border styling
* @property pageBorderBottom - Bottom border styling
* @property pageBorderLeft - Left border styling
*/
export type IPageBordersOptions = { export type IPageBordersOptions = {
/** General page border attributes (display, offset, z-order) */
readonly pageBorders?: IPageBorderAttributes; readonly pageBorders?: IPageBorderAttributes;
/** Top border styling */
readonly pageBorderTop?: IBorderOptions; readonly pageBorderTop?: IBorderOptions;
/** Right border styling */
readonly pageBorderRight?: IBorderOptions; readonly pageBorderRight?: IBorderOptions;
/** Bottom border styling */
readonly pageBorderBottom?: IBorderOptions; readonly pageBorderBottom?: IBorderOptions;
/** Left border styling */
readonly pageBorderLeft?: IBorderOptions; readonly pageBorderLeft?: IBorderOptions;
}; };
@@ -60,17 +119,43 @@ class PageBordersAttributes extends XmlAttributeComponent<IPageBorderAttributes>
}; };
} }
// <xsd:complexType name="CT_PageBorders"> /**
// <xsd:sequence> * Represents page borders (pgBorders) for a document section.
// <xsd:element name="top" type="CT_TopPageBorder" minOccurs="0"/> *
// <xsd:element name="left" type="CT_PageBorder" minOccurs="0"/> * This element specifies the borders to display around pages in a section,
// <xsd:element name="bottom" type="CT_BottomPageBorder" minOccurs="0"/> * including which pages display the borders and how they are positioned.
// <xsd:element name="right" type="CT_PageBorder" minOccurs="0"/> *
// </xsd:sequence> * Reference: http://officeopenxml.com/WPsectionBorders.php
// <xsd:attribute name="zOrder" type="ST_PageBorderZOrder" use="optional" default="front"/> *
// <xsd:attribute name="display" type="ST_PageBorderDisplay" use="optional"/> * ## XSD Schema
// <xsd:attribute name="offsetFrom" type="ST_PageBorderOffset" use="optional" default="text"/> * ```xml
// </xsd:complexType> * <xsd:complexType name="CT_PageBorders">
* <xsd:sequence>
* <xsd:element name="top" type="CT_TopPageBorder" minOccurs="0"/>
* <xsd:element name="left" type="CT_PageBorder" minOccurs="0"/>
* <xsd:element name="bottom" type="CT_BottomPageBorder" minOccurs="0"/>
* <xsd:element name="right" type="CT_PageBorder" minOccurs="0"/>
* </xsd:sequence>
* <xsd:attribute name="zOrder" type="ST_PageBorderZOrder" use="optional" default="front"/>
* <xsd:attribute name="display" type="ST_PageBorderDisplay" use="optional"/>
* <xsd:attribute name="offsetFrom" type="ST_PageBorderOffset" use="optional" default="text"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* // Add page borders to all pages
* new PageBorders({
* pageBorders: {
* display: PageBorderDisplay.ALL_PAGES,
* offsetFrom: PageBorderOffsetFrom.PAGE,
* zOrder: PageBorderZOrder.FRONT
* },
* pageBorderTop: { style: BorderStyle.SINGLE, size: 24, color: "000000" },
* pageBorderBottom: { style: BorderStyle.SINGLE, size: 24, color: "000000" }
* });
* ```
*/
export class PageBorders extends IgnoreIfEmptyXmlComponent { export class PageBorders extends IgnoreIfEmptyXmlComponent {
public constructor(options?: IPageBordersOptions) { public constructor(options?: IPageBordersOptions) {
super("w:pgBorders"); super("w:pgBorders");
@@ -1,25 +1,72 @@
/**
* Page margin module for WordprocessingML section properties.
*
* Defines page margins for document sections.
*
* Reference: http://officeopenxml.com/WPsectionPr.php
*
* @module
*/
import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { NextAttributeComponent, XmlComponent } from "@file/xml-components";
import { PositiveUniversalMeasure, UniversalMeasure, signedTwipsMeasureValue, twipsMeasureValue } from "@util/values"; import { PositiveUniversalMeasure, UniversalMeasure, signedTwipsMeasureValue, twipsMeasureValue } from "@util/values";
// <xsd:complexType name="CT_PageMar"> /**
// <xsd:attribute name="top" type="ST_SignedTwipsMeasure" use="required"/> * Options for configuring page margins.
// <xsd:attribute name="right" type="s:ST_TwipsMeasure" use="required"/> *
// <xsd:attribute name="bottom" type="ST_SignedTwipsMeasure" use="required"/> * All measurements are in twips (1/20th of a point) or universal measure.
// <xsd:attribute name="left" type="s:ST_TwipsMeasure" use="required"/> *
// <xsd:attribute name="header" type="s:ST_TwipsMeasure" use="required"/> * @property top - Top margin
// <xsd:attribute name="footer" type="s:ST_TwipsMeasure" use="required"/> * @property right - Right margin
// <xsd:attribute name="gutter" type="s:ST_TwipsMeasure" use="required"/> * @property bottom - Bottom margin
// </xsd:complexType> * @property left - Left margin
* @property header - Header margin (distance from top of page to header)
* @property footer - Footer margin (distance from bottom of page to footer)
* @property gutter - Gutter margin for binding
*/
export type IPageMarginAttributes = { export type IPageMarginAttributes = {
/** Top margin in twips or universal measure */
readonly top?: number | UniversalMeasure; readonly top?: number | UniversalMeasure;
/** Right margin in twips or universal measure */
readonly right?: number | PositiveUniversalMeasure; readonly right?: number | PositiveUniversalMeasure;
/** Bottom margin in twips or universal measure */
readonly bottom?: number | UniversalMeasure; readonly bottom?: number | UniversalMeasure;
/** Left margin in twips or universal measure */
readonly left?: number | PositiveUniversalMeasure; readonly left?: number | PositiveUniversalMeasure;
/** Header margin (distance from top of page to header) in twips or universal measure */
readonly header?: number | PositiveUniversalMeasure; readonly header?: number | PositiveUniversalMeasure;
/** Footer margin (distance from bottom of page to footer) in twips or universal measure */
readonly footer?: number | PositiveUniversalMeasure; readonly footer?: number | PositiveUniversalMeasure;
/** Gutter margin for binding in twips or universal measure */
readonly gutter?: number | PositiveUniversalMeasure; readonly gutter?: number | PositiveUniversalMeasure;
}; };
/**
* Represents page margins (pgMar) for a document section.
*
* This element specifies the page margins for all pages in a section,
* including top, bottom, left, right, header, footer, and gutter margins.
*
* Reference: http://officeopenxml.com/WPsectionPr.php
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_PageMar">
* <xsd:attribute name="top" type="ST_SignedTwipsMeasure" use="required"/>
* <xsd:attribute name="right" type="s:ST_TwipsMeasure" use="required"/>
* <xsd:attribute name="bottom" type="ST_SignedTwipsMeasure" use="required"/>
* <xsd:attribute name="left" type="s:ST_TwipsMeasure" use="required"/>
* <xsd:attribute name="header" type="s:ST_TwipsMeasure" use="required"/>
* <xsd:attribute name="footer" type="s:ST_TwipsMeasure" use="required"/>
* <xsd:attribute name="gutter" type="s:ST_TwipsMeasure" use="required"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* // Create page margins with 1 inch margins (1440 twips = 1 inch)
* new PageMargin(1440, 1440, 1440, 1440, 720, 720, 0);
* ```
*/
export class PageMargin extends XmlComponent { export class PageMargin extends XmlComponent {
public constructor( public constructor(
top: number | UniversalMeasure, top: number | UniversalMeasure,
@@ -1,39 +1,61 @@
// http://officeopenxml.com/WPSectionPgNumType.php /**
* Page number module for WordprocessingML section properties.
*
* Defines page numbering format and starting value for document sections.
*
* Reference: http://officeopenxml.com/WPSectionPgNumType.php
*
* @module
*/
import { NumberFormat } from "@file/shared/number-format"; import { NumberFormat } from "@file/shared/number-format";
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { decimalNumber } from "@util/values"; import { decimalNumber } from "@util/values";
// <xsd:simpleType name="ST_ChapterSep"> /**
// <xsd:restriction base="xsd:string"> * Specifies the separator character between chapter number and page number.
// <xsd:enumeration value="hyphen"/> *
// <xsd:enumeration value="period"/> * ## XSD Schema
// <xsd:enumeration value="colon"/> * ```xml
// <xsd:enumeration value="emDash"/> * <xsd:simpleType name="ST_ChapterSep">
// <xsd:enumeration value="enDash"/> * <xsd:restriction base="xsd:string">
// </xsd:restriction> * <xsd:enumeration value="hyphen"/>
// </xsd:simpleType> * <xsd:enumeration value="period"/>
* <xsd:enumeration value="colon"/>
* <xsd:enumeration value="emDash"/>
* <xsd:enumeration value="enDash"/>
* </xsd:restriction>
* </xsd:simpleType>
* ```
*/
export const PageNumberSeparator = { export const PageNumberSeparator = {
/** Hyphen separator (-) */
HYPHEN: "hyphen", HYPHEN: "hyphen",
/** Period separator (.) */
PERIOD: "period", PERIOD: "period",
/** Colon separator (:) */
COLON: "colon", COLON: "colon",
/** Em dash separator (—) */
EM_DASH: "emDash", EM_DASH: "emDash",
/** En dash separator (–) */
EN_DASH: "endash", EN_DASH: "endash",
} as const; } as const;
/**
* Options for configuring page numbering.
*
* @property start - Starting page number for the section
* @property formatType - Number format (decimal, roman, letter, etc.)
* @property separator - Separator between chapter and page number
*/
export type IPageNumberTypeAttributes = { export type IPageNumberTypeAttributes = {
/** Starting page number for the section */
readonly start?: number; readonly start?: number;
/** Number format (decimal, roman, letter, etc., default: decimal) */
readonly formatType?: (typeof NumberFormat)[keyof typeof NumberFormat]; readonly formatType?: (typeof NumberFormat)[keyof typeof NumberFormat];
/** Separator between chapter and page number (default: hyphen) */
readonly separator?: (typeof PageNumberSeparator)[keyof typeof PageNumberSeparator]; readonly separator?: (typeof PageNumberSeparator)[keyof typeof PageNumberSeparator];
}; };
// <xsd:complexType name="CT_PageNumber">
// <xsd:attribute name="fmt" type="ST_NumberFormat" use="optional" default="decimal"/>
// <xsd:attribute name="start" type="ST_DecimalNumber" use="optional"/>
// <xsd:attribute name="chapStyle" type="ST_DecimalNumber" use="optional"/>
// <xsd:attribute name="chapSep" type="ST_ChapterSep" use="optional" default="hyphen"/>
// </xsd:complexType>
export class PageNumberTypeAttributes extends XmlAttributeComponent<IPageNumberTypeAttributes> { export class PageNumberTypeAttributes extends XmlAttributeComponent<IPageNumberTypeAttributes> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
start: "w:start", start: "w:start",
@@ -42,6 +64,33 @@ export class PageNumberTypeAttributes extends XmlAttributeComponent<IPageNumberT
}; };
} }
/**
* Represents page numbering settings (pgNumType) for a document section.
*
* This element specifies the page numbering format and starting value
* for all pages in a section.
*
* Reference: http://officeopenxml.com/WPSectionPgNumType.php
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_PageNumber">
* <xsd:attribute name="fmt" type="ST_NumberFormat" use="optional" default="decimal"/>
* <xsd:attribute name="start" type="ST_DecimalNumber" use="optional"/>
* <xsd:attribute name="chapStyle" type="ST_DecimalNumber" use="optional"/>
* <xsd:attribute name="chapSep" type="ST_ChapterSep" use="optional" default="hyphen"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* // Start page numbering at 5 with lowercase roman numerals
* new PageNumberType({
* start: 5,
* formatType: NumberFormat.LOWER_ROMAN
* });
* ```
*/
export class PageNumberType extends XmlComponent { export class PageNumberType extends XmlComponent {
public constructor({ start, formatType, separator }: IPageNumberTypeAttributes) { public constructor({ start, formatType, separator }: IPageNumberTypeAttributes) {
super("w:pgNumType"); super("w:pgNumType");
@@ -1,7 +1,24 @@
/**
* Page text direction module for WordprocessingML section properties.
*
* Defines text flow direction for pages in a section.
*
* Reference: http://officeopenxml.com/WPsectionPr.php
*
* @module
*/
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
/**
* Specifies the text flow direction for pages in a section.
*
* This controls whether text flows horizontally (left-to-right) or
* vertically (top-to-bottom), commonly used for East Asian languages.
*/
export const PageTextDirectionType = { export const PageTextDirectionType = {
/** Left-to-right, top-to-bottom (standard Western text flow) */
LEFT_TO_RIGHT_TOP_TO_BOTTOM: "lrTb", LEFT_TO_RIGHT_TOP_TO_BOTTOM: "lrTb",
/** Top-to-bottom, right-to-left (vertical East Asian text flow) */
TOP_TO_BOTTOM_RIGHT_TO_LEFT: "tbRl", TOP_TO_BOTTOM_RIGHT_TO_LEFT: "tbRl",
} as const; } as const;
@@ -11,6 +28,23 @@ class PageTextDirectionAttributes extends XmlAttributeComponent<{
protected readonly xmlKeys = { val: "w:val" }; protected readonly xmlKeys = { val: "w:val" };
} }
/**
* Represents text direction (textDirection) for pages in a section.
*
* This element specifies the direction and orientation of text flow
* for all pages in a section.
*
* Reference: http://officeopenxml.com/WPsectionPr.php
*
* @example
* ```typescript
* // Horizontal text flow (left-to-right, top-to-bottom)
* new PageTextDirection(PageTextDirectionType.LEFT_TO_RIGHT_TOP_TO_BOTTOM);
*
* // Vertical text flow (top-to-bottom, right-to-left)
* new PageTextDirection(PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT);
* ```
*/
export class PageTextDirection extends XmlComponent { export class PageTextDirection extends XmlComponent {
public constructor(value: (typeof PageTextDirectionType)[keyof typeof PageTextDirectionType]) { public constructor(value: (typeof PageTextDirectionType)[keyof typeof PageTextDirectionType]) {
super("w:textDirection"); super("w:textDirection");
@@ -1,27 +1,45 @@
// http://officeopenxml.com/WPsection.php /**
* Section type module for WordprocessingML section properties.
*
* Defines how a section begins relative to the previous section.
*
* Reference: http://officeopenxml.com/WPsection.php
*
* @module
*/
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
// <xsd:simpleType name="ST_SectionMark"> /**
// <xsd:restriction base="xsd:string"> * Specifies the type of section break.
// <xsd:enumeration value="nextPage"/> *
// <xsd:enumeration value="nextColumn"/> * This determines where the section begins relative to the previous section.
// <xsd:enumeration value="continuous"/> *
// <xsd:enumeration value="evenPage"/> * ## XSD Schema
// <xsd:enumeration value="oddPage"/> * ```xml
// </xsd:restriction> * <xsd:simpleType name="ST_SectionMark">
// </xsd:simpleType> * <xsd:restriction base="xsd:string">
* <xsd:enumeration value="nextPage"/>
* <xsd:enumeration value="nextColumn"/>
* <xsd:enumeration value="continuous"/>
* <xsd:enumeration value="evenPage"/>
* <xsd:enumeration value="oddPage"/>
* </xsd:restriction>
* </xsd:simpleType>
* ```
*/
export const SectionType = { export const SectionType = {
/** Section begins on the next page */
NEXT_PAGE: "nextPage", NEXT_PAGE: "nextPage",
/** Section begins on the next column */
NEXT_COLUMN: "nextColumn", NEXT_COLUMN: "nextColumn",
/** Section begins immediately following the previous section */
CONTINUOUS: "continuous", CONTINUOUS: "continuous",
/** Section begins on the next even-numbered page */
EVEN_PAGE: "evenPage", EVEN_PAGE: "evenPage",
/** Section begins on the next odd-numbered page */
ODD_PAGE: "oddPage", ODD_PAGE: "oddPage",
} as const; } as const;
// <xsd:complexType name="CT_SectType">
// <xsd:attribute name="val" type="ST_SectionMark"/>
// </xsd:complexType>
export class SectionTypeAttributes extends XmlAttributeComponent<{ export class SectionTypeAttributes extends XmlAttributeComponent<{
readonly val: (typeof SectionType)[keyof typeof SectionType]; readonly val: (typeof SectionType)[keyof typeof SectionType];
}> { }> {
@@ -30,6 +48,30 @@ export class SectionTypeAttributes extends XmlAttributeComponent<{
}; };
} }
/**
* Represents section type (type) for a document section.
*
* This element specifies the type of section break, which determines
* where the new section begins relative to the previous section.
*
* Reference: http://officeopenxml.com/WPsection.php
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_SectType">
* <xsd:attribute name="val" type="ST_SectionMark"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* // Create a continuous section (no page break)
* new Type(SectionType.CONTINUOUS);
*
* // Create a section that starts on next odd page
* new Type(SectionType.ODD_PAGE);
* ```
*/
export class Type extends XmlComponent { export class Type extends XmlComponent {
public constructor(value: (typeof SectionType)[keyof typeof SectionType]) { public constructor(value: (typeof SectionType)[keyof typeof SectionType]) {
super("w:type"); super("w:type");
@@ -27,55 +27,116 @@ import { SectionType, Type } from "./properties/section-type";
/** /**
* Header/footer group for specifying different headers/footers * Header/footer group for specifying different headers/footers
* for default, first, and even pages. * for default, first, and even pages.
*
* @property default - Header/footer for default pages (odd pages when even headers are used)
* @property first - Header/footer for first page (requires titlePage setting)
* @property even - Header/footer for even pages (requires evenAndOddHeaders setting)
*/ */
export type IHeaderFooterGroup<T> = { export type IHeaderFooterGroup<T> = {
/** Header/footer for default pages (odd pages when even headers are used) */
readonly default?: T; readonly default?: T;
/** Header/footer for first page (requires titlePage setting) */
readonly first?: T; readonly first?: T;
/** Header/footer for even pages (requires evenAndOddHeaders setting) */
readonly even?: T; readonly even?: T;
}; };
/** /**
* Options for configuring section properties. * Options for configuring section properties.
* *
* This type defines all possible configuration options for a document section,
* including page layout, margins, headers/footers, and numbering.
*
* @property page - Page-level settings (size, margins, borders, numbering, text direction)
* @property grid - Document grid settings for East Asian typography
* @property headerWrapperGroup - Header definitions for default, first, and even pages
* @property footerWrapperGroup - Footer definitions for default, first, and even pages
* @property lineNumbers - Line numbering settings
* @property titlePage - Whether first page has different header/footer
* @property verticalAlign - Vertical alignment of text on page
* @property column - Column layout settings
* @property type - Section break type (next page, continuous, etc.)
*
* @see {@link SectionProperties} * @see {@link SectionProperties}
*/ */
export type ISectionPropertiesOptions = { export type ISectionPropertiesOptions = {
/** Page-level settings including size, margins, borders, and text direction */
readonly page?: { readonly page?: {
/** Page size and orientation */
readonly size?: Partial<IPageSizeAttributes>; readonly size?: Partial<IPageSizeAttributes>;
/** Page margins (top, bottom, left, right, header, footer, gutter) */
readonly margin?: IPageMarginAttributes; readonly margin?: IPageMarginAttributes;
/** Page numbering format and starting value */
readonly pageNumbers?: IPageNumberTypeAttributes; readonly pageNumbers?: IPageNumberTypeAttributes;
/** Page border settings */
readonly borders?: IPageBordersOptions; readonly borders?: IPageBordersOptions;
/** Text flow direction (horizontal or vertical) */
readonly textDirection?: (typeof PageTextDirectionType)[keyof typeof PageTextDirectionType]; readonly textDirection?: (typeof PageTextDirectionType)[keyof typeof PageTextDirectionType];
}; };
/** Document grid settings for precise East Asian character layout */
readonly grid?: Partial<IDocGridAttributesProperties>; readonly grid?: Partial<IDocGridAttributesProperties>;
/** Header definitions for default, first, and even pages */
readonly headerWrapperGroup?: IHeaderFooterGroup<HeaderWrapper>; readonly headerWrapperGroup?: IHeaderFooterGroup<HeaderWrapper>;
/** Footer definitions for default, first, and even pages */
readonly footerWrapperGroup?: IHeaderFooterGroup<FooterWrapper>; readonly footerWrapperGroup?: IHeaderFooterGroup<FooterWrapper>;
/** Line numbering settings for the section */
readonly lineNumbers?: ILineNumberAttributes; readonly lineNumbers?: ILineNumberAttributes;
/** Whether first page has different header/footer */
readonly titlePage?: boolean; readonly titlePage?: boolean;
/** Vertical alignment of text on page (top, center, bottom, justified) */
readonly verticalAlign?: SectionVerticalAlign; readonly verticalAlign?: SectionVerticalAlign;
/** Column layout settings (count, spacing, equal width) */
readonly column?: IColumnsAttributes; readonly column?: IColumnsAttributes;
/** Section break type (next page, continuous, even page, odd page) */
readonly type?: (typeof SectionType)[keyof typeof SectionType]; readonly type?: (typeof SectionType)[keyof typeof SectionType];
}; };
/** /**
* Default margin values for sections (in twips). * Default margin values for sections (in twips).
*
* Standard margins are 1 inch (1440 twips) on all sides.
* Header/footer margins are 0.5 inches (708 twips) from page edge.
*
* @property TOP - Top margin: 1440 twips (1 inch)
* @property RIGHT - Right margin: 1440 twips (1 inch)
* @property BOTTOM - Bottom margin: 1440 twips (1 inch)
* @property LEFT - Left margin: 1440 twips (1 inch)
* @property HEADER - Header margin: 708 twips (0.5 inches)
* @property FOOTER - Footer margin: 708 twips (0.5 inches)
* @property GUTTER - Gutter margin: 0 twips
*/ */
export const sectionMarginDefaults = { export const sectionMarginDefaults = {
/** Top margin: 1440 twips (1 inch) */
TOP: 1440, TOP: 1440,
/** Right margin: 1440 twips (1 inch) */
RIGHT: 1440, RIGHT: 1440,
/** Bottom margin: 1440 twips (1 inch) */
BOTTOM: 1440, BOTTOM: 1440,
/** Left margin: 1440 twips (1 inch) */
LEFT: 1440, LEFT: 1440,
/** Header margin from top: 708 twips (0.5 inches) */
HEADER: 708, HEADER: 708,
/** Footer margin from bottom: 708 twips (0.5 inches) */
FOOTER: 708, FOOTER: 708,
/** Gutter margin for binding: 0 twips */
GUTTER: 0, GUTTER: 0,
}; };
/** /**
* Default page size values (in twips, A4 portrait). * Default page size values (in twips, A4 portrait).
*
* A4 size is 210mm x 297mm (8.27" x 11.69").
*
* @property WIDTH - Page width: 11906 twips (8.27 inches, 210mm)
* @property HEIGHT - Page height: 16838 twips (11.69 inches, 297mm)
* @property ORIENTATION - Page orientation: portrait
*/ */
export const sectionPageSizeDefaults = { export const sectionPageSizeDefaults = {
/** Page width: 11906 twips (8.27 inches, 210mm) */
WIDTH: 11906, WIDTH: 11906,
/** Page height: 16838 twips (11.69 inches, 297mm) */
HEIGHT: 16838, HEIGHT: 16838,
/** Page orientation: portrait */
ORIENTATION: PageOrientation.PORTRAIT, ORIENTATION: PageOrientation.PORTRAIT,
}; };
@@ -84,6 +145,7 @@ export const sectionPageSizeDefaults = {
* *
* Section properties define the page layout for a section of the document, * Section properties define the page layout for a section of the document,
* including page size, margins, headers/footers, columns, and page numbering. * including page size, margins, headers/footers, columns, and page numbering.
* A document can contain multiple sections with different properties.
* *
* Reference: http://officeopenxml.com/WPsection.php * Reference: http://officeopenxml.com/WPsection.php
* *
@@ -98,6 +160,34 @@ export const sectionPageSizeDefaults = {
* <xsd:attributeGroup ref="AG_SectPrAttributes"/> * <xsd:attributeGroup ref="AG_SectPrAttributes"/>
* </xsd:complexType> * </xsd:complexType>
* ``` * ```
*
* @example
* ```typescript
* // Create section with custom page size and margins
* new SectionProperties({
* page: {
* size: {
* width: 12240,
* height: 15840,
* orientation: PageOrientation.PORTRAIT
* },
* margin: {
* top: 1440,
* right: 1440,
* bottom: 1440,
* left: 1440
* },
* pageNumbers: {
* start: 1,
* formatType: NumberFormat.DECIMAL
* }
* },
* column: {
* count: 2,
* space: 720
* }
* });
* ```
*/ */
export class SectionProperties extends XmlComponent { export class SectionProperties extends XmlComponent {
public constructor({ public constructor({
+39
View File
@@ -1,5 +1,21 @@
/**
* Document attributes module for WordprocessingML documents.
*
* This module defines the XML namespace declarations used in OOXML documents.
* These namespaces are required for proper document parsing and generation.
*
* Reference: http://officeopenxml.com/anatomyofOOXML.php
*
* @module
*/
import { AttributeMap, XmlAttributeComponent } from "@file/xml-components"; import { AttributeMap, XmlAttributeComponent } from "@file/xml-components";
/**
* XML namespace URIs used in WordprocessingML documents.
*
* These namespaces define the various XML schemas that can be referenced
* in a document, including WordprocessingML, DrawingML, VML, and others.
*/
/* cSpell:disable */ /* cSpell:disable */
export const DocumentAttributeNamespaces = { export const DocumentAttributeNamespaces = {
wpc: "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas", wpc: "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",
@@ -42,12 +58,35 @@ export const DocumentAttributeNamespaces = {
}; };
/* cSpell:enable */ /* cSpell:enable */
/**
* Type representing valid namespace keys.
*/
export type DocumentAttributeNamespace = keyof typeof DocumentAttributeNamespaces; export type DocumentAttributeNamespace = keyof typeof DocumentAttributeNamespaces;
/**
* Properties for document namespace attributes.
*
* Allows specifying which namespaces to include and optional Ignorable attribute
* for compatibility with older processors.
*/
export type IDocumentAttributesProperties = Partial<Record<DocumentAttributeNamespace, string>> & { export type IDocumentAttributesProperties = Partial<Record<DocumentAttributeNamespace, string>> & {
readonly Ignorable?: string; readonly Ignorable?: string;
}; };
/**
* Represents XML namespace attributes for a WordprocessingML document.
*
* This class generates the xmlns declarations required at the root element
* of document.xml and other document parts.
*
* @example
* ```typescript
* new DocumentAttributes(['w', 'r', 'wp'], 'w14 w15');
* // Generates: xmlns:w="..." xmlns:r="..." xmlns:wp="..." mc:Ignorable="w14 w15"
* ```
*
* @internal
*/
export class DocumentAttributes extends XmlAttributeComponent<IDocumentAttributesProperties> { export class DocumentAttributes extends XmlAttributeComponent<IDocumentAttributesProperties> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
Ignorable: "mc:Ignorable", Ignorable: "mc:Ignorable",
@@ -1,30 +1,46 @@
// http://officeopenxml.com/WPdocument.php /**
// http://www.datypic.com/sc/ooxml/e-w_background-1.html * Document background module for WordprocessingML documents.
*
* This module provides functionality for setting document background colors
* and theme-based backgrounds.
*
* Reference: http://officeopenxml.com/WPdocument.php
*
* @module
*/
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components"; import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { hexColorValue, uCharHexNumber } from "@util/values"; import { hexColorValue, uCharHexNumber } from "@util/values";
// <xsd:simpleType name="ST_ThemeColor"> /**
// <xsd:restriction base="xsd:string"> * Attributes for the document background element.
// <xsd:enumeration value="dark1"/> *
// <xsd:enumeration value="light1"/> * ## XSD Schema (ST_ThemeColor)
// <xsd:enumeration value="dark2"/> * ```xml
// <xsd:enumeration value="light2"/> * <xsd:simpleType name="ST_ThemeColor">
// <xsd:enumeration value="accent1"/> * <xsd:restriction base="xsd:string">
// <xsd:enumeration value="accent2"/> * <xsd:enumeration value="dark1"/>
// <xsd:enumeration value="accent3"/> * <xsd:enumeration value="light1"/>
// <xsd:enumeration value="accent4"/> * <xsd:enumeration value="dark2"/>
// <xsd:enumeration value="accent5"/> * <xsd:enumeration value="light2"/>
// <xsd:enumeration value="accent6"/> * <xsd:enumeration value="accent1"/>
// <xsd:enumeration value="hyperlink"/> * <xsd:enumeration value="accent2"/>
// <xsd:enumeration value="followedHyperlink"/> * <xsd:enumeration value="accent3"/>
// <xsd:enumeration value="none"/> * <xsd:enumeration value="accent4"/>
// <xsd:enumeration value="background1"/> * <xsd:enumeration value="accent5"/>
// <xsd:enumeration value="text1"/> * <xsd:enumeration value="accent6"/>
// <xsd:enumeration value="background2"/> * <xsd:enumeration value="hyperlink"/>
// <xsd:enumeration value="text2"/> * <xsd:enumeration value="followedHyperlink"/>
// </xsd:restriction> * <xsd:enumeration value="none"/>
// </xsd:simpleType> * <xsd:enumeration value="background1"/>
* <xsd:enumeration value="text1"/>
* <xsd:enumeration value="background2"/>
* <xsd:enumeration value="text2"/>
* </xsd:restriction>
* </xsd:simpleType>
* ```
*
* @internal
*/
export class DocumentBackgroundAttributes extends XmlAttributeComponent<{ export class DocumentBackgroundAttributes extends XmlAttributeComponent<{
readonly color?: string; readonly color?: string;
readonly themeColor?: string; readonly themeColor?: string;
@@ -39,29 +55,53 @@ export class DocumentBackgroundAttributes extends XmlAttributeComponent<{
}; };
} }
/**
* Options for creating a document background.
*
* @see {@link DocumentBackground}
*/
export type IDocumentBackgroundOptions = { export type IDocumentBackgroundOptions = {
/** Background color in hex format (e.g., "FF0000" for red) */
readonly color?: string; readonly color?: string;
/** Theme color name (e.g., "accent1", "dark1") */
readonly themeColor?: string; readonly themeColor?: string;
/** Theme shade value (darkens the theme color) */
readonly themeShade?: string; readonly themeShade?: string;
/** Theme tint value (lightens the theme color) */
readonly themeTint?: string; readonly themeTint?: string;
}; };
// <xsd:complexType name="CT_Background"> /**
// <xsd:sequence> * Represents a document background in a WordprocessingML document.
// <xsd:sequence maxOccurs="unbounded"> *
// <xsd:any processContents="lax" namespace="urn:schemas-microsoft-com:vml" minOccurs="0" * The background element specifies the background color or theme color
// maxOccurs="unbounded"/> * for the document.
// <xsd:any processContents="lax" namespace="urn:schemas-microsoft-com:office:office" *
// minOccurs="0" maxOccurs="unbounded"/> * Reference: http://officeopenxml.com/WPdocument.php
// </xsd:sequence> *
// <xsd:element name="drawing" type="CT_Drawing" minOccurs="0"/> * ## XSD Schema
// </xsd:sequence> * ```xml
// <xsd:attribute name="color" type="ST_HexColor" use="optional" default="auto"/> * <xsd:complexType name="CT_Background">
// <xsd:attribute name="themeColor" type="ST_ThemeColor" use="optional"/> * <xsd:sequence>
// <xsd:attribute name="themeTint" type="ST_UcharHexNumber" use="optional"/> * <xsd:sequence maxOccurs="unbounded">
// <xsd:attribute name="themeShade" type="ST_UcharHexNumber" use="optional"/> * <xsd:any processContents="lax" namespace="urn:schemas-microsoft-com:vml" minOccurs="0" maxOccurs="unbounded"/>
// </xsd:complexType> * <xsd:any processContents="lax" namespace="urn:schemas-microsoft-com:office:office" minOccurs="0" maxOccurs="unbounded"/>
* </xsd:sequence>
* <xsd:element name="drawing" type="CT_Drawing" minOccurs="0"/>
* </xsd:sequence>
* <xsd:attribute name="color" type="ST_HexColor" use="optional" default="auto"/>
* <xsd:attribute name="themeColor" type="ST_ThemeColor" use="optional"/>
* <xsd:attribute name="themeTint" type="ST_UcharHexNumber" use="optional"/>
* <xsd:attribute name="themeShade" type="ST_UcharHexNumber" use="optional"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* new DocumentBackground({ color: "FFFF00" }); // Yellow background
* new DocumentBackground({ themeColor: "accent1" }); // Theme accent color
* ```
*/
export class DocumentBackground extends XmlComponent { export class DocumentBackground extends XmlComponent {
public constructor(options: IDocumentBackgroundOptions) { public constructor(options: IDocumentBackgroundOptions) {
super("w:background"); super("w:background");
@@ -1 +1,6 @@
/**
* Document background module exports.
*
* @module
*/
export * from "./document-background"; export * from "./document-background";
+30
View File
@@ -17,6 +17,8 @@ import { DocumentBackground, IDocumentBackgroundOptions } from "./document-backg
/** /**
* Options for creating a Document element. * Options for creating a Document element.
* *
* @property background - Optional background settings for the document
*
* @see {@link Document} * @see {@link Document}
*/ */
export type IDocumentOptions = { export type IDocumentOptions = {
@@ -54,6 +56,23 @@ export type IDocumentOptions = {
* </xsd:sequence> * </xsd:sequence>
* </xsd:complexType> * </xsd:complexType>
* ``` * ```
*
* @example
* ```typescript
* // Create a document with default options
* const doc = new Document({});
*
* // Create a document with background
* const doc = new Document({
* background: {
* color: "FF0000",
* },
* });
*
* // Add content to the document
* doc.add(new Paragraph("Hello World"));
* doc.add(new Table({ rows: [...] }));
* ```
*/ */
export class Document extends XmlComponent { export class Document extends XmlComponent {
private readonly body: Body; private readonly body: Body;
@@ -106,11 +125,22 @@ export class Document extends XmlComponent {
this.root.push(this.body); this.root.push(this.body);
} }
/**
* Adds a block-level element to the document body.
*
* @param item - The element to add (paragraph, table, table of contents, or hyperlink)
* @returns The Document instance for method chaining
*/
public add(item: Paragraph | Table | TableOfContents | ConcreteHyperlink): Document { public add(item: Paragraph | Table | TableOfContents | ConcreteHyperlink): Document {
this.body.push(item); this.body.push(item);
return this; return this;
} }
/**
* Gets the document body element.
*
* @returns The Body instance containing all document content
*/
public get Body(): Body { public get Body(): Body {
return this.body; return this.body;
} }
+5
View File
@@ -1,3 +1,8 @@
/**
* Document module exports.
*
* @module
*/
export * from "./document"; export * from "./document";
export * from "./document-attributes"; export * from "./document-attributes";
export * from "./body"; export * from "./body";
@@ -1,16 +1,42 @@
/**
* Anchor attributes module for DrawingML floating elements.
*
* This module defines the attributes for anchored/floating drawings,
* controlling positioning, z-order, and wrapping behavior.
*
* @module
*/
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
import { IDistance } from "../drawing"; import { IDistance } from "../drawing";
/**
* Attributes for an anchored drawing element.
*
* These attributes control the positioning and behavior of floating drawings.
*/
export type IAnchorAttributes = { export type IAnchorAttributes = {
/** Whether the drawing can overlap other content ("0" = false, "1" = true) */
readonly allowOverlap?: "0" | "1"; readonly allowOverlap?: "0" | "1";
/** Whether the drawing is behind document text ("0" = false, "1" = true) */
readonly behindDoc?: "0" | "1"; readonly behindDoc?: "0" | "1";
/** Whether the drawing is contained within table cells ("0" = false, "1" = true) */
readonly layoutInCell?: "0" | "1"; readonly layoutInCell?: "0" | "1";
/** Whether the anchor position is locked ("0" = false, "1" = true) */
readonly locked?: "0" | "1"; readonly locked?: "0" | "1";
/** Z-order positioning (higher values appear in front) */
readonly relativeHeight?: number; readonly relativeHeight?: number;
/** Whether to use simple positioning ("0" = false, "1" = true) */
readonly simplePos?: "0" | "1"; readonly simplePos?: "0" | "1";
} & IDistance; } & IDistance;
/**
* XML attributes component for anchored drawings.
*
* Maps the IAnchorAttributes to XML attribute names for the wp:anchor element.
*
* @internal
*/
export class AnchorAttributes extends XmlAttributeComponent<IAnchorAttributes> { export class AnchorAttributes extends XmlAttributeComponent<IAnchorAttributes> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
distT: "distT", distT: "distT",
+5
View File
@@ -1,2 +1,7 @@
/**
* Drawing anchor module exports.
*
* @module
*/
export * from "./anchor"; export * from "./anchor";
export * from "./anchor-attributes"; export * from "./anchor-attributes";
@@ -1,3 +1,11 @@
/**
* Child elements for document properties.
*
* This module provides hyperlink elements that can be attached to
* drawing elements for interactive behavior.
*
* @module
*/
// <sequence> // <sequence>
// <element name="hlinkClick" type="CT_Hyperlink" minOccurs="0" maxOccurs="1" /> // <element name="hlinkClick" type="CT_Hyperlink" minOccurs="0" maxOccurs="1" />
// <element name="hlinkHover" type="CT_Hyperlink" minOccurs="0" maxOccurs="1" /> // <element name="hlinkHover" type="CT_Hyperlink" minOccurs="0" maxOccurs="1" />
@@ -18,6 +26,28 @@ import { BuilderElement, XmlComponent } from "@file/xml-components";
// TODO: Implement the rest of the attributes // TODO: Implement the rest of the attributes
/**
* Creates a click hyperlink element for a drawing.
*
* This element defines what happens when a user clicks on a drawing element.
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_Hyperlink">
* <xsd:group ref="EG_PContent" minOccurs="0" maxOccurs="unbounded"/>
* <xsd:attribute name="tgtFrame" type="s:ST_String"/>
* <xsd:attribute name="tooltip" type="s:ST_String"/>
* <xsd:attribute name="docLocation" type="s:ST_String"/>
* <xsd:attribute name="history" type="s:ST_OnOff"/>
* <xsd:attribute name="anchor" type="s:ST_String"/>
* <xsd:attribute ref="r:id"/>
* </xsd:complexType>
* ```
*
* @param linkId - The relationship ID for the hyperlink target
* @param hasXmlNs - Whether to include the XML namespace declaration
* @returns An XML component representing the click hyperlink
*/
export const createHyperlinkClick = (linkId: string, hasXmlNs: boolean): XmlComponent => export const createHyperlinkClick = (linkId: string, hasXmlNs: boolean): XmlComponent =>
new BuilderElement({ new BuilderElement({
name: "a:hlinkClick", name: "a:hlinkClick",
@@ -37,6 +67,28 @@ export const createHyperlinkClick = (linkId: string, hasXmlNs: boolean): XmlComp
}, },
}); });
/**
* Creates a hover hyperlink element for a drawing.
*
* This element defines what happens when a user hovers over a drawing element.
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_Hyperlink">
* <xsd:group ref="EG_PContent" minOccurs="0" maxOccurs="unbounded"/>
* <xsd:attribute name="tgtFrame" type="s:ST_String"/>
* <xsd:attribute name="tooltip" type="s:ST_String"/>
* <xsd:attribute name="docLocation" type="s:ST_String"/>
* <xsd:attribute name="history" type="s:ST_OnOff"/>
* <xsd:attribute name="anchor" type="s:ST_String"/>
* <xsd:attribute ref="r:id"/>
* </xsd:complexType>
* ```
*
* @param linkId - The relationship ID for the hyperlink target
* @param hasXmlNs - Whether to include the XML namespace declaration
* @returns An XML component representing the hover hyperlink
*/
export const createHyperlinkHover = (linkId: string, hasXmlNs: boolean): XmlComponent => export const createHyperlinkHover = (linkId: string, hasXmlNs: boolean): XmlComponent =>
new BuilderElement({ new BuilderElement({
name: "a:hlinkHover", name: "a:hlinkHover",
@@ -1,5 +1,18 @@
/**
* Effect extent for DrawingML objects.
*
* This module provides support for defining additional extent to compensate
* for drawing effects applied to objects.
*
* Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_effectExtent_topic_ID0E5O3OB.html
*
* @module
*/
import { BuilderElement, XmlComponent } from "@file/xml-components"; import { BuilderElement, XmlComponent } from "@file/xml-components";
/**
* Attributes for effect extent.
*/
export type EffectExtentAttributes = { export type EffectExtentAttributes = {
/** /**
* ## Additional Extent on Top Edge * ## Additional Extent on Top Edge
@@ -28,14 +41,19 @@ export type EffectExtentAttributes = {
}; };
/** /**
* This element specifies the additional extent which shall be added to each edge of the image (top, bottom, left, right) in order to compensate for any drawing effects applied to the DrawingML object. * Creates an effect extent element.
* *
* The `<extent>` element (§5.5.2.7) specifies the size of the actual DrawingML object; however, an object may have effects applied which change its overall size * This element specifies the additional extent which shall be added to each
* edge of the image (top, bottom, left, right) in order to compensate for any
* drawing effects applied to the DrawingML object.
*
* The extent element specifies the size of the actual DrawingML object; however,
* an object may have effects applied which change its overall size. This element
* accounts for that additional space.
* *
* Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_effectExtent_topic_ID0E5O3OB.html * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_effectExtent_topic_ID0E5O3OB.html
* *
* ## XSD Schema * ## XSD Schema
*
* ```xml * ```xml
* <xsd:complexType name="CT_EffectExtent"> * <xsd:complexType name="CT_EffectExtent">
* <xsd:attribute name="l" type="a:ST_Coordinate" use="required"/> * <xsd:attribute name="l" type="a:ST_Coordinate" use="required"/>
@@ -44,6 +62,16 @@ export type EffectExtentAttributes = {
* <xsd:attribute name="b" type="a:ST_Coordinate" use="required"/> * <xsd:attribute name="b" type="a:ST_Coordinate" use="required"/>
* </xsd:complexType> * </xsd:complexType>
* ``` * ```
*
* @example
* ```typescript
* const effectExtent = createEffectExtent({
* top: 0,
* right: 0,
* bottom: 0,
* left: 0
* });
* ```
*/ */
export const createEffectExtent = ({ top, right, bottom, left }: EffectExtentAttributes): XmlComponent => export const createEffectExtent = ({ top, right, bottom, left }: EffectExtentAttributes): XmlComponent =>
new BuilderElement<EffectExtentAttributes>({ new BuilderElement<EffectExtentAttributes>({
+30 -6
View File
@@ -1,5 +1,18 @@
/**
* Extent (size) for DrawingML objects.
*
* This module provides support for defining the size of DrawingML objects
* in inline drawings.
*
* Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_extent_topic_ID0EQB4OB.html
*
* @module
*/
import { BuilderElement, XmlComponent } from "@file/xml-components"; import { BuilderElement, XmlComponent } from "@file/xml-components";
/**
* Attributes for extent.
*/
type ExtentAttributes = { type ExtentAttributes = {
/** /**
* ## Extent Length * ## Extent Length
@@ -37,17 +50,28 @@ type ExtentAttributes = {
}; };
/** /**
* This element specifies the extents of the parent `DrawingML` object within the document (i.e. its final height and width). * Creates an extent element for inline drawings.
*
* This element specifies the extents of the parent DrawingML object within
* the document (i.e. its final height and width).
* *
* Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_extent_topic_ID0EQB4OB.html * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_extent_topic_ID0EQB4OB.html
* *
* ## XSD Schema * ## XSD Schema
*
* ```xml * ```xml
* <complexType name="CT_PositiveSize2D"> * <xsd:complexType name="CT_PositiveSize2D">
* <attribute name="cx" type="ST_PositiveCoordinate" use="required"/> * <xsd:attribute name="cx" type="ST_PositiveCoordinate" use="required"/>
* <attribute name="cy" type="ST_PositiveCoordinate" use="required"/> * <xsd:attribute name="cy" type="ST_PositiveCoordinate" use="required"/>
* </complexType> * </xsd:complexType>
* ```
*
* @example
* ```typescript
* // Create a 1-inch by 1-inch extent
* const extent = createExtent({
* x: 914400,
* y: 914400
* });
* ``` * ```
*/ */
export const createExtent = ({ x, y }: ExtentAttributes): XmlComponent => export const createExtent = ({ x, y }: ExtentAttributes): XmlComponent =>
@@ -1,4 +1,13 @@
// http://officeopenxml.com/drwPicFloating-position.php /**
* Horizontal position module for floating drawings in WordprocessingML documents.
*
* This module provides horizontal positioning for floating drawing objects,
* specifying the horizontal placement relative to a base element.
*
* Reference: http://officeopenxml.com/drwPicFloating-position.php
*
* @module
*/
import { BuilderElement, XmlComponent } from "@file/xml-components"; import { BuilderElement, XmlComponent } from "@file/xml-components";
import { createAlign } from "./align"; import { createAlign } from "./align";
@@ -6,9 +15,41 @@ import { HorizontalPositionRelativeFrom, IHorizontalPositionOptions } from "./fl
import { createPositionOffset } from "./position-offset"; import { createPositionOffset } from "./position-offset";
/** /**
* Horizontal Positioning * Creates a horizontal position element for floating drawings.
*
* The positionH element specifies the horizontal positioning of a floating
* object relative to a base element (page, margin, column, etc.).
* *
* Reference: https://www.datypic.com/sc/ooxml/e-wp_positionH-1.html * Reference: https://www.datypic.com/sc/ooxml/e-wp_positionH-1.html
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_PosH">
* <xsd:choice>
* <xsd:element name="align" type="ST_AlignH"/>
* <xsd:element name="posOffset" type="ST_PositionOffset"/>
* </xsd:choice>
* <xsd:attribute name="relativeFrom" type="ST_RelFromH" use="required"/>
* </xsd:complexType>
* ```
*
* @param options - Horizontal position configuration
* @returns The positionH XML element
*
* @example
* ```typescript
* // Align to the left of the page
* createHorizontalPosition({
* relative: HorizontalPositionRelativeFrom.PAGE,
* align: HorizontalPositionAlign.LEFT,
* });
*
* // Offset from the margin
* createHorizontalPosition({
* relative: HorizontalPositionRelativeFrom.MARGIN,
* offset: 914400, // 1 inch in EMUs
* });
* ```
*/ */
export const createHorizontalPosition = ({ relative, align, offset }: IHorizontalPositionOptions): XmlComponent => export const createHorizontalPosition = ({ relative, align, offset }: IHorizontalPositionOptions): XmlComponent =>
new BuilderElement<{ new BuilderElement<{
+5
View File
@@ -1,3 +1,8 @@
/**
* Floating drawing position module exports.
*
* @module
*/
export * from "./floating-position"; export * from "./floating-position";
export * from "./simple-pos"; export * from "./simple-pos";
export * from "./horizontal-position"; export * from "./horizontal-position";
+42 -3
View File
@@ -1,4 +1,13 @@
// http://officeopenxml.com/drwPicFloating-position.php /**
* Vertical position module for floating drawings in WordprocessingML documents.
*
* This module provides vertical positioning for floating drawing objects,
* specifying the vertical placement relative to a base element.
*
* Reference: http://officeopenxml.com/drwPicFloating-position.php
*
* @module
*/
import { BuilderElement, XmlComponent } from "@file/xml-components"; import { BuilderElement, XmlComponent } from "@file/xml-components";
import { createAlign } from "./align"; import { createAlign } from "./align";
@@ -6,11 +15,41 @@ import { IVerticalPositionOptions, VerticalPositionRelativeFrom } from "./floati
import { createPositionOffset } from "./position-offset"; import { createPositionOffset } from "./position-offset";
/** /**
* Vertical Positioning * Creates a vertical position element for floating drawings.
* *
* This simple type specifies the possible values for the base from which the relative vertical positioning of an object shall be calculated. * The positionV element specifies the vertical positioning of a floating
* object relative to a base element (page, margin, paragraph, line, etc.).
* *
* Reference: https://www.datypic.com/sc/ooxml/e-wp_positionV-1.html * Reference: https://www.datypic.com/sc/ooxml/e-wp_positionV-1.html
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_PosV">
* <xsd:choice>
* <xsd:element name="align" type="ST_AlignV"/>
* <xsd:element name="posOffset" type="ST_PositionOffset"/>
* </xsd:choice>
* <xsd:attribute name="relativeFrom" type="ST_RelFromV" use="required"/>
* </xsd:complexType>
* ```
*
* @param options - Vertical position configuration
* @returns The positionV XML element
*
* @example
* ```typescript
* // Align to the top of the page
* createVerticalPosition({
* relative: VerticalPositionRelativeFrom.PAGE,
* align: VerticalPositionAlign.TOP,
* });
*
* // Offset from the paragraph
* createVerticalPosition({
* relative: VerticalPositionRelativeFrom.PARAGRAPH,
* offset: 457200, // 0.5 inch in EMUs
* });
* ```
*/ */
export const createVerticalPosition = ({ relative, align, offset }: IVerticalPositionOptions): XmlComponent => export const createVerticalPosition = ({ relative, align, offset }: IVerticalPositionOptions): XmlComponent =>
new BuilderElement<{ new BuilderElement<{
@@ -1,7 +1,15 @@
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
/**
* Attributes for graphic frame locking properties.
*
* Defines the XML attributes that control which operations are forbidden
* on a graphic frame element.
*/
export class GraphicFrameLockAttributes extends XmlAttributeComponent<{ export class GraphicFrameLockAttributes extends XmlAttributeComponent<{
/** DrawingML namespace declaration */
readonly xmlns?: string; readonly xmlns?: string;
/** Disallow aspect ratio changes (0=allow, 1=disallow) */
readonly noChangeAspect?: number; readonly noChangeAspect?: number;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
@@ -2,6 +2,35 @@ import { XmlComponent } from "@file/xml-components";
import { GraphicFrameLockAttributes } from "./graphic-frame-lock-attributes"; import { GraphicFrameLockAttributes } from "./graphic-frame-lock-attributes";
/**
* Represents graphic frame locking properties in DrawingML.
*
* This element specifies all locking properties for a graphic frame. These properties
* inform the generating application about which operations are forbidden on the parent
* graphic frame.
*
* Reference: http://officeopenxml.com/drwPic.php
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_GraphicalObjectFrameLocking">
* <xsd:sequence>
* <xsd:element name="extLst" type="CT_OfficeArtExtensionList" minOccurs="0" maxOccurs="1"/>
* </xsd:sequence>
* <xsd:attribute name="noGrp" type="xsd:boolean" use="optional"/>
* <xsd:attribute name="noDrilldown" type="xsd:boolean" use="optional"/>
* <xsd:attribute name="noSelect" type="xsd:boolean" use="optional"/>
* <xsd:attribute name="noChangeAspect" type="xsd:boolean" use="optional"/>
* <xsd:attribute name="noMove" type="xsd:boolean" use="optional"/>
* <xsd:attribute name="noResize" type="xsd:boolean" use="optional"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* const locks = new GraphicFrameLocks();
* ```
*/
export class GraphicFrameLocks extends XmlComponent { export class GraphicFrameLocks extends XmlComponent {
public constructor() { public constructor() {
super("a:graphicFrameLocks"); super("a:graphicFrameLocks");
+5
View File
@@ -1,3 +1,8 @@
/**
* Drawing module exports.
*
* @module
*/
export * from "./drawing"; export * from "./drawing";
export * from "./text-wrap"; export * from "./text-wrap";
export * from "./floating"; export * from "./floating";
@@ -1,6 +1,24 @@
/**
* Graphic data attributes module.
*
* This module defines the URI attribute that identifies the type
* of graphical content within a graphicData element.
*
* @module
*/
import { XmlAttributeComponent } from "@file/xml-components"; import { XmlAttributeComponent } from "@file/xml-components";
/**
* XML attributes component for graphic data.
*
* The URI attribute identifies the schema namespace of the content
* stored in the graphicData element. For pictures, this is typically
* "http://schemas.openxmlformats.org/drawingml/2006/picture".
*
* @internal
*/
export class GraphicDataAttributes extends XmlAttributeComponent<{ export class GraphicDataAttributes extends XmlAttributeComponent<{
/** URI identifying the type of graphical content */
readonly uri?: string; readonly uri?: string;
}> { }> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
@@ -1,3 +1,13 @@
/**
* Graphic data module for DrawingML elements.
*
* This module provides the graphicData element that contains
* the actual graphical content within a graphic element.
*
* Reference: http://officeopenxml.com/drwPic.php
*
* @module
*/
import { IMediaData, IMediaDataTransformation } from "@file/media"; import { IMediaData, IMediaDataTransformation } from "@file/media";
import { XmlComponent } from "@file/xml-components"; import { XmlComponent } from "@file/xml-components";
@@ -5,6 +15,34 @@ import { GraphicDataAttributes } from "./graphic-data-attribute";
import { Pic } from "./pic"; import { Pic } from "./pic";
import { OutlineOptions } from "./pic/shape-properties/outline/outline"; import { OutlineOptions } from "./pic/shape-properties/outline/outline";
/**
* Represents graphical data within a DrawingML graphic element.
*
* GraphicData contains the actual picture, chart, or other graphical
* content referenced by a graphic element. It uses a URI to identify
* the type of content being stored.
*
* Reference: http://officeopenxml.com/drwPic.php
*
* ## XSD Schema
* ```xml
* <xsd:complexType name="CT_GraphicalObjectData">
* <xsd:sequence>
* <xsd:any minOccurs="0" maxOccurs="unbounded" processContents="strict"/>
* </xsd:sequence>
* <xsd:attribute name="uri" type="xsd:token" use="required"/>
* </xsd:complexType>
* ```
*
* @example
* ```typescript
* const graphicData = new GraphicData({
* mediaData: imageData,
* transform: transformation,
* outline: { color: "000000", width: 9525 }
* });
* ```
*/
export class GraphicData extends XmlComponent { export class GraphicData extends XmlComponent {
private readonly pic: Pic; private readonly pic: Pic;

Some files were not shown because too many files have changed in this diff Show More