or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-layout.mdcontent-elements.mddocument-creation.mddocument-export.mddocument-patching.mdindex.mdstyling-formatting.mdutility-functions.md
tile.json

document-export.mddocs/

Document Export

Document export functionality with multiple output formats and customization options for generating Word documents in various formats.

Capabilities

Packer Class

Static utility class providing methods to export documents to various formats including Buffer, Blob, Stream, and more.

/**
 * Static utility class for exporting documents to various formats
 */
class Packer {
  /** 
   * Export document to specified format type
   * @param file - Document to export
   * @param type - Output format type
   * @param prettify - XML prettification options
   * @param overrides - Export overrides
   * @returns Promise resolving to the specified output type
   */
  static pack<T>(
    file: Document, 
    type: T, 
    prettify?: PrettifyType, 
    overrides?: any
  ): Promise<OutputByType[T]>;

  /**
   * Export document as XML string
   * @param file - Document to export
   * @param prettify - XML prettification options
   * @param overrides - Export overrides
   * @returns Promise resolving to XML string
   */
  static toString(
    file: Document, 
    prettify?: PrettifyType, 
    overrides?: any
  ): Promise<string>;

  /**
   * Export document as Node.js Buffer
   * @param file - Document to export
   * @param prettify - XML prettification options
   * @param overrides - Export overrides
   * @returns Promise resolving to Buffer
   */
  static toBuffer(
    file: Document, 
    prettify?: PrettifyType, 
    overrides?: any
  ): Promise<Buffer>;

  /**
   * Export document as Base64 string
   * @param file - Document to export
   * @param prettify - XML prettification options
   * @param overrides - Export overrides
   * @returns Promise resolving to Base64 string
   */
  static toBase64String(
    file: Document, 
    prettify?: PrettifyType, 
    overrides?: any
  ): Promise<string>;

  /**
   * Export document as Blob (browser environment)
   * @param file - Document to export
   * @param prettify - XML prettification options
   * @param overrides - Export overrides
   * @returns Promise resolving to Blob
   */
  static toBlob(
    file: Document, 
    prettify?: PrettifyType, 
    overrides?: any
  ): Promise<Blob>;

  /**
   * Export document as ArrayBuffer
   * @param file - Document to export
   * @param prettify - XML prettification options
   * @param overrides - Export overrides
   * @returns Promise resolving to ArrayBuffer
   */
  static toArrayBuffer(
    file: Document, 
    prettify?: PrettifyType, 
    overrides?: any
  ): Promise<ArrayBuffer>;

  /**
   * Export document as readable Stream (Node.js)
   * @param file - Document to export
   * @param prettify - XML prettification options
   * @param overrides - Export overrides
   * @returns Readable stream
   */
  static toStream(
    file: Document, 
    prettify?: PrettifyType, 
    overrides?: any
  ): Stream;
}

Usage Examples:

import { Document, Packer, Paragraph } from "docx";
import * as fs from "fs";

const doc = new Document({
  sections: [{
    children: [
      new Paragraph("Hello World"),
    ],
  }],
});

// Export to Buffer (Node.js)
Packer.toBuffer(doc).then((buffer) => {
  fs.writeFileSync("document.docx", buffer);
});

// Export to Blob (Browser)
Packer.toBlob(doc).then((blob) => {
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = "document.docx";
  link.click();
});

// Export to Base64 string
Packer.toBase64String(doc).then((base64) => {
  console.log("Document as Base64:", base64);
});

// Export with prettified XML
Packer.toString(doc, PrettifyType.WITH_4_BLANKS).then((xml) => {
  console.log("Pretty XML:", xml);
});

Output Types

Type definitions for all supported output formats.

/**
 * Map of output types to their corresponding TypeScript types
 */
type OutputByType = {
  readonly base64: string;
  readonly string: string;
  readonly text: string;
  readonly binarystring: string;
  readonly array: readonly number[];
  readonly uint8array: Uint8Array;
  readonly arraybuffer: ArrayBuffer;
  readonly blob: Blob;
  readonly nodebuffer: Buffer;
};

/**
 * Available output format types
 */
type OutputType = keyof OutputByType;

Prettify Options

Options for XML formatting and prettification.

/**
 * XML prettification options for readable output
 */
const PrettifyType = {
  /** No formatting (minified) */
  NONE: "",
  /** 2-space indentation */
  WITH_2_BLANKS: "  ",
  /** 4-space indentation */
  WITH_4_BLANKS: "    ",
  /** Tab indentation */
  WITH_TAB: "\t"
} as const;

type PrettifyType = typeof PrettifyType[keyof typeof PrettifyType];

Usage Example:

import { Document, Packer, PrettifyType } from "docx";

const doc = new Document({
  sections: [{ children: [...] }],
});

// Export with different prettification options
const minified = await Packer.toString(doc, PrettifyType.NONE);
const readable = await Packer.toString(doc, PrettifyType.WITH_4_BLANKS);
const tabbed = await Packer.toString(doc, PrettifyType.WITH_TAB);

Export Process

The export process involves several steps:

  1. Document Serialization: The Document and all its components are serialized to XML
  2. ZIP Packaging: The XML files are packaged into a .docx ZIP archive
  3. Format Conversion: The ZIP archive is converted to the requested output format
  4. Return: The final output is returned as a Promise

Advanced Export Example:

import { Document, Packer, Paragraph, TextRun } from "docx";
import * as fs from "fs";

const doc = new Document({
  sections: [{
    children: [
      new Paragraph({
        children: [
          new TextRun("This is a "),
          new TextRun({ text: "formatted", bold: true }),
          new TextRun(" document."),
        ],
      }),
    ],
  }],
  title: "Sample Document",
  creator: "Docx Library",
});

// Multiple export formats from the same document
Promise.all([
  Packer.toBuffer(doc),
  Packer.toBase64String(doc),
  Packer.toString(doc, PrettifyType.WITH_2_BLANKS),
]).then(([buffer, base64, xml]) => {
  // Save binary file
  fs.writeFileSync("document.docx", buffer);
  
  // Log Base64 for transfer
  console.log("Base64 length:", base64.length);
  
  // Save readable XML for debugging
  fs.writeFileSync("document.xml", xml);
});

Browser Environment

Special considerations for browser environments:

// Browser-specific export example
import { Document, Packer } from "docx";

const doc = new Document({
  sections: [{ children: [...] }],
});

// Create downloadable link
Packer.toBlob(doc).then((blob) => {
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = "my-document.docx";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
});

// Send via fetch API
Packer.toArrayBuffer(doc).then((arrayBuffer) => {
  fetch("/api/save-document", {
    method: "POST",
    headers: {
      "Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    },
    body: arrayBuffer,
  });
});

Error Handling

Export operations can fail for various reasons. Always handle errors appropriately:

import { Document, Packer } from "docx";

const doc = new Document({
  sections: [{ children: [...] }],
});

try {
  const buffer = await Packer.toBuffer(doc);
  fs.writeFileSync("document.docx", buffer);
  console.log("Document exported successfully");
} catch (error) {
  console.error("Export failed:", error);
  // Handle export failure appropriately
}