Helper functions for measurement conversion, ID generation, value formatting, and other common operations when working with Word documents.
Functions for converting between different measurement units commonly used in document formatting.
/**
* Convert millimeters to twips (twentieths of a point)
* @param millimeters - Value in millimeters
* @returns Value in twips
*/
function convertMillimetersToTwip(millimeters: number): number;
/**
* Convert inches to twips
* @param inches - Value in inches
* @returns Value in twips
*/
function convertInchesToTwip(inches: number): number;Usage Examples:
import { convertMillimetersToTwip, convertInchesToTwip, Paragraph } from "docx";
// Convert measurements for document margins
const leftMargin = convertInchesToTwip(1); // 1 inch = 1440 twips
const rightMargin = convertMillimetersToTwip(25); // 25mm ≈ 708 twips
const paragraph = new Paragraph({
text: "Paragraph with converted measurements",
indent: {
left: leftMargin,
right: rightMargin,
},
});
// Useful conversion reference:
// 1 inch = 1440 twips
// 1 cm = 567 twips
// 1 mm = 56.7 twips
// 1 point = 20 twipsFunctions for generating unique identifiers used throughout document creation.
/**
* Create a unique numeric ID generator
* @param initial - Starting value for the generator (optional)
* @returns Function that generates sequential numeric IDs
*/
function uniqueNumericIdCreator(initial?: number): UniqueNumericIdCreator;
/**
* Unique numeric ID creator function type
*/
type UniqueNumericIdCreator = () => number;
/**
* Generate unique numeric ID for abstract numbering
* @returns Sequential numeric ID for abstract numbering
*/
function abstractNumUniqueNumericIdGen(): UniqueNumericIdCreator;
/**
* Generate unique numeric ID for concrete numbering
* @returns Sequential numeric ID for concrete numbering
*/
function concreteNumUniqueNumericIdGen(): UniqueNumericIdCreator;
/**
* Generate unique numeric ID for document properties
* @returns Sequential numeric ID for document properties
*/
function docPropertiesUniqueNumericIdGen(): UniqueNumericIdCreator;
/**
* Generate unique numeric ID for bookmarks
* @returns Sequential numeric ID for bookmarks
*/
function bookmarkUniqueNumericIdGen(): UniqueNumericIdCreator;
/**
* Generate a unique string identifier
* @returns Unique string ID
*/
function uniqueId(): string;
/**
* Generate a hashed ID from input data
* @param data - Input data to hash
* @returns Hashed string ID
*/
function hashedId(data: Buffer | string | Uint8Array | ArrayBuffer): string;
/**
* Generate a unique UUID
* @returns UUID string
*/
function uniqueUuid(): string;Usage Examples:
import {
uniqueNumericIdCreator,
uniqueId,
hashedId,
uniqueUuid,
Bookmark
} from "docx";
// Create a numeric ID generator starting from 100
const idGenerator = uniqueNumericIdCreator(100);
const id1 = idGenerator(); // 100
const id2 = idGenerator(); // 101
const id3 = idGenerator(); // 102
// Generate unique string IDs
const stringId = uniqueId(); // e.g., "rId123"
const uuid = uniqueUuid(); // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Generate hashed ID from content
const contentHash = hashedId("bookmark-content");
// Use in document elements
const bookmark = new Bookmark({
id: uniqueId(),
children: [new TextRun("Bookmark content")],
});Functions for formatting and validating various value types used in document properties.
/**
* Format decimal number value
* @param val - Numeric value
* @returns Formatted decimal number
*/
function decimalNumber(val: number): number;
/**
* Format unsigned decimal number value
* @param val - Numeric value (must be positive)
* @returns Formatted unsigned decimal number
*/
function unsignedDecimalNumber(val: number): number;
/**
* Format long hexadecimal number
* @param val - Hexadecimal string value
* @returns Formatted long hex number
*/
function longHexNumber(val: string): string;
/**
* Format short hexadecimal number
* @param val - Hexadecimal string value
* @returns Formatted short hex number
*/
function shortHexNumber(val: string): string;
/**
* Format Unicode character hexadecimal number
* @param val - Hexadecimal string value
* @returns Formatted Unicode char hex number
*/
function uCharHexNumber(val: string): string;
/**
* Format universal measure value
* @param val - Universal measure value
* @returns Formatted universal measure
*/
function universalMeasureValue(val: UniversalMeasure): UniversalMeasure;
/**
* Format positive universal measure value
* @param val - Positive universal measure value
* @returns Formatted positive universal measure
*/
function positiveUniversalMeasureValue(val: PositiveUniversalMeasure): PositiveUniversalMeasure;
/**
* Format hexadecimal color value
* @param val - Color string (hex format)
* @returns Formatted hex color value
*/
function hexColorValue(val: string): string;
/**
* Format signed twips measure value
* @param val - Universal measure or numeric value
* @returns Formatted signed twips measure
*/
function signedTwipsMeasureValue(val: UniversalMeasure | number): UniversalMeasure | number;
/**
* Format half-point measure value
* @param val - Universal measure or numeric value
* @returns Formatted half-point measure
*/
function hpsMeasureValue(val: PositiveUniversalMeasure | number): string | number;
/**
* Format signed half-point measure value
* @param val - Universal measure or numeric value
* @returns Formatted signed half-point measure
*/
function signedHpsMeasureValue(val: UniversalMeasure | number): string | number;
/**
* Format twips measure value
* @param val - Universal measure or numeric value
* @returns Formatted twips measure
*/
function twipsMeasureValue(val: PositiveUniversalMeasure | number): PositiveUniversalMeasure | number;
/**
* Format percentage value
* @param val - Percentage value
* @returns Formatted percentage
*/
function percentageValue(val: Percentage): Percentage;
/**
* Format measurement or percentage value
* @param val - Numeric, percentage, or universal measure value
* @returns Formatted measurement or percentage
*/
function measurementOrPercentValue(val: number | Percentage | UniversalMeasure): number | UniversalMeasure | Percentage;
/**
* Format eighth-point measure value
* @param val - Numeric value
* @returns Formatted eighth-point measure
*/
function eighthPointMeasureValue(val: number): number;
/**
* Format point measure value
* @param val - Numeric value
* @returns Formatted point measure
*/
function pointMeasureValue(val: number): number;
/**
* Format date-time value for Word documents
* @param val - Date object
* @returns Formatted date-time string
*/
function dateTimeValue(val: Date): string;Usage Examples:
import {
hexColorValue,
percentageValue,
dateTimeValue,
measurementOrPercentValue,
TextRun,
Document
} from "docx";
// Format color values
const redColor = hexColorValue("FF0000");
const blueColor = hexColorValue("#0000FF"); // Handles # prefix
// Format percentage values
const width = percentageValue("50%");
const opacity = percentageValue("75%");
// Format date values
const creationDate = dateTimeValue(new Date());
// Format mixed measurement values
const margin1 = measurementOrPercentValue("1in");
const margin2 = measurementOrPercentValue("50%");
const margin3 = measurementOrPercentValue(720); // twips
// Use in document elements
const coloredText = new TextRun({
text: "Colored text",
color: hexColorValue("FF6600"),
});
const doc = new Document({
sections: [{ children: [...] }],
creator: "Document Generator",
created: dateTimeValue(new Date()),
});Utility type definitions for measurements and values.
/**
* Universal measurement with unit suffix
*/
type UniversalMeasure = `${"-" | ""}${number}${"mm" | "cm" | "in" | "pt" | "pc" | "pi"}`;
/**
* Positive universal measurement
*/
type PositiveUniversalMeasure = `${number}${"mm" | "cm" | "in" | "pt" | "pc" | "pi"}`;
/**
* Percentage value with % suffix
*/
type Percentage = `${"-" | ""}${number}%`;
/**
* Positive percentage value
*/
type PositivePercentage = `${number}%`;
/**
* Relative measurement (em, ex units)
*/
type RelativeMeasure = `${"-" | ""}${number}${"em" | "ex"}`;Common patterns for using utility functions in document creation:
Consistent Spacing and Margins:
import { convertInchesToTwip, Document, Paragraph } from "docx";
const STANDARD_MARGIN = convertInchesToTwip(1);
const PARAGRAPH_SPACING = convertInchesToTwip(0.1);
const doc = new Document({
sections: [{
properties: {
page: {
margin: {
top: STANDARD_MARGIN,
right: STANDARD_MARGIN,
bottom: STANDARD_MARGIN,
left: STANDARD_MARGIN,
},
},
},
children: [
new Paragraph({
text: "Consistently spaced paragraph",
spacing: {
after: PARAGRAPH_SPACING,
},
}),
],
}],
});ID Management for Complex Documents:
import { uniqueNumericIdCreator, uniqueId, Bookmark, InternalHyperlink } from "docx";
// Create ID generators for different element types
const bookmarkIdGen = uniqueNumericIdCreator(1);
const hyperlinkIdGen = uniqueNumericIdCreator(100);
// Generate consistent IDs
const bookmarkId = `bookmark_${bookmarkIdGen()}`;
const hyperlinkId = `hyperlink_${hyperlinkIdGen()}`;
const bookmark = new Bookmark({
id: bookmarkId,
children: [new TextRun("Referenced section")],
});
const hyperlink = new InternalHyperlink({
children: [new TextRun("Go to section")],
anchor: bookmarkId,
});Color and Style Consistency:
import { hexColorValue, TextRun } from "docx";
// Define color palette
const COLORS = {
primary: hexColorValue("2E74B5"),
secondary: hexColorValue("F4B942"),
success: hexColorValue("28A745"),
error: hexColorValue("DC3545"),
text: hexColorValue("333333"),
};
// Use consistent colors throughout document
const titleRun = new TextRun({
text: "Document Title",
color: COLORS.primary,
bold: true,
});
const errorRun = new TextRun({
text: "Error message",
color: COLORS.error,
});