### Install OpenXmlSdkTs Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Getting_Started.html Use npm to install the library and its runtime dependencies. ```bash npm install openxmlsdkts ``` -------------------------------- ### Perform Basic Document Operations Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Getting_Started.html A complete example showing how to open a Word document, inspect its content, add a paragraph, and save the changes. ```typescript import { WmlPackage, W, XElement } from "openxmlsdkts"; import fs from "fs"; // Read the file into a Blob const buffer = fs.readFileSync("report.docx"); const doc = await WmlPackage.open(new Blob([buffer])); // Navigate to the main document part const mainPart = await doc.mainDocumentPart(); const xDoc = await mainPart!.getXDocument(); // Query the XML const body = xDoc.root!.element(W.body); const paragraphs = body!.elements(W.p); console.log(`Document has ${paragraphs.length} paragraphs`); // Add a new paragraph const newPara = new XElement(W.p, new XElement(W.r, new XElement(W.t, "Hello from OpenXmlSdkTs!") ) ); body!.add(newPara); // Save changes back to the part and export mainPart!.putXDocument(xDoc); const blob = await doc.saveToBlobAsync(); ``` -------------------------------- ### Utility Class Usage Examples Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.Utility.html Demonstrates importing the Utility class and using its methods to resolve relationship URIs and validate Base64 strings. ```typescript import { Utility } from "openxmlsdkts"; const relsUri = Utility.getRelsPartUri(mainPart); // "/word/_rels/document.xml.rels" Utility.isBase64("UEsDBBQAAAA..."); // true Utility.isBase64(", ] ``` -------------------------------- ### WmlPackage.open Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPackage.html Opens a .docx file from a Blob and returns a WmlPackage instance. ```APIDOC ## WmlPackage.open ### Description Opens a Word document package from a provided Blob. ### Signature static open(blob: Blob): Promise ### Parameters - **blob** (Blob) - The source .docx file as a Blob. ``` -------------------------------- ### Get parts by relationship type Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.SmlPackage.html Retrieves parts associated with a specific relationship type, such as theme parts. ```typescript import { RelationshipType } from "openxmlsdkts"; const themeParts = await pkg.getPartsByRelationshipType(RelationshipType.theme); ``` -------------------------------- ### new XProcessingInstruction(other) Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XProcessingInstruction.html Creates a new XProcessingInstruction by copying an existing instance. ```APIDOC ## Constructor: new XProcessingInstruction(other: XProcessingInstruction) ### Description Creates a new XProcessingInstruction by copying another instance. ### Parameters - **other** (XProcessingInstruction) - Required - The instance to copy. ``` -------------------------------- ### Create and use an XNamespace Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XNamespace.html Demonstrates retrieving an XNamespace instance and using it to create an XName or generate Clark-notation strings. ```typescript const W = XNamespace.get('http://schemas.openxmlformats.org/wordprocessingml/2006/main'); const wBody = W.getName('body'); // Clark notation via string concatenation: const name = W + 'body'; // '{http://...}body' ``` -------------------------------- ### Open and Save an OpenXmlPackage Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPackage.html Demonstrates opening a document from a buffer and saving the package back to a blob. ```typescript import { OpenXmlPackage } from "openxmlsdkts"; import fs from "fs"; const buffer = fs.readFileSync("document.docx"); const pkg = await OpenXmlPackage.open(new Blob([buffer])); const parts = pkg.getParts(); console.log(`Package contains ${parts.length} parts`); const blob = await pkg.saveToBlobAsync(); ``` -------------------------------- ### Initialize and Parse XDocument Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XDocument.html Demonstrates creating an XDocument with a declaration and root element, as well as parsing an XML string. ```typescript const doc = new XDocument( new XDeclaration('1.0', 'UTF-8', 'yes'), new XElement('root', new XElement('child')), ); doc.declaration?.version; // '1.0' doc.root?.name.localName; // 'root' const doc = XDocument.parse(""); ``` -------------------------------- ### new VML() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.VML.html Constructor for the VML class. ```APIDOC ## new VML() ### Description Creates a new instance of the VML class. ### Returns - **VML** - A new instance of the VML class. ``` -------------------------------- ### SmlPackage.open Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.SmlPackage.html Opens an Excel document from a string or Blob. ```APIDOC ## Static open ### Description Opens an Excel document from any supported format. ### Signature `open(document: string | Blob): Promise` ### Parameters - **document** (string | Blob) - Required - The document to open (Blob, Base64 string, or Flat OPC XML string). ### Returns - **Promise** - A promise resolving to a SmlPackage instance. ``` -------------------------------- ### new XProcessingInstruction(target, data) Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XProcessingInstruction.html Creates a new XProcessingInstruction instance from target and data strings. ```APIDOC ## Constructor: new XProcessingInstruction(target: string, data: string) ### Description Creates a new XProcessingInstruction from target and data strings. The target must not contain whitespace or '?>', and the data must not contain '?>'. ### Parameters - **target** (string) - Required - The PI target. - **data** (string) - Required - The PI data. ### Throws - Error if target contains whitespace or if the target or data contains '?>'. ``` -------------------------------- ### Open a PowerPoint Presentation Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.PmlPackage.html Demonstrates how to open a .pptx file from a buffer and access its slide parts. ```typescript import { PmlPackage, P } from "openxmlsdkts"; import fs from "fs"; const buffer = fs.readFileSync("deck.pptx"); const doc = await PmlPackage.open(new Blob([buffer])); const presentation = await doc.presentationPart(); const slides = await presentation!.slideParts(); console.log(`${slides.length} slides`); ``` -------------------------------- ### new XSI() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XSI.html Constructor for the XSI class. ```APIDOC ## constructor ### Description Creates a new instance of the XSI class. ### Signature `new XSI(): XSI` ### Returns - **XSI** - A new instance of the XSI class. ``` -------------------------------- ### WmlPackage.getPartByUri Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPackage.html Looks up a part by its URI. ```APIDOC ## getPartByUri(uri: string): OpenXmlPart | undefined ### Description Looks up a part by its URI. ### Parameters - **uri** (string) - Required - The full part URI (e.g., "/word/document.xml"). ### Returns - **OpenXmlPart | undefined** - The matching OpenXmlPart, or undefined if not found. ``` -------------------------------- ### PmlPackage.open Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.PmlPackage.html Opens a PowerPoint document from a Blob, Base64 string, or Flat OPC XML string. ```APIDOC ## PmlPackage.open(document: string | Blob): Promise ### Description Opens a PowerPoint document from any supported format. ### Parameters - **document** (string | Blob) - Required - The document to open (Blob, Base64 string, or Flat OPC XML string). ### Returns - **Promise** - A promise resolving to a PmlPackage instance. ``` -------------------------------- ### WmlPackage.open Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPackage.html Opens a Word document from a string or Blob. ```APIDOC ## Static open(document: string | Blob): Promise ### Description Opens a Word document from any supported format. ### Parameters - **document** (string | Blob) - Required - The document to open (Blob, Base64 string, or Flat OPC XML string). ### Returns - **Promise** - A promise resolving to a WmlPackage instance. ``` -------------------------------- ### webSettingsPart() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPart.html Retrieves the web settings part from the document. ```APIDOC ## webSettingsPart() ### Description Returns the web settings part, or undefined if not present. ### Returns Promise ``` -------------------------------- ### Open an Open XML document Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPackage.html Demonstrates opening documents from binary Blobs, Base64 strings, or Flat OPC XML strings. ```typescript // Open from binary Blob const buffer = fs.readFileSync("document.docx"); const pkg = await OpenXmlPackage.open(new Blob([buffer])); // Open from Base64 string const base64 = fs.readFileSync("document.txt", "utf-8"); const pkg2 = await OpenXmlPackage.open(base64); // Open from Flat OPC XML string const flatOpc = fs.readFileSync("document.xml", "utf-8"); const pkg3 = await OpenXmlPackage.open(flatOpc); ``` -------------------------------- ### Open and Save Binary Blobs Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Opening_and_Saving_Documents.html Use Blob or Buffer for standard file system I/O with .docx, .xlsx, and .pptx files. ```typescript import { WmlPackage } from "openxmlsdkts"; import fs from "fs"; // Open from Blob const buffer = fs.readFileSync("document.docx"); const doc = await WmlPackage.open(new Blob([buffer])); // Save to Blob const blob = await doc.saveToBlobAsync(); ``` -------------------------------- ### Navigate Word Document Parts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/index.html Accesses package-level and part-level components within a WmlPackage. ```typescript const doc = await WmlPackage.open(blob); // Package-level const mainPart = await doc.mainDocumentPart(); const contentParts = await doc.contentParts(); // main + headers + footers + footnotes + endnotes // Part-level navigation const styles = await mainPart!.styleDefinitionsPart(); const theme = await mainPart!.themePart(); const numbering = await mainPart!.numberingDefinitionsPart(); const headers = await mainPart!.headerParts(); const footers = await mainPart!.footersParts(); const comments = await mainPart!.wordprocessingCommentsPart(); const fonts = await mainPart!.fontTablePart(); const settings = await mainPart!.documentSettingsPart(); ``` -------------------------------- ### constructor Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XDocument.html Creates a new instance of an XDocument. It can be initialized empty, with an XML declaration, as a clone of another document, or with specific content nodes. ```APIDOC ## constructor ### Description Creates a new XDocument instance. ### Signatures - `new XDocument()` - `new XDocument(declaration: XDeclaration)` - `new XDocument(other: XDocument)` - `new XDocument(...content: unknown[])` - `new XDocument(declaration: XDeclaration, ...content: unknown[])` ### Parameters - **declaration** (XDeclaration) - Optional - The XML declaration. - **other** (XDocument) - Optional - The document to deep-clone. - **content** (unknown[]) - Optional - Root element, comments, processing instructions, or whitespace-only strings. ``` -------------------------------- ### OpenXmlPackage.open Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPackage.html Opens an Open XML document from a binary Blob, Base64 string, or Flat OPC XML string. ```APIDOC ## static open(document: string | Blob): Promise ### Description Opens an Open XML document from any supported format. The method auto-detects the input format. ### Parameters - **document** (string | Blob) - Required - The document to open. ### Returns - **Promise** - A promise resolving to an OpenXmlPackage instance. ``` -------------------------------- ### Create and stringify an XProcessingInstruction Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XProcessingInstruction.html Instantiate a new processing instruction and convert it to its XML string representation. ```typescript const pi = new XProcessingInstruction('xml-stylesheet', 'type="text/css" href="style.css"'); pi.toString(); // '' ``` -------------------------------- ### Using XName for Qualified Names Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XName.html Demonstrates the caching behavior of XName instances and how to extract local names and namespace URIs using Clark notation. ```typescript const n1 = XName.get('title'); const n2 = XName.get('title'); n1 === n2; // true -- same cached instance XName.get('{urn:example}item').localName; // 'item' XName.get('{urn:example}item').namespaceName; // 'urn:example' ``` -------------------------------- ### OpenXmlPackage.saveToBlobAsync Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPackage.html Asynchronously saves the current package state to a Blob. ```APIDOC ## saveToBlobAsync() ### Description Serializes the package and returns it as a Blob. ### Returns - **Promise** - A promise that resolves to the package as a Blob. ``` -------------------------------- ### XNamespace.equals Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XNamespace.html Compares two XNamespace instances. ```APIDOC ## equals(other: XNamespace) ### Description Compares this namespace to another by identity (interned reference equality). ### Parameters - **other** (XNamespace) - Required - The namespace to compare against. ### Returns - **boolean** - true if both are the same interned instance. ``` -------------------------------- ### OpenXmlPackage.open Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPackage.html Static method to open an Open XML package. It auto-detects the input format from a binary Blob, Base64 string, or Flat OPC XML string. ```APIDOC ## static open(input) ### Description Opens an Open XML package from the provided input, automatically detecting the format. ### Parameters - **input** (Blob | string) - Required - The package data as a Blob, Base64 string, or Flat OPC XML string. ### Returns - **Promise** - A promise that resolves to an instance of OpenXmlPackage. ``` -------------------------------- ### new XAttribute(name, content?) Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XAttribute.html Creates a new instance of an XAttribute. It can be initialized with a name and value, a name alone, or by copying an existing XAttribute. ```APIDOC ## Constructor: new XAttribute(name: string | XName, content?: unknown | XAttribute) ### Description Creates a new XAttribute instance. The constructor supports initializing with a name and value, a name alone (resulting in an empty-string value), or by copying an existing XAttribute instance. ### Parameters - **name** (string | XName) - Required - The qualified name of the attribute. - **content** (unknown | XAttribute) - Optional - The value of the attribute, or an existing XAttribute to copy. ### Returns - **XAttribute** - A new instance of the XAttribute class. ### Example ```typescript const a = new XAttribute('id', '42'); const copy = new XAttribute(a); ``` ``` -------------------------------- ### XNamespace Constructor Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XNamespace.html Creates or retrieves a cached XNamespace instance for a given URI. ```APIDOC ## constructor(uri: string, preferredPrefix?: string | null) ### Description Creates (or retrieves from cache) an XNamespace for the given URI. ### Parameters - **uri** (string) - Required - The namespace URI string. - **preferredPrefix** (string | null) - Optional - Optional preferred prefix for serialization. ### Returns - **XNamespace** - The created or retrieved instance. ``` -------------------------------- ### new PKGREL() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.PKGREL.html Constructor for the PKGREL class. ```APIDOC ## constructor ### Description Creates a new instance of the PKGREL class. ### Signature `new PKGREL(): PKGREL` ### Returns - **PKGREL** - A new instance of the PKGREL class. ``` -------------------------------- ### Initialize and Access XAttribute Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XAttribute.html Demonstrates creating an attribute and accessing its name and value properties. ```typescript const a = new XAttribute('id', '42'); a.name.localName; // 'id' a.value; // '42' ``` -------------------------------- ### getPkg() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPart.html Returns the OpenXmlPackage that contains this part. ```APIDOC ## getPkg() ### Description Returns the OpenXmlPackage that contains this part. ### Returns - **OpenXmlPackage** - The parent package. ``` -------------------------------- ### OpenXmlPackage.getParts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPackage.html Retrieves all content parts in the package. ```APIDOC ## getParts(): OpenXmlPart[] ### Description Returns all content parts in the package, excluding the content-types part and relationship parts. ### Returns - **OpenXmlPart[]** - An array of all content OpenXmlPart instances. ``` -------------------------------- ### new XElement(name: string | XName) Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XElement.html Creates an empty XElement with the given name. ```APIDOC ## constructor(name: string | XName) ### Description Creates an empty XElement with the given name. ### Parameters - **name** (string | XName) - Required - The element name. ``` -------------------------------- ### Query and Add Parts using ContentType Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Content_and_Relationship_Types.html Demonstrates importing the ContentType object to query existing parts or define the MIME type when adding new parts to a package. ```typescript import { ContentType } from "openxmlsdkts"; // Query parts by content type const parts = await pkg.getPartsByContentType(ContentType.mainDocument); // Use when adding a new part await mainPart.addPart("/word/comments.xml", ContentType.wordprocessingComments, "xml", xDoc); ``` -------------------------------- ### SmlPackage.addPart Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.SmlPackage.html Adds a new part to the package. ```APIDOC ## addPart ### Description Adds a new part to the package. ### Signature `addPart(uri: string, contentType: string, partType: PartType, data: unknown): OpenXmlPart` ### Parameters - **uri** (string) - Required - The part URI (e.g., "/word/comments.xml"). - **contentType** (string) - Required - The MIME content type. - **partType** (PartType) - Required - The part data type: "xml", "binary", or "base64". - **data** (unknown) - Required - The part content. ### Returns - **OpenXmlPart** - The newly created OpenXmlPart. ``` -------------------------------- ### Accessing PresentationML elements Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.P.html Demonstrates using P and A constants to navigate the document tree and retrieve shape elements. ```typescript import { P, A } from "openxmlsdkts"; const spTree = xDoc.root!.element(P.cSld)?.element(P.spTree); const shapes = spTree?.elements(P.sp) ?? []; ``` -------------------------------- ### Open an Excel document Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.SmlPackage.html Demonstrates how to open an Excel file from a buffer and access its workbook and worksheet parts. ```typescript import { SmlPackage, S } from "openxmlsdkts"; import fs from "fs"; const buffer = fs.readFileSync("data.xlsx"); const doc = await SmlPackage.open(new Blob([buffer])); const workbook = await doc.workbookPart(); const worksheets = await workbook!.worksheetParts(); console.log(`${worksheets.length} worksheets`); ``` -------------------------------- ### Navigate PowerPoint Presentation Parts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Navigating_Parts.html Access presentation-specific parts like slides, masters, and layouts in a PmlPackage. ```typescript const pres = await PmlPackage.open(blob); // Presentation part (the root of presentation content) const presPart = await pres.presentationPart(); // Slides const slides = await pres.slideParts(); // Slide masters and layouts const masters = await pres.slideMasterParts(); const layouts = await pres.slideLayoutParts(); ``` -------------------------------- ### Document Round-Trip Workflow Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Opening_and_Saving_Documents.html Demonstrates opening a document, modifying its content, and saving it in a different format. ```typescript import { WmlPackage, W, XElement } from "openxmlsdkts"; // Open from Base64 (e.g., received from an API) const doc = await WmlPackage.open(base64Input); // Modify the document const mainPart = await doc.mainDocumentPart(); const xDoc = await mainPart!.getXDocument(); const body = xDoc.root!.element(W.body); body!.add( new XElement(W.p, new XElement(W.r, new XElement(W.t, "Added by OpenXmlSdkTs") ) ) ); mainPart!.putXDocument(xDoc); // Save as Flat OPC (e.g., to send to an Office Add-in) const flatOpc = await doc.saveToFlatOpcAsync(); ``` -------------------------------- ### Constructing and Cloning an XElement Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XElement.html Demonstrates creating an XML element with attributes and child nodes using functional construction, as well as deep-cloning an existing element. ```typescript const el = new XElement('item', new XAttribute('id', '1'), new XElement('name', 'Widget'), ); const copy = new XElement(el); // clone ``` -------------------------------- ### Accessing and Navigating OpenXmlPart Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPart.html Demonstrates reading XML content from a main document part and navigating to related parts using relationship types. ```typescript const mainPart = await doc.mainDocumentPart(); const xDoc = await mainPart!.getXDocument(); const body = xDoc.root!.element(W.body); console.log(`${body!.elements(W.p).length} paragraphs`); // Navigate to related parts const stylesPart = await mainPart!.getPartByRelationshipType(RelationshipType.styles); ``` -------------------------------- ### documentSettingsPart() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPart.html Retrieves the document settings part from the document. ```APIDOC ## documentSettingsPart() ### Description Returns the document settings part, or undefined if not present. ### Returns Promise ``` -------------------------------- ### getPkg() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlRelationship.html Returns the OpenXmlPackage that contains this relationship. ```APIDOC ### getPkg() Returns the OpenXmlPackage that contains this relationship. #### Returns - **OpenXmlPackage** - The parent package. ``` -------------------------------- ### WmlPackage.saveToBlobAsync Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPackage.html Saves the current WmlPackage instance to a Blob. ```APIDOC ## WmlPackage.saveToBlobAsync ### Description Serializes the current document package to a Blob. ### Signature saveToBlobAsync(): Promise ``` -------------------------------- ### XElement.loadAsync(filePath: string): Promise Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XElement.html Asynchronously loads and parses an XML file. ```APIDOC ## XElement.loadAsync(filePath: string): Promise ### Description Loads an XML file asynchronously and parses it into an XElement. ### Parameters - **filePath** (string) - Required - Path to the XML file. ### Returns - **Promise** - A promise that resolves to the parsed element. ### Example ``` const el = await XElement.loadAsync('/path/to/data.xml'); ``` ``` -------------------------------- ### Manage Package Parts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Navigating_Parts.html Add or remove parts from a package. ```typescript // Add a new part await mainPart!.addPart(newPart, relationshipType); // Delete a part await mainPart!.deletePart(existingPart); ``` -------------------------------- ### Copy an XAttribute Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XAttribute.html Demonstrates creating a new XAttribute instance by copying an existing one. ```typescript const a = new XAttribute('id', '42'); const copy = new XAttribute(a); ``` -------------------------------- ### OpenXmlPackage.getParts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPackage.html Retrieves all parts contained within the package. ```APIDOC ## getParts() ### Description Returns an array of all parts currently managed by the package. ### Returns - **Array** - A list of parts. ``` -------------------------------- ### XNamespace.get Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XNamespace.html Static method to retrieve a cached XNamespace instance. ```APIDOC ## XNamespace.get(uri: string) ### Description Returns a cached XNamespace for the given URI. ### Parameters - **uri** (string) - Required - The namespace URI string. ### Returns - **XNamespace** - The cached XNamespace instance. ``` -------------------------------- ### new XElement(other: XElement) Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XElement.html Deep-clones an existing XElement. ```APIDOC ## constructor(other: XElement) ### Description Deep-clones an existing XElement instance. ### Parameters - **other** (XElement) - Required - The element to clone. ``` -------------------------------- ### new XElement(name: string | XName, ...content: unknown[]) Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XElement.html Creates an XElement with the given name and content (child nodes, attributes, strings, or arrays). ```APIDOC ## constructor(name: string | XName, ...content: unknown[]) ### Description Creates an XElement with the given name and content via functional construction. ### Parameters - **name** (string | XName) - Required - The element name. - **content** (unknown[]) - Optional - Child nodes, attributes, strings, or arrays thereof. ``` -------------------------------- ### WmlPackage.addPart Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPackage.html Adds a new part to the package. ```APIDOC ## addPart(uri: string, contentType: string, partType: PartType, data: unknown): OpenXmlPart ### Description Adds a new part to the package. ### Parameters - **uri** (string) - Required - The part URI (e.g., "/word/comments.xml"). - **contentType** (string) - Required - The MIME content type. - **partType** (PartType) - Required - The part data type: "xml", "binary", or "base64". - **data** (unknown) - Required - The part content (an XDocument for XML parts, or a string/Blob for binary). ### Returns - **OpenXmlPart** - The newly created OpenXmlPart. ### Throws - Error if a part with the given URI already exists. ``` -------------------------------- ### Manipulate XML with LINQ to XML Source: https://ericwhitedev.github.io/OpenXmlSdkTs/index.html Demonstrates opening a document, querying elements, and adding new content using the WmlPackage and XElement APIs. ```typescript import { WmlPackage, W, NoNamespace, XElement } from "openxmlsdkts"; const doc = await WmlPackage.open(blob); const mainPart = await doc.mainDocumentPart(); const xDoc = await mainPart!.getXDocument(); // Query all paragraphs const paragraphs = xDoc.root!.element(W.body)!.elements(W.p); // Find paragraphs with a specific style for (const para of paragraphs) { const pPr = para.element(W.pPr); const pStyle = pPr?.element(W.pStyle); const styleVal = pStyle?.attribute(NoNamespace.val)?.value; if (styleVal === "Heading1") { console.log("Found Heading1 paragraph"); } } // Add a new paragraph const newPara = new XElement(W.p, new XElement(W.r, new XElement(W.t, "Hello from OpenXmlSdkTs!") ) ); xDoc.root!.element(W.body)!.add(newPara); // Write the modified XML back to the part mainPart!.putXDocument(xDoc); ``` -------------------------------- ### Open and Modify a Word Document Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPackage.html Demonstrates opening a .docx file, accessing the main document body, adding a new paragraph, and saving the changes. ```typescript import { WmlPackage, W, XElement } from "openxmlsdkts"; import fs from "fs"; const buffer = fs.readFileSync("report.docx"); const doc = await WmlPackage.open(new Blob([buffer])); const mainPart = await doc.mainDocumentPart(); const xDoc = await mainPart!.getXDocument(); const body = xDoc.root!.element(W.body); console.log(`Document has ${body!.elements(W.p).length} paragraphs`); // Add a new paragraph const newPara = new XElement(W.p, new XElement(W.r, new XElement(W.t, "Hello from OpenXmlSdkTs!"))); body!.add(newPara); mainPart!.putXDocument(xDoc); const blob = await doc.saveToBlobAsync(); ``` -------------------------------- ### presentationPart Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.PmlPackage.html Retrieves the main presentation part of the package. ```APIDOC ## presentationPart ### Description Returns the main presentation part. ### Signature `presentationPart(): Promise` ### Returns - **Promise** - The presentation PmlPart, or undefined if not found. ``` -------------------------------- ### PmlPackage.addPart Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.PmlPackage.html Adds a new part to the PowerPoint package. ```APIDOC ## PmlPackage.addPart(uri: string, contentType: string, partType: PartType, data: unknown): OpenXmlPart ### Description Adds a new part to the package. ### Parameters - **uri** (string) - Required - The part URI (e.g., "/word/comments.xml"). - **contentType** (string) - Required - The MIME content type. - **partType** (PartType) - Required - The part data type: "xml", "binary", or "base64". - **data** (unknown) - Required - The part content (an XDocument for XML parts, or a string/Blob for binary). ### Returns - **OpenXmlPart** - The newly created OpenXmlPart. ### Throws - Error if a part with the given URI already exists. ``` -------------------------------- ### XName.get Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XName.html Retrieves a cached XName instance for a given namespace and local name, or parses a Clark-notation string. ```APIDOC ## Static Method: XName.get ### Description Returns a cached XName for the given namespace and local name, or parses a Clark-notation string. ### Parameters - **namespace** (XNamespace | string) - Required - The namespace, or a string in Clark notation. - **localName** (string) - Optional - The local name (when providing an explicit namespace). ### Returns - **XName** - The cached XName instance. ``` -------------------------------- ### Load XML from File Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XElement.html Synchronously load and parse an XML file from the specified path. ```typescript const el = XElement.load('/path/to/data.xml'); ``` -------------------------------- ### WmlPackage.mainDocumentPart Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPackage.html Retrieves the main document part of the Word package. ```APIDOC ## WmlPackage.mainDocumentPart ### Description Returns the main document part associated with the WmlPackage. ### Signature mainDocumentPart(): Promise ``` -------------------------------- ### Navigate Word Document Parts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Navigating_Parts.html Access common parts in a WmlPackage such as main document, headers, footers, and styles. ```typescript const doc = await WmlPackage.open(blob); // Main content const mainPart = await doc.mainDocumentPart(); // Headers and footers const headers = await doc.headerParts(); const footers = await doc.footerParts(); // Content parts (main document + headers + footers) const allContent = await doc.contentParts(); // Styles and formatting const styles = await doc.styleDefinitionsPart(); // Other common parts const numbering = await doc.numberingDefinitionsPart(); const footnotes = await doc.footnotesPart(); const endnotes = await doc.endnotesPart(); const comments = await doc.commentsPart(); const settings = await doc.documentSettingsPart(); ``` -------------------------------- ### Accessing and Managing Relationships with RelationshipType Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Content_and_Relationship_Types.html Demonstrates how to import RelationshipType and use its properties to retrieve parts or add new relationships to a main part. ```typescript import { RelationshipType } from "openxmlsdkts"; // Get a part by relationship type const stylePart = await mainPart.getPartByRelationshipType(RelationshipType.styles); // Get all image relationships const imageRels = await mainPart.getRelationshipsByRelationshipType(RelationshipType.image); // Add a relationship await mainPart.addRelationship("rId20", RelationshipType.image, "media/image1.png"); ``` -------------------------------- ### Open and Save Binary Documents Source: https://ericwhitedev.github.io/OpenXmlSdkTs/index.html Handles standard ZIP-based .docx, .xlsx, or .pptx files using Blob objects. ```typescript // Open const buffer = fs.readFileSync("report.docx"); const doc = await WmlPackage.open(new Blob([buffer])); // Save const blob = await doc.saveToBlobAsync(); ``` -------------------------------- ### Add a new part to the package Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.SmlPackage.html Shows how to add a new XML part to the package using a specific URI, content type, and XDocument. ```typescript import { ContentType, XDocument, XElement, W } from "openxmlsdkts"; const xDoc = new XDocument(new XElement(W.comments)); pkg.addPart("/word/comments.xml", ContentType.wordprocessingComments, "xml", xDoc); ``` -------------------------------- ### Navigate Excel Spreadsheet Parts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/index.html Accesses workbook and worksheet components within an SmlPackage. ```typescript const doc = await SmlPackage.open(blob); const workbook = await doc.workbookPart(); const worksheets = await workbook!.worksheetParts(); const sharedStrings = await workbook!.sharedStringTablePart(); const wbStyles = await workbook!.workbookStylesPart(); const charts = await workbook!.chartsheetParts(); const pivotTables = await workbook!.pivotTableParts(); ``` -------------------------------- ### contentParts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPackage.html Retrieves all content parts within the package. ```APIDOC ## contentParts() ### Description Returns an array of content parts. ### Returns - **Promise** - An array of WmlPart objects. ``` -------------------------------- ### Manipulating Documents in Office Add-ins Source: https://ericwhitedev.github.io/OpenXmlSdkTs/index.html Workflow for opening, modifying, and saving a document as Flat OPC within an Office Add-in environment. ```typescript // In an Office Add-in — get the document as Flat OPC via the Office.js API // then manipulate with OpenXmlSdkTs const doc = await WmlPackage.open(flatOpcString); const mainPart = await doc.mainDocumentPart(); // ... modify the document ... const modifiedFlatOpc = await doc.saveToFlatOpcAsync(); // Set the modified Flat OPC back via the Office.js API ``` -------------------------------- ### Retrieve Parts by Content Type Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.SmlPackage.html Use the ContentType constants to filter parts within the package. ```typescript import { ContentType } from "openxmlsdkts"; const themeParts = await pkg.getPartsByContentType(ContentType.theme); ``` -------------------------------- ### Iterate over package relationships Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlRelationship.html Retrieves and logs the ID, type, and full target path for all relationships associated with a part. ```typescript const rels = await mainPart.getRelationships(); for (const rel of rels) { console.log(`${rel.getId()} [${rel.getType()}] -> ${rel.getTargetFullName()}`); } ``` -------------------------------- ### XDocument.load Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XDocument.html Loads an XML file synchronously and parses it into an XDocument. ```APIDOC ## XDocument.load(filePath: string) ### Description Loads an XML file synchronously and parses it into an XDocument. ### Parameters - **filePath** (string) - Required - Path to the XML file. ### Returns - **XDocument** - The parsed document. ``` -------------------------------- ### saveToBase64Async Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.SmlPackage.html Saves the package as a Base64-encoded string. ```APIDOC ## saveToBase64Async() ### Description Saves the package as a Base64-encoded string, useful for embedding in JSON payloads or data URIs. ### Returns - **Promise** - A promise resolving to the Base64 string. ``` -------------------------------- ### Save package as binary Blob Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.SmlPackage.html Use this method to save the package as a binary Blob. In Node.js environments, convert the result to a Buffer for file system operations. ```typescript const blob = await pkg.saveToBlobAsync(); // In Node.js, convert to Buffer for file I/O: const buffer = Buffer.from(await blob.arrayBuffer()); fs.writeFileSync("output.docx", buffer); ``` -------------------------------- ### Navigate Parts and Relationships Source: https://ericwhitedev.github.io/OpenXmlSdkTs/index.html Uses ContentType and RelationshipType static lookups to navigate document parts and query relationships. ```typescript import { ContentType, RelationshipType } from "openxmlsdkts"; // Navigate parts by relationship type const stylePart = await mainPart!.getPartByRelationshipType(RelationshipType.styles); const themePart = await mainPart!.getPartByRelationshipType(RelationshipType.theme); const imageParts = await mainPart!.getPartsByRelationshipType(RelationshipType.image); // Query relationships const rels = await mainPart!.getRelationships(); for (const rel of rels) { console.log(rel.getType()); // e.g. the styles relationship URI console.log(rel.getTarget()); // e.g. "styles.xml" } ``` -------------------------------- ### Package Classes Source: https://ericwhitedev.github.io/OpenXmlSdkTs/index.html Classes for handling Word, Excel, and PowerPoint document packages. ```APIDOC ## Package Classes ### WmlPackage - Description: Handles Word documents. - Methods: `open()`, `mainDocumentPart()`, `contentParts()`, `saveToBase64Async()`, `saveToBlobAsync()`, `saveToFlatOpcAsync()` ### SmlPackage - Description: Handles Excel spreadsheets. - Methods: `open()`, `workbookPart()`, `saveToBase64Async()`, `saveToBlobAsync()`, `saveToFlatOpcAsync()` ### PmlPackage - Description: Handles PowerPoint presentations. - Methods: `open()`, `presentationPart()`, `saveToBase64Async()`, `saveToBlobAsync()`, `saveToFlatOpcAsync()` ``` -------------------------------- ### toString(): string Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XProcessingInstruction.html Returns the XML serialization of this processing instruction. ```APIDOC ## toString(): string ### Description Returns the XML serialization of this processing instruction. ### Returns - **string** - The serialized PI string, e.g. . ``` -------------------------------- ### Open and Save Flat OPC Documents Source: https://ericwhitedev.github.io/OpenXmlSdkTs/index.html Uses single-file XML strings, required for Office JavaScript/TypeScript add-in development. ```typescript // Open const flatOpcXml = fs.readFileSync("report.xml", "utf-8"); const doc = await WmlPackage.open(flatOpcXml); // Save const flatOpc: string = await doc.saveToFlatOpcAsync(); ``` -------------------------------- ### OpenXmlPackage.addPart Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlPackage.html Adds a new part to the Open XML package. ```APIDOC ## addPart(uri: string, contentType: string, partType: PartType, data: unknown): OpenXmlPart ### Description Adds a new part to the package. Throws an error if a part with the given URI already exists. ### Parameters - **uri** (string) - Required - The part URI (e.g., "/word/comments.xml"). - **contentType** (string) - Required - The MIME content type. - **partType** (PartType) - Required - The part data type: "xml", "binary", or "base64". - **data** (unknown) - Required - The part content. ### Returns - **OpenXmlPart** - The newly created OpenXmlPart. ``` -------------------------------- ### Create and Serialize XDeclaration Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XDeclaration.html Instantiate a new XML declaration and convert it to its string representation. ```typescript const decl = new XDeclaration('1.0', 'UTF-8', 'yes'); decl.toString(); // "" ``` -------------------------------- ### new XDeclaration(version, encoding, standalone) Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XDeclaration.html Creates a new XDeclaration instance with specified XML declaration attributes. ```APIDOC ## constructor(version: string, encoding: string, standalone: string) ### Description Creates a new XDeclaration instance from explicit values. ### Parameters - **version** (string) - The XML version string. - **encoding** (string) - The encoding name (pass "" to omit). - **standalone** (string) - The standalone value (pass "" to omit). ``` -------------------------------- ### PKGREL Static Properties Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.PKGREL.html Static properties providing XName and XNamespace constants for Package Relationships. ```APIDOC ## Static Properties ### namespace - **Type**: XNamespace - **Description**: The namespace URI for package relationships. ### Relationship - **Type**: XName - **Description**: The XName constant for a relationship element. ### Relationships - **Type**: XName - **Description**: The XName constant for the relationships root element. ``` -------------------------------- ### getTarget() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.OpenXmlRelationship.html Returns the raw target URI. ```APIDOC ### getTarget() Returns the raw target URI (may be relative). Use getTargetFullName for a resolved URI. #### Returns - **string** - The raw target URI. ``` -------------------------------- ### Auto-Detection of Input Formats Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Opening_and_Saving_Documents.html The open() method automatically identifies the input format regardless of whether it is a Blob, Flat OPC string, or Base64 string. ```typescript // All three work with the same open() method const doc1 = await WmlPackage.open(blob); // Blob detected const doc2 = await WmlPackage.open(flatOpc); // Flat OPC XML detected const doc3 = await WmlPackage.open(base64Str); // Base64 detected ``` -------------------------------- ### Access SpreadsheetML elements using S Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.S.html Demonstrates how to import the S class and use its constants to navigate and extract data from an Excel worksheet structure. ```typescript import { S, NoNamespace } from "openxmlsdkts"; const sheetData = xDoc.root!.element(S.sheetData); const rows = sheetData!.elements(S.row); for (const row of rows) { for (const cell of row.elements(S.c)) { const ref = cell.attribute(NoNamespace.r)?.value; const val = cell.element(S.v)?.value; } } ``` -------------------------------- ### Navigate Excel Workbook Parts Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Navigating_Parts.html Access spreadsheet-specific parts like worksheets, shared strings, and styles in an SmlPackage. ```typescript const workbook = await SmlPackage.open(blob); // Workbook part (the root of spreadsheet content) const wbPart = await workbook.workbookPart(); // Individual worksheets const sheets = await workbook.worksheetParts(); // Shared strings (text values referenced by cells) const sst = await workbook.sharedStringTablePart(); // Styles const styles = await workbook.workbookStylesPart(); ``` -------------------------------- ### loadAsync Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XDocument.html Loads an XML file asynchronously and parses it into an XDocument. ```APIDOC ## loadAsync(filePath: string) ### Description Loads an XML file asynchronously and parses it into an XDocument. ### Parameters - **filePath** (string) - Required - Path to the XML file. ### Returns - **Promise** - A promise that resolves to the parsed document. ``` -------------------------------- ### Constructing XML Elements Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Working_with_XML.html Use the XElement constructor to define elements, attributes, and nested content. ```typescript import { XElement, XAttribute } from "ltxmlts"; import { W, NoNamespace } from "openxmlsdkts"; // Create a simple paragraph with text const paragraph = new XElement(W.p, new XElement(W.r, new XElement(W.rPr, new XElement(W.b) // bold ), new XElement(W.t, "Bold text here") ) ); // Create an element with attributes const bookmark = new XElement(W.bookmarkStart, new XAttribute(NoNamespace.id, "0"), new XAttribute(NoNamespace.name, "MyBookmark") ); ``` -------------------------------- ### Navigate Parts by Relationship or Content Type Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Navigating_Parts.html Use generic accessors to find parts when typed accessors are insufficient. ```typescript // Get parts by relationship type const parts = await mainPart!.getPartsByRelationshipType( RelationshipType.Image ); // Get a single part by relationship type const part = await mainPart!.getPartByRelationshipType( RelationshipType.StyleDefinitions ); // Get parts by content type const xmlParts = await mainPart!.getPartsByContentType( ContentType.WmlStyles ); ``` -------------------------------- ### XNamespace.getName Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XNamespace.html Creates an XName within the current namespace. ```APIDOC ## getName(localName: string) ### Description Returns an XName in this namespace with the given local name. ### Parameters - **localName** (string) - Required - The local part of the qualified name. ### Returns - **XName** - The cached XName instance. ``` -------------------------------- ### equals(other: XProcessingInstruction): boolean Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XProcessingInstruction.html Compares this processing instruction to another by target and data. ```APIDOC ## equals(other: XProcessingInstruction): boolean ### Description Compares this processing instruction to another by target and data. ### Parameters - **other** (XProcessingInstruction) - Required - The processing instruction to compare against. ### Returns - **boolean** - true if both target and data are equal. ``` -------------------------------- ### Chaining XML Queries Source: https://ericwhitedev.github.io/OpenXmlSdkTs/documents/Working_with_XML.html Shows how to chain LINQ to XML methods to traverse deep document structures and extract specific values. ```typescript // Get all text content from a document const texts = xDoc.root! .element(W.body)! .elements(W.p) .flatMap(p => p.elements(W.r)) .flatMap(r => r.elements(W.t)) .map(t => t.value); ``` -------------------------------- ### glossaryDocumentPart() Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.WmlPart.html Retrieves the glossary document part (Quick Parts / AutoText) from the document. ```APIDOC ## glossaryDocumentPart() ### Description Returns the glossary document part (Quick Parts / AutoText), or undefined if not present. ### Returns Promise ``` -------------------------------- ### Use addAfterSelf method Source: https://ericwhitedev.github.io/OpenXmlSdkTs/classes/index.XProcessingInstruction.html Inserts a new node after the current node in the XML tree. ```javascript const parent = new XElement('p', new XElement('a'), new XElement('c')); const a = parent.elements()[0]; a.addAfterSelf(new XElement('b')); // parent now contains , , ```