### ImageFormatter Example with Model Binding Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Complete example demonstrating how to register the ImageFormatter, load image data into a model, bind the model to the template, and save the output document. ```csharp var template = DocxTemplate.Open("document.docx"); template.RegisterFormatter(new ImageFormatter()); byte[] logoData = File.ReadAllBytes("logo.png"); byte[] photoData = File.ReadAllBytes("photo.jpg"); template.BindModel("data", new { CompanyLogo = logoData, ProfilePhoto = photoData }); // In template: // {{data.CompanyLogo}:img(w:50mm)} // {{data.ProfilePhoto}:img(keepratio)} template.Save("output.docx"); ``` -------------------------------- ### Example: Inspecting Collection Item Schema Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-TemplateSchema.md Demonstrates how to get the schema for a collection's items and iterate through its properties. Useful for understanding the structure of data expected in a collection. ```csharp var schema = template.GetTemplateSchema(); // Template: {{#Items}}{{.Name}} - {{.Price}}{{/Items}} var itemsNode = schema.Roots["items"]; Console.WriteLine(itemsNode.Kind); // TemplateNodeKind.Collection var itemSchema = itemsNode.ItemSchema; Console.WriteLine(itemSchema.Kind); // TemplateNodeKind.Object // Item has two properties: "Name" and "Price" foreach (var prop in itemSchema.Properties.Keys) { Console.WriteLine(prop); // "Name", "Price" } ``` -------------------------------- ### Custom ListLevelConfiguration Example Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ProcessSettings.md Example of defining a custom list level with specific text, font, numbering format, and indent. ```csharp // Define a custom level: "A.", "B.", "C.", ... with Arial font and 720 twips indent var customLevel = new ListLevelConfiguration( "%1.", "Arial", NumberFormatValues.UpperLetter, 720); ``` -------------------------------- ### Install DocxTemplater.Markdown Package Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/README.md Installs the DocxTemplater.Markdown extension package via NuGet. This package enables Markdown to OpenXML conversion. ```powershell Install-Package DocxTemplater.Markdown ``` -------------------------------- ### ProductModel Usage Example with German Display Names Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Models.md A usage example for TemplateModelWithDisplayNames, showing a ProductModel with German display names for properties. Demonstrates how templates can use either the original property names or their localized display names. ```csharp public class ProductModel : TemplateModelWithDisplayNames { [DisplayName("Produktname")] public string Name { get; set; } [DisplayName("Verkaufspreis")] public decimal Price { get; set; } } var product = new ProductModel { Name = "Widget", Price = 99.99m }; var template = DocxTemplate.Open("product.docx"); // Template can use German or English names: // {{product.Produktname}} -> "Widget" // {{product.Verkaufspreis}} -> 99.99 // {{product.Name}} -> "Widget" (fallback) // {{product.Price}} -> 99.99 (fallback) template.BindModel("product", product); template.Save("output.docx"); ``` -------------------------------- ### Full Markdown Conversion Example Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Demonstrates registering the MarkdownFormatter and binding Markdown content to a template. The example includes various Markdown elements like headings, paragraphs, lists, and tables. ```csharp var template = DocxTemplate.Open("report.docx"); template.RegisterFormatter(new MarkdownFormatter()); string markdownContent = @" # Section 1 This is a paragraph with **bold** and *italic* text. ## Subsection - Item 1 - Item 2 - Nested item | Column A | Column B | |----------|----------| | Value 1 | Value 2 | | Value 3 | Value 4 | "; template.BindModel("report", new { Content = markdownContent }); // In template: // {{report.Content}:md} template.Save("output.docx"); ``` -------------------------------- ### Custom Image Formatter Example Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Example implementation of an IFormatter for handling image data. It checks for 'IMG' or 'IMAGE' prefixes and expects a byte array. ```csharp public class ImageFormatter : IFormatter { public bool CanHandle(Type type, string prefix) { // Handles {{imageData}:img} var prefixUpper = prefix?.ToUpper(); return (prefixUpper == "IMG" || prefixUpper == "IMAGE") && type == typeof(byte[]); } } ``` -------------------------------- ### Complete Chart Data Binding Example Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ChartData.md A full example demonstrating the creation of multi-series chart data and its binding to a Word template for report generation. ```csharp using DocxTemplater; using DocxTemplater.Extensions.Charts; // Create multi-series chart data var sales2023 = new[] { 50000, 55000, 60000, 65000, 70000, 75000 }; var sales2024 = new[] { 60000, 65000, 70000, 75000, 80000, 85000 }; var chartData = new ChartData { ChartTitle = "Sales Trend Analysis", Categories = new[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun" }, Series = new List { new() { Name = "2023", Values = sales2023.Select(x => (double)x) }, new() { Name = "2024", Values = sales2024.Select(x => (double)x) } } }; // Bind to model var template = DocxTemplate.Open("annual_report.docx"); template.BindModel("report", new { Chart = chartData }); template.Save("annual_report_2024.docx"); ``` -------------------------------- ### Custom Markdown Formatter Example Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Example implementation of an IFormatter for handling markdown text. It checks for the 'MD' prefix and expects a string. ```csharp public class MarkdownFormatter : IFormatter { public bool CanHandle(Type type, string prefix) { // Handles {{markdownText}:md} return prefix?.ToUpper() == "MD" && type == typeof(string); } } ``` -------------------------------- ### Install DocxTemplater.Images Package Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/README.md Installs the DocxTemplater.Images extension package via NuGet. This package provides image embedding capabilities. ```powershell Install-Package DocxTemplater.Images ``` -------------------------------- ### Implement IImageServiceProvider for Image Formatting Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Extensions.md Provides an example implementation of `IImageServiceProvider` for use with image formatting. The `CreateImageService` method is called internally by Docxtemplater. ```csharp public class ImageFormatter : IFormatter, IImageServiceProvider { public IImageService CreateImageService() { return new ImageService(); } } // Usage var template = DocxTemplate.Open("template.docx"); var formatter = new ImageFormatter(); template.RegisterFormatter(formatter); // CreateImageService() is called internally to configure image handling ``` -------------------------------- ### Configure Runtime Process Settings Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Provides an example of creating a configured DocxTemplate based on an environment name, adjusting culture, binding error handling, and line break behavior. ```csharp public static DocxTemplate CreateConfiguredTemplate(string templatePath, string environmentName) { var settings = environmentName switch { "Development" => new ProcessSettings { Culture = CultureInfo.CurrentUICulture, BindingErrorHandling = BindingErrorHandling.ThrowException, IgnoreLineBreaksAroundTags = true }, "Production" => new ProcessSettings { Culture = new CultureInfo("en-US"), BindingErrorHandling = BindingErrorHandling.HighlightErrorsInDocument, IgnoreLineBreaksAroundTags = false }, _ => ProcessSettings.Default }; var template = DocxTemplate.Open(templatePath, settings); template.RegisterFormatter(new ImageFormatter()); template.RegisterFormatter(new MarkdownFormatter()); return template; } ``` -------------------------------- ### Install DocxTemplater via NuGet Source: https://github.com/amberg/docxtemplater/blob/main/README.md Installs the DocxTemplater package using the NuGet Package Manager Console. This is the primary method for adding the library to your project. ```powershell PM> Install-Package DocxTemplater ``` -------------------------------- ### Get Default ProcessSettings Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ProcessSettings.md Retrieves a new ProcessSettings instance with all default values. Use this as a starting point for custom configurations. ```csharp var template = new DocxTemplate(stream, ProcessSettings.Default); ``` -------------------------------- ### Model Binding Example Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ChartData.md Demonstrates how to prepare ChartData and bind it to a template model for chart rendering. ```APIDOC ## Usage and Setup ### Model Binding ```csharp // 1. Prepare chart data var chartData = new ChartData { ChartTitle = "Monthly Sales", Categories = new[] { "Jan", "Feb", "Mar", "Apr" }, Series = new List { new() { Name = "Product A", Values = new[] { 100.0, 120.0, 110.0, 140.0 } }, new() { Name = "Product B", Values = new[] { 80.0, 90.0, 100.0, 110.0 } } } }; // 2. Open template and bind var template = DocxTemplate.Open("report.docx"); // Template property name MUST match chart title template.BindModel("report", new { SalesChart = chartData }); // 3. Process and save template.Save("output.docx"); ``` ### Complete Example ```csharp using DocxTemplater; using DocxTemplater.Extensions.Charts; // Create multi-series chart data var sales2023 = new[] { 50000, 55000, 60000, 65000, 70000, 75000 }; var sales2024 = new[] { 60000, 65000, 70000, 75000, 80000, 85000 }; var chartData = new ChartData { ChartTitle = "Sales Trend Analysis", Categories = new[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun" }, Series = new List { new() { Name = "2023", Values = sales2023.Select(x => (double)x) }, new() { Name = "2024", Values = sales2024.Select(x => (double)x) } } }; // Bind to model var template = DocxTemplate.Open("annual_report.docx"); template.BindModel("report", new { Chart = chartData }); template.Save("annual_report_2024.docx"); ``` ``` -------------------------------- ### Binding Model Data to DocxTemplater Source: https://github.com/amberg/docxtemplater/blob/main/README.md C# example showing how to open a template, define a model with a collection, bind the model to the template, and save the generated document. ```csharp var template = DocxTemplate.Open("template.docx"); var model = new { Items = new[] { new { Name = "John", Position = "Developer" }, new { Name = "Alice", Position = "CEO" } } }; template.BindModel("ds", model); template.Save("generated.docx"); ``` -------------------------------- ### Example Error Handling Strategy with BindingErrorHandling Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/errors.md Demonstrates how to use the BindingErrorHandling setting to control behavior during template processing. This example shows attempting to process with ThrowException and then retrying with SkipBindingAndRemoveContent. ```csharp var settings = new ProcessSettings { BindingErrorHandling = BindingErrorHandling.ThrowException }; var template = new DocxTemplate(stream, settings); try { template.BindModel("customer", customerData); template.Save("output.docx"); } catch (OpenXmlTemplateException ex) { // Log error logger.Error($"Template processing failed: {ex.Message}", ex); // Optionally retry with lenient settings var lenientSettings = new ProcessSettings { BindingErrorHandling = BindingErrorHandling.SkipBindingAndRemoveContent }; var template2 = new DocxTemplate(stream, lenientSettings); template2.BindModel("customer", customerData); template2.Save("output_with_errors.docx"); } ``` -------------------------------- ### PersonModel Example with DisplayName Attributes Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Models.md An example demonstrating how to use the DisplayName attribute to provide aliases for properties in a model inheriting from TemplateModelWithDisplayNames. Supports both original and aliased names in templates. ```csharp using System.ComponentModel; using DocxTemplater.Model; public class PersonModel : TemplateModelWithDisplayNames { [DisplayName("Vorname")] public string FirstName { get; set; } [DisplayName("Nachname")] public string LastName { get; set; } public string Email { get; set; } } // Template can use any of these: // {{person.FirstName}} -> FirstName value // {{person.Vorname}} -> FirstName value (display name) // {{person.LastName}} -> LastName value // {{person.Nachname}} -> LastName value (display name) // {{person.Email}} -> Email value ``` -------------------------------- ### Examples of Invalid Placeholder Syntax Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/errors.md Illustrates malformed placeholder syntax that DocxTemplater cannot parse. Ensure placeholders have correct opening and closing braces and valid arguments. ```csharp // Invalid: {{customer.name}} - missing opening brace {{customer.name}}} - extra closing brace {{customer.name:formatter(}} - unclosed argument ``` -------------------------------- ### Formatter with Expression: Currency Source: https://github.com/amberg/docxtemplater/blob/main/README.md Apply standard formatters to the results of C# expressions. This example calculates a gross price and formats it as currency. ```csharp {{(ds.Price * 1.19)}:f(c)} ``` -------------------------------- ### Register Image Formatter Source: https://github.com/amberg/docxtemplater/blob/main/README.md To use the Image Formatter, the 'DocxTemplater.Images' NuGet package must be installed and the formatter registered with the DocxTemplate instance. ```csharp var docTemplate = new DocxTemplate(fileStream); docTemplate.RegisterFormatter(new ImageFormatter()); ``` -------------------------------- ### Image Formatter ApplyFormat Implementation Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Example implementation of ApplyFormat for the ImageFormatter. It retrieves image data, creates a drawing element, and inserts it into the document, then removes the original text element. ```csharp public void ApplyFormat( ITemplateProcessingContext templateContext, FormatterContext formatterContext, Text target) { if (formatterContext.Value is not byte[] imageBytes) return; var imageInfo = templateContext.ImageService.GetImage( target.GetRoot(), imageBytes, out var info); // Create drawing element and insert it var drawing = new Drawing(/* ... */); target.InsertAfterSelf(drawing); target.Remove(); } ``` -------------------------------- ### Example of Unmatched Block Closing Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/errors.md Shows template blocks where opening tags do not have corresponding closing tags with the correct names. Ensure all `{{#tag}}` have a matching `{{/tag}}`. ```plaintext {{#Items}} {{.Name}} {{/WrongName}} // ERROR: should be {{/Items}} {{#if condition}} Content // Missing: {{/if}} ``` -------------------------------- ### Handle Invalid Image Formatter Arguments Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/errors.md This section shows examples of valid and invalid arguments for image formatting, such as size and rotation. Invalid arguments can trigger exceptions. ```text w:100mm // width in mm h:50px // height in pixels r:90 // rotation in degrees w:100cm,h:50cm,r:45 // combined ``` ```text w:100abc // invalid unit h:fifty // non-numeric r:400 // invalid rotation (mod 360) ``` -------------------------------- ### Template Title Matching Example Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ChartData.md Demonstrates how the chart title in the template must match the model property name (case-insensitive) for correct data binding. ```csharp // Model var model = new { MyChart = chartData }; // Template MUST have chart with title "MyChart" // (or "mychart", "MYCHART", etc. - case insensitive) ``` -------------------------------- ### DynamicModel Implementation of ITemplateModel Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Models.md An example implementation of the ITemplateModel interface using a Dictionary to store and retrieve property values. Useful for dynamic or runtime-defined models. ```csharp public class DynamicModel : ITemplateModel { private readonly Dictionary _data = new(); public bool TryGetPropertyValue(string propertyName, out ValueWithMetadata value) { if (_data.TryGetValue(propertyName, out var val)) { value = new ValueWithMetadata(val); return true; } value = new ValueWithMetadata(null); return false; } public void Set(string key, object value) => _data[key] = value; } // Usage var model = new DynamicModel(); model.Set("Name", "John"); model.Set("Email", "john@example.com"); template.BindModel("person", model); // {{person.Name}} -> "John" // {{person.Email}} -> "john@example.com" // {{person.Phone}} -> error or empty (not in _data) ``` -------------------------------- ### Conditional Rendering in DocxTemplater Source: https://github.com/amberg/docxtemplater/blob/main/README.md Shows how to use conditional blocks to show or hide content based on a specified condition. Includes an example of an 'else' block. ```DocxTemplater Syntax {?{Item.Value >= 0}}Only visible if value is >= 0 {{:}}Otherwise this text is shown{{/}} ``` -------------------------------- ### Implement ITemplateProcessorExtension for PreProcess Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Extensions.md Implement the PreProcess method to modify document structure or remove elements before placeholder detection. This example removes spell-check squiggles. ```csharp public class RemoveProofErrorsExtension : ITemplateProcessorExtension { public void PreProcess(OpenXmlCompositeElement content) { // Remove spell-check squiggles foreach (var proofError in content.Descendants().ToList()) { proofError.Remove(); } } } ``` -------------------------------- ### Looping through Collections in a Table Source: https://github.com/amberg/docxtemplater/blob/main/README.md Demonstrates how to use collection looping syntax within a table row to render data for each item. The start and end tags must be placed within the table row. ```DocxTemplater Syntax {{#Items}} This text {{Items.Name}} is rendered for each element in the items collection {{/Items}} ``` ```DocxTemplater Syntax | Name | Position | |--------------|-----------| | **{{#Items}}** {{Items.Name}} | {{Items.Position}} **{{/Items}}** | ``` -------------------------------- ### Allowed Expression Evaluation Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Illustrates examples of allowed expression evaluations within DocxTemplater, including string manipulation, arithmetic, conditional expressions, and null-coalescing operators. ```csharp // Allowed {{(customer.Name.ToUpper())}} {{(customer.Price * 1.19)}} {{(items.Count > 0 ? "Yes" : "No")}} {{(customer.Phone ?? "N/A")}} ``` -------------------------------- ### Basic DocxTemplate Workflow Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Demonstrates the fundamental steps to open a template, register formatters, bind data, and save the generated document. ```csharp // 1. Open template var template = DocxTemplate.Open("template.docx"); // 2. Register optional formatters/extensions template.RegisterFormatter(new ImageFormatter()); template.RegisterFormatter(new MarkdownFormatter()); // 3. Bind models template.BindModel("customer", customerObject); template.BindModel("items", itemsList); // 4. Save result template.Save("output.docx"); ``` -------------------------------- ### Basic ProcessSettings Configuration Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Demonstrates using default process settings. This is equivalent to explicitly setting ProcessSettings.Default. ```csharp var template = DocxTemplate.Open("template.docx"); // Equivalent to: var settings = ProcessSettings.Default; var template = new DocxTemplate(stream, settings); ``` -------------------------------- ### Basic Template Usage Source: https://github.com/amberg/docxtemplater/blob/main/README.md Demonstrates how to open a docx template, bind a model, and save the generated document. Use this for simple text replacement in your templates. ```csharp var template = DocxTemplate.Open("template.docx"); // To open the file from a stream use the constructor directly // var template = new DocxTemplate(stream); template.BindModel("ds", new { Title = "Some Text" }); template.Save("generated.docx"); ``` -------------------------------- ### Get Processed Document as Stream Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Use AsStream() as a convenience method to get the processed document as a MemoryStream. This is equivalent to calling Process(). ```csharp public Stream AsStream() ``` ```csharp template.BindModel("ds", data); var stream = template.AsStream(); ``` -------------------------------- ### Create DocxTemplate with Stream and Settings Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Instantiates DocxTemplate using a stream and custom processing settings. Useful for specifying culture or other configurations. ```csharp var settings = new ProcessSettings { Culture = new CultureInfo("de-DE") }; using var fileStream = File.OpenRead("template.docx"); var template = new DocxTemplate(fileStream, settings); ``` -------------------------------- ### Create DocxTemplate with Stream Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Instantiates DocxTemplate using a stream containing the .docx file. Use default processing settings. ```csharp using var fileStream = File.OpenRead("template.docx"); var template = new DocxTemplate(fileStream); ``` -------------------------------- ### Processing with Images and Markdown Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/README.md Demonstrates how to register custom formatters for images and markdown, bind content including image data and markdown text, and save the document. ```csharp var template = DocxTemplate.Open("template.docx"); template.RegisterFormatter(new ImageFormatter()); template.RegisterFormatter(new MarkdownFormatter()); template.BindModel("doc", new { Logo = File.ReadAllBytes("logo.png"), Content = "# Title\n\nMarkdown text..." }); template.Save("output.docx"); ``` -------------------------------- ### ModelPropertyAttribute Usage Example Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/types.md Demonstrates how to apply the ModelPropertyAttribute to a property within a custom model class. The DefaultFormatter is set to 'toupper'. ```csharp public class InvoiceModel : TemplateModelWithDisplayNames { [DisplayName("Rechnungsnummer")] [ModelProperty(DefaultFormatter = "toupper")] public string InvoiceNumber { get; set; } } ``` -------------------------------- ### Get Variable Value with Metadata Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Extensions.md Resolves a variable and returns both its value and associated metadata, including the default formatter if specified. ```csharp ValueWithMetadata GetValueWithMetadata(string variableName) ``` -------------------------------- ### DocxTemplate.Open Static Method Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Opens a DocxTemplate instance from a specified file path, with optional processing settings. ```APIDOC ## DocxTemplate.Open(string pathToTemplate, ProcessSettings settings = null) ### Description Opens a `DocxTemplate` instance from the specified file path. Allows for optional custom processing settings. ### Method `static DocxTemplate Open(string pathToTemplate, ProcessSettings settings = null)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **pathToTemplate** (`string`) - Required - File path to the .docx template - **settings** (`ProcessSettings`) - Optional - Processing settings. Defaults to `ProcessSettings.Default`. ### Return - `DocxTemplate` instance opened from the file. ### Throws - `FileNotFoundException` if the template file does not exist. - `UnauthorizedAccessException` if file access is denied. ### Example ```csharp var template = DocxTemplate.Open("template.docx"); var result = template.Process(); ``` ``` -------------------------------- ### Open DocxTemplate from File Path Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Opens a DocxTemplate directly from a file path. Optionally accepts custom processing settings. The template is ready for processing after opening. ```csharp var template = DocxTemplate.Open("template.docx"); var result = template.Process(); ``` -------------------------------- ### Using Markdown Formatter in Template Source: https://github.com/amberg/docxtemplater/blob/main/README.md Initializes the template, binds a model containing Markdown content, and saves the generated document. The Markdown content is then rendered in the template using the MD prefix. ```C# // Initialize the template var template = DocxTemplate.Open("template.docx"); var markdown = """ | Header 1 | Header 2 | |----------|----------| | Row 1 Col 1 | Row 1 Col 2 | | Row 2 Col 1 | Row 2 Col 2 | """; // Bind model with Markdown content template.BindModel("ds", new { MarkdownContent = markdown }); // Save the generated document template.Save("generated.docx"); ``` ```DocxTemplater Template Syntax {{ds.MarkdownContent}:MD} ``` -------------------------------- ### Get Template Schema Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-TemplateSchema.md Retrieves the static schema of variables referenced by a template. This is useful for understanding the template's data requirements. ```csharp var schema = template.GetTemplateSchema(); ``` -------------------------------- ### Configure Markdown Formatting Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ProcessSettings.md Demonstrates how to register a custom Markdown formatter with specific styling for lists and tables. ```csharp var mdConfig = new MarkDownFormatterConfiguration { UnorderedListStyle = "List Bullet", OrderedListStyle = "List Number", TableStyle = "Light Shading Accent 1" }; var template = DocxTemplate.Open("template.docx"); template.RegisterFormatter(new MarkdownFormatter(mdConfig)); template.BindModel("content", new { MarkdownText = "- Item 1 - Item 2 | A | B | |---|---| | 1 | 2 |" }); template.Save("output.docx"); ``` -------------------------------- ### Define Supported Cultures Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Shows how to instantiate CultureInfo objects for various languages and regions, including system defaults and invariant culture. ```csharp // German var de_DE = new CultureInfo("de-DE"); // French (France) var fr_FR = new CultureInfo("fr-FR"); // Spanish (Spain) var es_ES = new CultureInfo("es-ES"); // Japanese var ja_JP = new CultureInfo("ja-JP"); // Current system culture var current = CultureInfo.CurrentUICulture; // Invariant (English, US-style formatting) var invariant = CultureInfo.InvariantCulture; ``` -------------------------------- ### Model Binding with Prefix Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/README.md Demonstrates how to bind a model to a template using a prefix. This allows you to reference model properties within the template using the specified prefix. ```csharp template.BindModel("prefix", model); // Then use: {{prefix.Property}} ``` -------------------------------- ### Schema Validation Before Processing Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/README.md Illustrates how to retrieve the template's schema, inspect its requirements, and then proceed with binding data and saving the document. ```csharp var template = DocxTemplate.Open("template.docx"); var schema = template.GetTemplateSchema(); // Check if model matches template requirements foreach (var root in schema.Roots.Values) { Console.WriteLine($"Required root: {root.Name}"); } // Now bind and process template.BindModel("customer", data); template.Save("output.docx"); ``` -------------------------------- ### Basic Template Processing Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/README.md This snippet shows the fundamental steps for opening a template, binding data, and saving the processed document. ```csharp var template = DocxTemplate.Open("template.docx"); template.BindModel("data", new { Name = "John", Date = DateTime.Now }); template.Save("output.docx"); ``` -------------------------------- ### Implement ITemplateProcessorExtension for ReplaceVariables Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Extensions.md Implement the ReplaceVariables method to apply custom transformations after variable replacement, such as chart binding. This example shows a placeholder for chart data updates. ```csharp public class ChartProcessor : ITemplateProcessorExtension { public void PreProcess(OpenXmlCompositeElement content) { } public void ReplaceVariables( ITemplateProcessingContext context, OpenXmlElement parentNode, List content) { // Find charts and bind them to model data foreach (var chart in content.OfType()) { // Update chart data based on bound models } } } ``` -------------------------------- ### Template Schema Inspection Options Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Illustrates the two valid ways to interact with template schema inspection: either before processing or by skipping inspection entirely. ```csharp var template = DocxTemplate.Open("template.docx"); // Option 1: Inspect first, then process var schema = template.GetTemplateSchema(); template.BindModel("customer", data); template.Save("output.docx"); ``` ```csharp // Option 2: Process directly (no schema inspection) template.BindModel("customer", data); template.Save("output.docx"); ``` -------------------------------- ### Handle Null Argument Errors Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/errors.md Catch ArgumentNullException when required parameters, such as the document stream, are null. This example demonstrates creating a template with a null stream, which throws an exception. ```csharp Stream nullStream = null; var template = new DocxTemplate(nullStream); // ArgumentNullException ``` ```csharp if (stream == null) throw new ArgumentNullException(nameof(stream)); var template = new DocxTemplate(stream); ``` -------------------------------- ### Handle Duplicate Extension Registration Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/errors.md Prevent 'Extension of type [TypeName] is already registered' errors by ensuring each extension type is registered only once. This example shows the error scenario. ```csharp // Only register each extension type once template.RegisterExtension(new ChartProcessor()); template.RegisterExtension(new ChartProcessor()); // ERROR: duplicate type ``` -------------------------------- ### Return Document as Stream Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Demonstrates how to obtain the generated document as a stream instead of saving it directly to a file, useful for HTTP responses or uploads. ```csharp var template = DocxTemplate.Open("template.docx"); template.BindModel("ds", data); var resultStream = template.AsStream(); // Use resultStream in HTTP response, upload, etc. // Remember to dispose of resultStream when done ``` -------------------------------- ### Examples of Expression Evaluation Errors Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/errors.md Shows C# expressions within placeholders that fail to compile or execute. This includes accessing non-existent properties or performing invalid operations. ```csharp // Invalid expression: {{(customer.UnknownProperty)}} // Property doesn't exist {{(1 / 0)}} // Division by zero {{(customer.Date.DayOfWeek)}} // If Date is null ``` -------------------------------- ### Registering ImageFormatter Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Demonstrates how to register a new ImageFormatter instance with a DocxTemplate. Registering an ImageFormatter also sets up the IImageService internally. ```csharp var template = DocxTemplate.Open("template.docx"); template.RegisterFormatter(new ImageFormatter()); // Also implements IImageServiceProvider, so this sets up image service: template.RegisterFormatter(new ImageFormatter()); // -> Automatically registers the IImageService internally ``` -------------------------------- ### Get Variable Value Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Extensions.md Resolves a variable name to its corresponding value, traversing the property path and scope chain as necessary. Supports qualified names like 'customer.Name'. ```csharp object GetValue(string variableName) ``` -------------------------------- ### Create ChartSeries with Name Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ChartData.md Instantiate a ChartSeries object and set its Name property. This name will appear in the chart's legend. ```csharp var series = new ChartSeries { Name = "Revenue 2024" }; ``` -------------------------------- ### Custom Processing Settings Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Illustrates how to configure custom processing settings, such as culture, error handling, and line break behavior, when creating a new DocxTemplate instance. ```csharp var settings = new ProcessSettings { Culture = new CultureInfo("fr-FR"), BindingErrorHandling = BindingErrorHandling.SkipBindingAndRemoveContent, IgnoreLineBreaksAroundTags = true }; var template = new DocxTemplate(fileStream, settings); template.BindModel("ds", data); template.Save("output.docx"); ``` -------------------------------- ### HtmlFormatter Usage Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Demonstrates the basic syntax for using the built-in HtmlFormatter to insert HTML content as OpenXML within a template. ```text {{htmlContent}:html} ``` -------------------------------- ### Inspect Template Schema Source: https://github.com/amberg/docxtemplater/blob/main/README.md Statically analyze a template without rendering to get its structural schema of variables, collections, and nested objects. Use this to validate a model against template expectations before rendering. ```csharp using var template = DocxTemplate.Open("template.docx"); // Template: "Hello {{customer.Name}}" and "{{#items}}{{items.Price}}{{/items}}" var schema = template.GetTemplateSchema(); // Roots are the top-level models you would pass to BindModel (case-insensitive) foreach (var root in schema.Roots.Values) { Console.WriteLine($"{root.Name}: {root.Kind}"); } schema.Roots["customer"].Properties["Name"].Kind; // Scalar schema.Roots["items"].Kind; // Collection schema.Roots["items"].ItemSchema.Properties["Price"].Kind; // Scalar ``` -------------------------------- ### Resource Cleanup with Explicit Disposal Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Demonstrates explicit resource cleanup for DocxTemplate instances using a try-finally block to ensure Dispose() is called. ```csharp // Or explicit disposal var template = DocxTemplate.Open("template.docx"); try { template.BindModel("data", data); template.Save("output.docx"); } finally { template.Dispose(); } ``` -------------------------------- ### Disallowed Expression Evaluation Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Highlights examples of disallowed expression evaluations in DocxTemplater due to security restrictions, such as assignments, system access, and model modifications. All bound models are read-only within expressions. ```csharp // Not allowed (no assignment) {{(x = 5)}} // ERROR: assignment forbidden {{(File.Delete("..."))}} // ERROR: no system access {{(customer.Score = 100)}} // ERROR: model modification forbidden All bound models are read-only within expressions. ``` -------------------------------- ### Default Property for MarkDownFormatterConfiguration Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ProcessSettings.md Returns the default configuration instance with standard styles, numbering formats, and indentation. ```csharp public static readonly MarkDownFormatterConfiguration Default { get; } ``` ```csharp var template = DocxTemplate.Open("template.docx"); var mdFormatter = new MarkdownFormatter(MarkDownFormatterConfiguration.Default); template.RegisterFormatter(mdFormatter); ``` -------------------------------- ### Binding Chart Data in DocxTemplater Source: https://github.com/amberg/docxtemplater/blob/main/README.md C# example for binding chart data to a DocxTemplater template. The model property name must match the chart's title in the template, and the property must be of type ChartData. ```csharp using var fileStream = File.OpenRead("MyTemplate.docx"); var docTemplate = new DocxTemplate(fileStream); var model = new { MyChart = new ChartData() { ChartTitle = "Foo 2", Categories = ["Cat1", "Cat2", "Cat3", "Cat4", "Cat5"], Series = [ new() {Name = "serie 1", Values = [2200.0, 5500.0, 4600.25, 9560.56],}, new() {Name = "serie 2", Values = [1200.0, 2500.0, 8600.25, 4560.56],}, ] } }; docTemplate.BindModel("ds", model); var resultStream = docTemplate.Process(); ``` -------------------------------- ### ProcessSettings with Culture Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ProcessSettings.md Demonstrates how to set a specific culture for localization when processing a template. This affects how dates and numbers are formatted. ```APIDOC ## ProcessSettings with Culture ### Description This example shows how to configure `ProcessSettings` to use a specific culture, such as French (`fr-FR`), for formatting dates and numbers within a DocxTemplater template. ### Method Not applicable (Object instantiation and property assignment) ### Endpoint Not applicable ### Parameters #### Request Body - **Culture** (CultureInfo) - Required - The culture to use for formatting. ### Request Example ```csharp var settings = new ProcessSettings { Culture = new CultureInfo("fr-FR") }; var template = new DocxTemplate(fileStream, settings); template.BindModel("ds", new { Date = DateTime.Now, Price = 1234.56 }); // Dates and numbers format according to French locale template.Save("output.docx"); ``` ### Response #### Success Response (200) Not applicable (Operation modifies template processing and saves output) #### Response Example Not applicable ``` -------------------------------- ### Register Markdown Formatter Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Demonstrates how to register the MarkdownFormatter with default and custom configurations for list and table styles. ```csharp var template = DocxTemplate.Open("template.docx"); template.RegisterFormatter(new MarkdownFormatter()); ``` ```csharp var mdConfig = new MarkDownFormatterConfiguration { UnorderedListStyle = "List Bullet", OrderedListStyle = "List Number", TableStyle = "Light Grid Accent 1" }; var template = new DocxTemplate(stream, settings); template.RegisterFormatter(new MarkdownFormatter(mdConfig)); ``` -------------------------------- ### Schema Analysis Workflow for Validation and Rendering Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-TemplateSchema.md Combines schema analysis with data preparation and validation before template rendering. Ensures data model compatibility with the template structure for a smoother processing pipeline. ```csharp using var template = DocxTemplate.Open("report.docx"); // Analyze before processing (cheaper than process and rollback) var schema = template.GetTemplateSchema(); // Prepare data based on schema var dataModel = new { Title = "Q1 Report", Date = DateTime.Now, Items = GetReportItems() // Items collection from schema }; // Validate that model matches schema expectations var itemsNode = schema.Roots["items"]; if (itemsNode?.Kind == TemplateNodeKind.Collection) { var requiredItemProperties = itemsNode.ItemSchema.Properties.Keys; // Verify each item in GetReportItems() has these properties } // Now render knowing it should work template.BindModel("ds", dataModel); template.Save("report_out.docx"); ``` -------------------------------- ### Save(string targetPath) Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Processes the template and saves the resulting .docx file to the specified file system path. Ensure the target directory exists and the path is writable. ```APIDOC ## Save(string targetPath) ### Description Processes the template and saves the result to a file. ### Method `Save(string targetPath)` ### Parameters #### Path Parameters - **targetPath** (`string`) - Required - File system path where the output .docx will be written ### Throws `UnauthorizedAccessException` if the file path is not writable; `DirectoryNotFoundException` if the target directory does not exist. ### Example ```csharp template.BindModel("ds", data); template.Save("output.docx"); ``` ``` -------------------------------- ### ImageFormatter Usage in Templates Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Shows various syntaxes for using the ImageFormatter in templates, including basic insertion, stretching options for containers, and setting specific dimensions or rotation. ```plaintext {{imageBytes}:img} {{imageData}:img(keepratio)} {{imageData}:img(STRETCHW)} {{imageData}:img(STRETCHH)} {{imageData}:img(w:100mm)} {{imageData}:img(h:50px)} {{imageData}:img(w:100cm,h:50cm)} {{imageData}:img(r:90)} {{imageData}:img(w:100mm,h:50mm,r:45)} ``` -------------------------------- ### Initialize ProcessSettings with Culture Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ProcessSettings.md Sets the culture for formatting locale-specific values during template processing. Use this when generating documents for different regions. ```csharp var settings = new ProcessSettings { Culture = new CultureInfo("de-DE") }; var template = new DocxTemplate(stream, settings); ``` -------------------------------- ### Process() Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Executes the complete template processing pipeline, including variable replacement, formatter application, loop expansion, and conditional rendering. This method must be called after all models are bound but before saving the document. It returns a MemoryStream containing the processed .docx file. ```APIDOC ## Process() ### Description Executes the complete template processing pipeline: variable replacement, formatter application, loop expansion, conditional rendering, and cleanup. Must be called after all models are bound but before saving. ### Method `Process()` ### Return `MemoryStream` containing the processed .docx file. ### Throws `OpenXmlTemplateException` if placeholders cannot be resolved (depends on `ProcessSettings.BindingErrorHandling`). ### Notes - Can only be called once per instance. - After processing, the document state is finalized. - The returned stream is positioned at the beginning. ### Example ```csharp template.BindModel("ds", data); var resultStream = template.Process(); ``` ``` -------------------------------- ### Register Custom Extension Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Shows how to create and register a custom ITemplateProcessorExtension. Only one instance of each extension type is permitted. ```csharp public class CustomExtension : ITemplateProcessorExtension { public void PreProcess(OpenXmlCompositeElement content) { } public void ReplaceVariables(ITemplateProcessingContext ctx, OpenXmlElement parent, List content) { } } var template = DocxTemplate.Open("template.docx"); template.RegisterExtension(new CustomExtension()); // Only one extension of each type allowed ``` -------------------------------- ### Clone Method for MarkDownFormatterConfiguration Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-ProcessSettings.md Creates an independent deep copy of the configuration. Useful for creating context-specific configurations during template processing. ```csharp public MarkDownFormatterConfiguration Clone() ``` ```csharp var baseConfig = MarkDownFormatterConfiguration.Default; var contextConfig = baseConfig.Clone(); contextConfig.TableStyle = "Table Grid"; ``` -------------------------------- ### DocxTemplate Constructors Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Instantiates a DocxTemplate object, either with default settings or custom processing settings, using a stream of the .docx file. ```APIDOC ## DocxTemplate(Stream docXStream) ### Description Creates a new `DocxTemplate` instance with default processing settings. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```csharp public DocxTemplate(Stream docXStream) ``` ### Parameters - **docXStream** (`Stream`) - Required - Stream containing the .docx file bytes ### Throws - `ArgumentNullException` if `docXStream` is null. ### Example ```csharp using var fileStream = File.OpenRead("template.docx"); var template = new DocxTemplate(fileStream); ``` ## DocxTemplate(Stream docXStream, ProcessSettings settings) ### Description Creates a new `DocxTemplate` instance with custom processing settings. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```csharp public DocxTemplate(Stream docXStream, ProcessSettings settings) ``` ### Parameters - **docXStream** (`Stream`) - Required - Stream containing the .docx file bytes - **settings** (`ProcessSettings`) - Required - Configuration for template processing ### Throws - `ArgumentNullException` if either parameter is null. ### Example ```csharp var settings = new ProcessSettings { Culture = new CultureInfo("de-DE") }; using var fileStream = File.OpenRead("template.docx"); var template = new DocxTemplate(fileStream, settings); ``` ``` -------------------------------- ### Configure Custom List Levels for Markdown Formatter Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Shows how to customize list item appearance and numbering for specific levels within the MarkdownFormatter. ```csharp var mdConfig = new MarkDownFormatterConfiguration(); // Replace default level 0 with custom bullets mdConfig.UnorderedListLevelConfiguration[0] = new ListLevelConfiguration( LevelText: "►", FontOverride: null, NumberingFormat: NumberFormatValues.Bullet, IndentPerLevel: 720 ); // Replace default level 0 ordering mdConfig.OrderedListLevelConfiguration[0] = new ListLevelConfiguration( LevelText: "%1)", FontOverride: null, NumberingFormat: NumberFormatValues.Decimal, IndentPerLevel: 720 ); template.RegisterFormatter(new MarkdownFormatter(mdConfig)); ``` -------------------------------- ### Create and Register Currency Formatter Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Formatters.md Implements a custom IFormatter for currency values. It handles decimal, double, and int types and formats them according to the specified culture. The formatter is then registered with the template. ```csharp public class CurrencyFormatter : IFormatter { public bool CanHandle(Type type, string prefix) { return prefix?.ToUpper() == "CURRENCY" && (type == typeof(decimal) || type == typeof(double) || type == typeof(int)); } public void ApplyFormat( ITemplateProcessingContext templateContext, FormatterContext formatterContext, Text target) { if (formatterContext.Value is not decimal amount) amount = Convert.ToDecimal(formatterContext.Value); var currency = formatterContext.Args.FirstOrDefault() ?? "USD"; var formatted = amount.ToString($"C", templateContext.ProcessSettings.Culture); target.Text = formatted; } } // Registration and usage var template = DocxTemplate.Open("invoice.docx"); template.RegisterFormatter(new CurrencyFormatter()); template.BindModel("invoice", new { Total = 1234.56m }); // {{invoice.Total}:currency(USD)} -> "$1,234.56" ``` -------------------------------- ### Creating a DynamicTable Instance Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-Models.md Instantiate a DynamicTable to represent data with variable columns. An optional header comparer can be provided for custom header deduplication. ```csharp var table = new DynamicTable(); // or with custom header comparison: var table = new DynamicTable(StringComparer.OrdinalIgnoreCase); ``` -------------------------------- ### Resource Cleanup with Using Statement Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/configuration.md Ensures proper resource cleanup by using a 'using' statement, which automatically calls Dispose() on the DocxTemplate instance. ```csharp using (var template = DocxTemplate.Open("template.docx")) { template.BindModel("data", data); template.Save("output.docx"); } // Dispose() called automatically ``` -------------------------------- ### DocxTemplate.BindModel Instance Method Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-DocxTemplate.md Registers a data model for template binding, associating it with a specific prefix for use in placeholders. ```APIDOC ## BindModel(string prefix, object model) ### Description Registers a data model for template binding. The prefix is used to reference the model in template placeholders (e.g., `{{prefix.PropertyName}}`). ### Method `void BindModel(string prefix, object model)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **prefix** (`string`) - Required - Case-insensitive name to reference the model in placeholders (e.g., "ds", "customer") - **model** (`object`) - Required - Data object, anonymous type, dictionary, or `ITemplateModel` implementation ### Throws No exception thrown; null models are accepted. ### Example ```csharp var template = DocxTemplate.Open("template.docx"); var data = new { Name = "John", Age = 30 }; template.BindModel("person", data); template.Save("output.docx"); ``` ``` -------------------------------- ### Rendering Separator Between Collection Items Source: https://github.com/amberg/docxtemplater/blob/main/README.md Demonstrates how to use the separator syntax within a collection loop to render specific text between each item. ```DocxTemplater Syntax {{#Items}} This text {{.Name}} is rendered for each element in the items collection {{:s:}} This is rendered between each element {{/Items}} ``` -------------------------------- ### Generate Skeleton Model from Schema Source: https://github.com/amberg/docxtemplater/blob/main/_autodocs/api-reference-TemplateSchema.md Builds a string representation of the template's data requirements by iterating through the schema's roots, properties, and item schemas. Useful for creating documentation or initial data structures. ```csharp var template = DocxTemplate.Open("invoice.docx"); var schema = template.GetTemplateSchema(); // Build a documentation or skeleton of what data is needed var requirements = new StringBuilder(); foreach (var (rootName, rootNode) in schema.Roots) { requirements.AppendLine($"Root: {rootName} ({rootNode.Kind})"); if (rootNode.Kind == TemplateNodeKind.Object) { foreach (var (propName, propNode) in rootNode.Properties) { requirements.AppendLine($" - {propName}: {propNode.Kind}"); } } else if (rootNode.Kind == TemplateNodeKind.Collection) { requirements.AppendLine($" Items:"); if (rootNode.ItemSchema?.Kind == TemplateNodeKind.Object) { foreach (var (propName, propNode) in rootNode.ItemSchema.Properties) { requirements.AppendLine($" - {propName}: {propNode.Kind}"); } } } } Console.WriteLine(requirements.ToString()); ```