Create Word files in Blazor

With GemBox.Document you can build Blazor applications that read, write, edit, process, and convert Word documents. The following live examples show how you can create Blazor apps that generate Word files and download them to your browser.

Create Word files in Blazor Server App

The following example shows how you can create a Blazor Server application that:

  1. Imports data from a web form into a Word document using the Mail Merge process.
  2. Creates a file of a specified format like DOCX, PDF, ODT, or HTML.
  3. Downloads the generated file with a downloadFileFromStream JS function (see ASP.NET Core Blazor file downloads).
Generating a DOCX file from Blazor Server app
Screenshot of submitted web form and created Word document
@page "/"
@inject IJSRuntime JS
@using BlazorServerApp.Data
@using System.IO
@using GemBox.Document

<h1>Invoice generator [Blazor Server App]</h1>

<EditForm Model="model" OnSubmit="CreateDocument">
    <p><label>Number: <InputNumber @bind-Value="model.Number" /></label></p>
    <p><label>Date: <InputDate @bind-Value="model.Date" /></label></p>
    <p><label>Company: <InputText @bind-Value="model.Company" /></label></p>
    <p><label>Address: <InputText @bind-Value="model.Address" /></label></p>
    <p><label>Name: <InputText @bind-Value="model.Name" /></label></p>
    <p><label>Format:
        <InputSelect @bind-Value="model.Format">
            @foreach (string format in model.FormatMappingDictionary.Select(item => item.Key))
            {
                <option value="@format">@format</option>
            }
        </InputSelect>
    </label></p>
    <button class="btn btn-primary" type="submit">Create</button>
</EditForm>

@code {
    private InvoiceModel model = new();

    private async Task CreateDocument()
    {
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        // Load template document.
        var document = DocumentModel.Load("InvoiceWithFields.docx");

        // Execute mail merge process.
        document.MailMerge.Execute(this.model);

        // Save document in specified file format.
        var stream = new MemoryStream();
        document.Save(stream, this.model.Options);

        // Download file.
        using var streamRef = new DotNetStreamReference(stream);
        await JS.InvokeVoidAsync("downloadFileFromStream", $"BlazorServerOutput.{this.model.Format.ToLower()}", streamRef);
    }
}
using GemBox.Document;
using System;
using System.Collections.Generic;

namespace BlazorServerApp.Data
{
    public class InvoiceModel
    {
        public int Number { get; set; } = 1;
        public DateTime Date { get; set; } = DateTime.Today;
        public string Company { get; set; } = "ACME Corp.";
        public string Address { get; set; } = "240 Old Country Road, Springfield, United States";
        public string Name { get; set; } = "Joe Smith";
        public string Format { get; set; } = "DOCX";
        public SaveOptions Options => this.FormatMappingDictionary[this.Format];
        public IDictionary<string, SaveOptions> FormatMappingDictionary => new Dictionary<string, SaveOptions>()
        {
            ["PDF"] = new PdfSaveOptions(),
            ["DOCX"] = new DocxSaveOptions(),
            ["ODT"] = new OdtSaveOptions(),
            ["HTML"] = new HtmlSaveOptions() { EmbedImages = true },
            ["MHTML"] = new HtmlSaveOptions() { HtmlType = HtmlType.Mhtml },
            ["RTF"] = new RtfSaveOptions(),
            ["XML"] = new XmlSaveOptions(),
            ["TXT"] = new TxtSaveOptions(),
            ["XPS"] = new XpsSaveOptions(), // XPS is supported only on Windows.
            ["PNG"] = new ImageSaveOptions(ImageSaveFormat.Png),
            ["JPG"] = new ImageSaveOptions(ImageSaveFormat.Jpeg),
            ["BMP"] = new ImageSaveOptions(ImageSaveFormat.Bmp),
            ["GIF"] = new ImageSaveOptions(ImageSaveFormat.Gif),
            ["TIF"] = new ImageSaveOptions(ImageSaveFormat.Tiff),
            ["SVG"] = new ImageSaveOptions(ImageSaveFormat.Svg)
        };
    }
}

Create Word files in Blazor WebAssembly App

The following example shows how you can create a Blazor WebAssembly application that:

  1. Imports data from a web form into a Word document using Find and Replace operations.
  2. Creates a file of a specified format like DOCX, PDF, ODT, or HTML.
  3. Downloads the generated file with a downloadFileFromStream JS function (see ASP.NET Core Blazor file downloads).
Generating a PDF document from Blazor WebAssembly app
Screenshot of submitted web form and created PDF document
@page "/"
@inject IJSRuntime JS
@using BlazorWebAssemblyApp.Data
@using System.IO
@using System.Reflection
@using GemBox.Document

<h1>Invoice generator [Blazor WebAssembly App]</h1>

