Create a Word Document from a Template Using C#

Create a Word Document from a Template Using C#

2025-04-18 08:58:44 Written by  Koohji
Rate this item
(0 votes)

Generating Word documents programmatically is a common requirement in business applications, whether for creating reports, contracts, or personalized letters. Spire.Doc for .NET provides a comprehensive solution for working with Word documents in C# without Microsoft Office dependencies.

This article explores two effective approaches for document generation from templates: replacing text placeholders and modifying bookmark content.

.NET Library for Creating Word Documents

Spire.Doc for .NET is a professional Word API that enables developers to perform a wide range of document processing tasks. Key features include:

  • Creating, reading, editing, and converting Word documents
  • Support for DOC, DOCX, RTF, and other formats
  • Template-based document generation
  • Mail merge functionality
  • Preservation of original formatting

The library is particularly useful for automating document generation in enterprise applications, where consistency and efficiency are crucial.

To begin generating Word documents from a template, donwload Spire.Doc for .NET from our official website or install it using the NuGet Package Manager with the following command:

PM> Install-Package Spire.Doc

Create a Word Document By Replacing Text Placeholders

The Document.Replace method in the Spire.Doc library is used to find and replace specific text within a Word document. This method allows for the efficient modification of text placeholders, enabling the dynamic generation of documents based on templates.

Here are the steps for Word generation through text pattern replacement:

  • Document Initialization: Create a new Document object and load the template file.
  • Placeholder Definition: Use a dictionary to map placeholders (like #name#) to their replacement values.
  • Text Replacement: The Document.Replace method performs case-sensitive and whole-word replacement of all placeholders.
  • Image Handling: The custom ReplaceTextWithImage method locates a text placeholder and substitutes it with an image.
  • Document Saving: The modified document is saved with a new filename.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace CreateWordByReplacingTextPlaceholders
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a new Document object
            Document document = new Document();

            // Load the template Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Dictionary to hold text placeholders and their replacements
            Dictionary<string, string> replaceDict = new Dictionary<string, string>
            {
                { "#name#", "John Doe" },
                { "#gender#", "Male" },
                { "#birthdate#", "January 15, 1990" },
                { "#address#", "123 Main Street" },
                { "#city#", "Springfield" },
                { "#state#", "Illinois" },
                { "#postal#", "62701" },
                { "#country#", "United States" }
            };

            // Replace placeholders in the document with corresponding values
            foreach (KeyValuePair<string, string> kvp in replaceDict)
            {
                document.Replace(kvp.Key, kvp.Value, true, true);
            }

            // Path to the image file
            String imagePath = "C:\\Users\\Administrator\\Desktop\\portrait.png";

            // Replace the placeholder “#photo#” with an image
            ReplaceTextWithImage(document, "#photo#", imagePath);

            // Save the modified document
            document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);

            // Release resources
            document.Dispose();
        }

        // Method to replace a placeholder in the document with an image
        static void ReplaceTextWithImage(Document document, String stringToReplace, String imagePath)
        {
            // Load the image from the specified path
            Image image = Image.FromFile(imagePath);
            DocPicture pic = new DocPicture(document);
            pic.LoadImage(image);

            // Find the placeholder in the document
            TextSelection selection = document.FindString(stringToReplace, false, true);

            // Get the range of the found text
            TextRange range = selection.GetAsOneRange();
            int index = range.OwnerParagraph.ChildObjects.IndexOf(range);

            // Insert the image and remove the placeholder text
            range.OwnerParagraph.ChildObjects.Insert(index, pic);
            range.OwnerParagraph.ChildObjects.Remove(range);
        }
    }
}

Create Word from Template by Replacing Text Placeholders

Create a Word Document By Replacing Bookmark Content

The BookmarksNavigator class in Spire.Doc is specifically designed to manage and navigate through bookmarks in a Word document. This class simplifies the process of finding and replacing content in bookmarks, making it easy to update sections of a document without manually searching for each bookmark.

The following are the steps for Word generation using bookmark content replacement:

  • Document Initialization: Create a new Document object and load the template file.
  • Bookmark Content Definitions: Create a dictionary mapping bookmark names to their replacement content.
  • Bookmark Navigation: The BookmarksNavigator class provides precise control over bookmark locations.
  • Content Replacement: The ReplaceBookmarkContent method preserves the bookmark while updating its content.
  • Document Saving: The modified document is saved with a new filename.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace CreateWordByReplacingBookmarkContent
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a new Document object
            Document document = new Document();

            // Load the template Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Define bookmark names and their replacement values
            Dictionary<string, string> replaceDict = new Dictionary<string, string>
            {
                { "name", "Tech Innovations Inc." },
                { "year", "2015" },
                { "headquarter", "San Francisco, California, USA" },
                { "history", "Tech Innovations Inc. was founded by a group of engineers and " +
                              "entrepreneurs with a vision to revolutionize the technology sector. Starting " +
                              "with a focus on software development, the company expanded its portfolio to " +
                              "include artificial intelligence and cloud computing solutions." }
            };

            // Create a BookmarksNavigator to manage bookmarks in the document
            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);

            // Replace each bookmark's content with the corresponding value
            foreach (KeyValuePair<string, string> kvp in replaceDict)
            {
                bookmarkNavigator.MoveToBookmark(kvp.Key); // Navigate to bookmark
                bookmarkNavigator.ReplaceBookmarkContent(kvp.Value, true); // Replace content
            }

            // Save the modified document
            document.SaveToFile("ReplaceBookmarkContent.docx", FileFormat.Docx2013);

            // Release resources
            document.Dispose();
        }
    }
}

Create Word from Template by Replacing Bookmark Content

Conclusion

Both approaches provide effective ways to generate documents from templates, but with important differences:

  • Text Replacement Method:
    • Permanently removes placeholders during replacement
    • Best for one-time document generation
    • Better suited for replacing text with images
  • Bookmark Replacement Method:
    • Preserves bookmarks for future updates
    • Ideal for templates requiring periodic updates

Additionally, Spire.Doc for .NET supports Mail Merge functionality, which provides another powerful way to dynamically generate documents from templates. This feature is particularly useful for creating personalized documents in bulk, such as form letters or reports, where data comes from a database or other structured source.

Get a Free License

To fully experience the capabilities of Spire.Doc for .NET without any evaluation limitations, you can request a free 30-day trial license.

Additional Info

  • tutorial_title:
Last modified on Monday, 21 April 2025 01:26