C#: Generate Word Documents Rapidly from a Template

 In daily development, we often encounter scenarios where we need to generate Word documents in bulk, such as contracts, notices, and reports. The most elegant approach is to prepare a template file and then use code to replace placeholders, quickly producing the final documents. In this article, we’ll show how to easily achieve this using Free Spire.Doc.

Why Choose Free Spire.Doc?

Free Spire.Doc is a free and easy-to-use Word processing library that allows you to create, read, edit, and save documents without installing Microsoft Office. It supports both .NET Framework and .NET Core, making it ideal for server-side batch processing.

Install via NuGet:

PM> Install-Package FreeSpire.Doc

Implementation Steps

  1. Design a Word template in advance (e.g., template.docx) and mark placeholders for dynamic content
  2. Load the template in code and replace placeholders with actual data
  3. Support both text replacement and image insertion (e.g., profile photos)
  4. Save the result as a new Word document

Complete Code

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace CreateWordByReplacingPlaceholders
{
    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 placeholders and their replacements
            Dictionary<string, string> replaceDict = new Dictionary<string, string>
            {
		{ "#name#", "Michael Johnson" },
		{ "#gender#", "Male" },
		{ "#birthdate#", "March 20, 1990" },
		{ "#address#", "1234 Maple Street" },
		{ "#city#", "Los Angeles" },
		{ "#province#", "California" },
		{ "#postal#", "90001" },
		{ "#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 for the photograph 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);
            pic.Width = 130;

            // 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);
        }
    }
}


Code Explanation

1. Text Replacement

First, prepare a dictionary that maps placeholders to their replacement values:

Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
    { "#name#", "Michael Johnson" },
    { "#gender#", "Male" },
    // ... other fields
};

Then iterate through the dictionary and call the document.Replace method. The last two parameters indicate whether the replacement is case-sensitive and whether to match whole words only.

2. Image Replacement

Replacing text with an image is slightly more complex. The key steps are:

  • Load the image using Image.FromFile
  • Create a DocPicture object, load the image, and set its width
  • Locate the placeholder using FindString
  • Get the paragraph and index of the placeholder
  • Insert the image at the same position and remove the placeholder text

3. Save the Document

Finally, call SaveToFile to save the new document and release resources.

Template Preparation Tips

In your Word template, mark dynamic fields with placeholders, for example:

FieldPlaceholder
Name#name#
Gender#gender#
Birth Date#birthdate#
Photo#photo#

Notes

  1. Ensure that the template file path and image path are correct
  2. Use unique placeholder patterns (e.g., #fieldname#) to avoid accidental replacements
  3. Adjust Width and Height when inserting images to control display size
  4. Always call Dispose() to release resources after processing

Summary

With Free Spire.Doc, you only need to maintain a single template file to generate thousands of personalized documents efficiently. The library also supports advanced features such as merging table cells, setting font styles, and adding headers and footers. Feel free to explore more!

评论

此博客中的热门博文

How to Convert Between Excel and CSV in C#:Based on Spire.XLS

Python Tutorial: Easily Rotate PDF Pages

Convert PDF to PNG Using Spire.PDF for Python