### Configure Custom Delimiters Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Customize the start and end delimiters (defaulting to '{' and '}') to prevent conflicts with your template's content. This example shows how to use '<<' and '>>', and also demonstrates ERB-style delimiters. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); // Template content example using custom delimiters: // "Hello <>, your order <> is ready." const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, delimiters: { start: "<<", end: ">>", }, }); doc.render({ name: "John", orderId: "ORD-12345", }); fs.writeFileSync("output.docx", doc.toBuffer()); // Alternative: Use different delimiters like ERB-style const doc2 = new Docxtemplater(new PizZip(content), { delimiters: { start: "<%=", end: "%", }, }); ``` -------------------------------- ### Customize Null Value Handling Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt This example shows how to use the `nullGetter` option to define custom behavior for undefined or null placeholders during document rendering. It provides specific handling for raw XML tags and a fallback for missing values. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, nullGetter: (part, scopeManager) => { // Return custom value for undefined placeholders if (part.module === "rawxml") { return ""; // Return empty string for raw XML tags } // Return placeholder text for missing values return `[Missing: ${part.value}]`; }, }); doc.render({ name: "John", // 'email' is not provided - will show "[Missing: email]" }); fs.writeFileSync("output.docx", doc.toBuffer()); ``` -------------------------------- ### Basic Document Generation with Docxtemplater Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Load a docx template, replace placeholders with data, and generate an output document. Ensure template.docx exists in the same directory. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); const path = require("path"); // Load the template file as binary content const content = fs.readFileSync(path.resolve(__dirname, "template.docx"), "binary"); // Create a PizZip instance with the template content const zip = new PizZip(content); // Create a new Docxtemplater instance with options const doc = new Docxtemplater(zip, { paragraphLoop: true, // Better loop handling linebreaks: true, // Support \n line breaks in data }); // Render the document by replacing placeholders doc.render({ first_name: "John", last_name: "Doe", phone: "0652455478", description: "New Website Project", }); // Generate the output as a Node.js Buffer const buf = doc.toBuffer(); // Write the output to a file fs.writeFileSync(path.resolve(__dirname, "output.docx"), buf); ``` -------------------------------- ### Text Templating with TxtTemplater Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Shows how to use TxtTemplater for generating plain text content with the same template syntax as Docxtemplater. This is suitable for scenarios where a full docx file is not required. ```javascript const TxtTemplater = require("docxtemplater/js/text.js"); // Simple text templating const doc = new TxtTemplater("Hello {user}, welcome to {company}!"); const result = doc.render({ user: "John", company: "Acme Corp", }); console.log(result); // Output: "Hello John, welcome to Acme Corp!" // With loops const docWithLoop = new TxtTemplater(` Attendees: {#attendees} - {name} ({role}) {/attendees} `); const output = docWithLoop.render({ attendees: [ { name: "Alice", role: "Developer" }, { name: "Bob", role: "Designer" }, { name: "Charlie", role: "Manager" }, ], }); console.log(output); // Output: // "Attendees: // - Alice (Developer) // - Bob (Designer) // - Charlie (Manager)" ``` -------------------------------- ### Raw XML Insertion for Advanced Formatting Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Demonstrates how to insert pre-formatted XML content directly into a document using the `{@rawXml}` tag. This is useful for applying complex formatting like bold and italic text programmatically. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); // Template content example: // "{@formattedContent}" const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, }); // Insert formatted XML with bold and italic text const rawXml = ` Bold Text and Italic Text `; doc.render({ formattedContent: rawXml, }); fs.writeFileSync("output.docx", doc.toBuffer()); ``` -------------------------------- ### Export Document in Various Formats Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Generate the output document in multiple formats suitable for different environments. This includes Node.js Buffer, Base64 string, Uint8Array, and ArrayBuffer. Browser-specific Blob export is also mentioned. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, }); doc.render({ name: "John Doe" }); // Export as Node.js Buffer (best for server-side file operations) const buffer = doc.toBuffer(); fs.writeFileSync("output.docx", buffer); // Export as Base64 string (useful for email attachments, API responses) const base64 = doc.toBase64(); console.log("Base64 length:", base64.length); // Export as Uint8Array (useful for web workers, streaming) const uint8Array = doc.toUint8Array(); console.log("Uint8Array length:", uint8Array.length); // Export as ArrayBuffer (useful for low-level operations) const arrayBuffer = doc.toArrayBuffer(); console.log("ArrayBuffer byte length:", arrayBuffer.byteLength); // Export as Blob (browser only - useful for downloads) // const blob = doc.toBlob(); // Custom compression options const customBuffer = doc.toBuffer({ compression: "DEFLATE", compressionOptions: { level: 9 }, // Maximum compression }); ``` -------------------------------- ### Loop Tags for Iterating Over Arrays in Docxtemplater Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Use {#array}...{/array} syntax to repeat template sections for each item in an array. Ensure template.docx contains the loop structure. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); // Template content example: // "Users: // {#users} // - {name} ({email}) // {/users}" const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, }); doc.render({ users: [ { name: "Alice", email: "alice@example.com" }, { name: "Bob", email: "bob@example.com" }, { name: "Charlie", email: "charlie@example.com" }, ], }); // Output will contain: // "Users: // - Alice (alice@example.com) // - Bob (bob@example.com) // - Charlie (charlie@example.com)" fs.writeFileSync("output.docx", doc.toBuffer()); ``` -------------------------------- ### Asynchronous Rendering with Promises Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Utilizes the `renderAsync` method for handling data fetched from asynchronous sources, such as APIs or databases. This method returns a Promise, allowing for seamless integration with async/await patterns. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); // Simulate async data fetching async function fetchUserData(userId) { return new Promise((resolve) => { setTimeout(() => { resolve({ name: "John Doe", email: "john@example.com", orders: [ { id: 1, product: "Widget", price: 29.99 }, { id: 2, product: "Gadget", price: 49.99 }, ], }); }, 100); }); } async function generateDocument() { const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, }); // Use renderAsync for Promise-based data await doc.renderAsync({ user: fetchUserData("user123"), generatedAt: new Date().toISOString(), }); fs.writeFileSync("output.docx", doc.toBuffer()); console.log("Document generated successfully!"); } generateDocument().catch(console.error); ``` -------------------------------- ### Discover Tags with Inspect Module Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Use the InspectModule to find all tags in a template before rendering. This is useful for validation and generating UI elements. Ensure the inspectModule is included in the Docxtemplater options. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const inspectModule = require("docxtemplater/js/inspect-module.js"); const fs = require("fs"); const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); const iModule = inspectModule(); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, modules: [iModule], }); // Get all tags from the document const tags = iModule.getAllTags(); console.log("Tags found in template:", JSON.stringify(tags, null, 2)); // Output example: // { // "name": {}, // "users": { // "email": {}, // "address": { // "city": {}, // "country": {} // } // } // } // Get structured tag information with positions and types const structuredTags = iModule.getAllStructuredTags(); console.log("Structured tags:", structuredTags.length, "placeholders found"); // Get list of templated files in the document const templatedFiles = iModule.getTemplatedFiles(); console.log("Templated files:", templatedFiles); // Output: ["word/document.xml", "word/header1.xml", "word/footer1.xml"] ``` -------------------------------- ### Custom Angular Expression Parser with Filters Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Demonstrates how to extend Docxtemplater with a custom expression parser that supports Angular-style syntax, including custom filters like 'uppercase' and 'filter'. Ensure the 'docxtemplater/expressions.js' module is imported. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const expressionParser = require("docxtemplater/expressions.js"); const fs = require("fs"); // Template content example: // "Hello {user.name | uppercase}!\n // {#users | filter:active} // - {name}: {age > 18 ? 'Adult' : 'Minor'} // {/}" const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); // Add custom filters expressionParser.filters.uppercase = (input) => { if (typeof input === "string") { return input.toUpperCase(); } return input; }; expressionParser.filters.filter = (input, ...args) => { if (!Array.isArray(input)) return input; return input.filter(item => item[args[0]]); }; const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, parser: expressionParser, }); doc.render({ user: { name: "john" }, users: [ { name: "Alice", age: 25, active: true }, { name: "Bob", age: 17, active: false }, { name: "Charlie", age: 30, active: true }, ], }); // Output: "Hello JOHN!\n // - Alice: Adult // - Charlie: Adult" fs.writeFileSync("output.docx", doc.toBuffer()); ``` -------------------------------- ### Handle Errors in Document Generation Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt This snippet demonstrates how to catch and log detailed error information, including multi-errors, during document rendering. It disables automatic console logging for errors. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); function generateDocument(templatePath, data) { try { const content = fs.readFileSync(templatePath, "binary"); const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, errorLogging: false, // Disable automatic console logging }); doc.render(data); return doc.toBuffer(); } catch (error) { // Handle multi-errors (multiple template issues) if (error.properties && error.properties.errors) { const errorMessages = error.properties.errors.map((e) => { return { message: e.message, id: e.properties?.id, tag: e.properties?.xtag, explanation: e.properties?.explanation, }; }); console.error("Template errors:", JSON.stringify(errorMessages, null, 2)); } else { console.error("Error:", error.message); } throw error; } } // Example with intentional error (unclosed tag) // Template: "Hello {name" (missing closing brace) try { generateDocument("broken-template.docx", { name: "John" }); } catch (error) { // Error will contain details about the unclosed tag console.log("Document generation failed"); } ``` -------------------------------- ### Conditional Tags in Docxtemplater Source: https://context7.com/open-xml-templating/docxtemplater/llms.txt Use {#condition}...{/condition} for truthy and {^condition}...{/condition} for falsy values to conditionally show or hide content. Template content must include these tags. ```javascript const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); const fs = require("fs"); // Template content example: // "{#isPremium}Thank you for being a Premium member!{/isPremium} // {^isPremium}Upgrade to Premium for more features.{/isPremium}" const content = fs.readFileSync("template.docx", "binary"); const zip = new PizZip(content); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, }); // Premium user example doc.render({ isPremium: true, userName: "John", }); // Output: "Thank you for being a Premium member!" // Non-premium user example const doc2 = new Docxtemplater(new PizZip(content), { paragraphLoop: true, linebreaks: true, }); doc2.render({ isPremium: false, userName: "Jane", }); // Output: "Upgrade to Premium for more features." fs.writeFileSync("output.docx", doc.toBuffer()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.