<EditForm Model="model" OnSubmit="CreateDocument">
    <p><label>Number: <InputNumber @bind-Value="model.Number" /></label></p>
    <p><label>Date: <InputDate @bind-Value="model.Date" /></label></p>
    <p><label>Company: <InputText @bind-Value="model.Company" /></label></p>
    <p><label>Address: <InputText @bind-Value="model.Address" /></label></p>
    <p><label>Name: <InputText @bind-Value="model.Name" /></label></p>
    <p><label>Format:
        <InputSelect @bind-Value="model.Format">
            @foreach (string format in model.FormatMappingDictionary.Select(item => item.Key))
            {
                <option value="@format">@format</option>
            }
        </InputSelect>
    </label></p>
    <button class="btn btn-primary" type="submit">Create</button>
</EditForm>

@code {
    private InvoiceModel model = new();

    private async Task CreateDocument()
    {
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        // Add embedded resource fonts, required for saving to PDF.
        FontSettings.FontsBaseResourceLocation = "/Fonts/";

        // Load template document.
        using var inputStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BlazorWebAssemblyApp.InvoiceWithPlaceholders.docx")!;
        var document = DocumentModel.Load(inputStream, LoadOptions.DocxDefault);

        // Execute find and replace operations.
        document.Content.Replace("{{Number}}", this.model.Number.ToString("0000"));
        document.Content.Replace("{{Date}}", this.model.Date.ToString("d MMM yyyy HH:mm"));
        document.Content.Replace("{{Company}}", this.model.Company);
        document.Content.Replace("{{Address}}", this.model.Address);
        document.Content.Replace("{{Name}}", this.model.Name);

        // Save document in specified file format.
        var outputStream = new MemoryStream();
        document.Save(outputStream, this.model.Options);

        // Download file.
        using var streamRef = new DotNetStreamReference(outputStream);
        await JS.InvokeVoidAsync("downloadFileFromStream", $"BlazorWebAssemblyOutput.{this.model.Format.ToLower()}", streamRef);
    }
}
using GemBox.Document;
using System;
using System.Collections.Generic;

namespace BlazorWebAssemblyApp.Data
{
    public class InvoiceModel
    {
        public int Number { get; set; } = 1;
        public DateTime Date { get; set; } = DateTime.Today;
        public string Company { get; set; } = "ACME Corp.";
        public string Address { get; set; } = "240 Old Country Road, Springfield, United States";
        public string Name { get; set; } = "Joe Smith";
        public string Format { get; set; } = "PDF";
        public SaveOptions Options => this.FormatMappingDictionary[this.Format];
        public IDictionary<string, SaveOptions> FormatMappingDictionary => new Dictionary<string, SaveOptions>()
        {
            ["PDF"] = new PdfSaveOptions(),
            ["DOCX"] = new DocxSaveOptions(),
            ["ODT"] = new OdtSaveOptions(),
            ["HTML"] = new HtmlSaveOptions() { EmbedImages = true },
            ["MHTML"] = new HtmlSaveOptions() { HtmlType = HtmlType.Mhtml },
            ["RTF"] = new RtfSaveOptions(),
            ["XML"] = new XmlSaveOptions(),
            ["TXT"] = new TxtSaveOptions(),
            ["PNG"] = new ImageSaveOptions(ImageSaveFormat.Png),
            ["JPG"] = new ImageSaveOptions(ImageSaveFormat.Jpeg),
            ["BMP"] = new ImageSaveOptions(ImageSaveFormat.Bmp),
            ["GIF"] = new ImageSaveOptions(ImageSaveFormat.Gif),
            ["TIF"] = new ImageSaveOptions(ImageSaveFormat.Tiff),
            ["SVG"] = new ImageSaveOptions(ImageSaveFormat.Svg)
        };
    }
}

Besides installing GemBox.Document, for Blazor WebAssembly, you'll also need to include its native dependencies.

If you are going to create PDF or image files, the font files need to be present, so you'll need to embed the required font files inside the application itself and specify the FontSettings.FontsBaseResourceLocation property. For more information, see the Assembly fonts example.

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <WasmBuildNative>true</WasmBuildNative>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="GemBox.Document" Version="*" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.1" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="8.0.1" PrivateAssets="all" />
  </ItemGroup>

  <!-- Add HarfBuzzSharp and SkiaSharp native assets. -->
  <ItemGroup>
    <PackageReference Include="HarfBuzzSharp.NativeAssets.WebAssembly" Version="7.3.0" />
    <NativeFileReference Include="$(HarfBuzzSharpStaticLibraryPath)\3.1.34\**\*.a" />
    <PackageReference Include="SkiaSharp.NativeAssets.WebAssembly" Version="2.88.6" />
    <NativeFileReference Include="$(SkiaSharpStaticLibraryPath)\3.1.34\**\*.a" />
  </ItemGroup>

  <!-- Add Calibri and Calibri Bold embedded fonts. -->
  <ItemGroup>
    <EmbeddedResource Include="Fonts\calibri.ttf" />
    <EmbeddedResource Include="Fonts\calibrib.ttf" />
  </ItemGroup>

</Project>

See also


Next steps

GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API. How about testing it today?

Download Buy