In office automation development, one of the most common requirements is to batch-generate Word documents (such as contracts, reports, resumes, notices, etc.) from fixed templates. This article demonstrates how to use the Spire.Doc for .NET component to load a template file, replace text placeholders with real data, support replacing placeholders with images, and ultimately produce a complete Word document.
Why Choose Spire.Doc?
Spire.Doc is a powerful .NET Word component that allows you to create, read, edit, and convert Word documents without installing Microsoft Office. It provides a rich set of APIs – especially the Document.Replace() method for fast text substitution, and in combination with FindString() and DocPicture, it flexibly enables image insertion, making it ideal for template‑filling scenarios.
Implementation Steps
The following complete console application example demonstrates how to replace placeholders like #name# and #gender# with actual content, and replace #photo# with an image.
1. Import Namespaces and Initialize the Document
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
Create a Document object and load the template file (.docx):
Document document = new Document();
document.LoadFromFile("Template.docx");
2. Text Placeholder Replacement
Build a dictionary where keys are placeholders (e.g., #name#) and values are the actual data. Here we localize the sample content to an English context:
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "#name#", "Zhang San" },
{ "#gender#", "Male" },
{ "#birthdate#", "January 15, 1990" },
{ "#address#", "Pudong New Area, Shanghai" },
{ "#city#", "Shanghai" },
{ "#state#", "Municipality" },
{ "#postal#", "200120" },
{ "#country#", "China" }
};
Iterate through the dictionary and call document.Replace(placeholder, replacement, true, true) to perform a full‑document replacement. The two Boolean parameters specify whether to match case and whole words, respectively; set them as needed.
3. Image Placeholder Replacement
Text replacement cannot handle images, so we need a separate method ReplaceTextWithImage. Its core logic is:
- Load the image with
Image.FromFile(); - Create a
DocPictureobject and load the image into it; - Locate the
#photo#placeholder usingdocument.FindString(), obtaining theTextRange; - Retrieve the index of that
TextRangewithin its paragraph’s child objects, insert the picture at the same position, and then remove the placeholder text.
static void ReplaceTextWithImage(Document document, string stringToReplace, string imagePath)
{
Image image = Image.FromFile(imagePath);
DocPicture pic = new DocPicture(document);
pic.LoadImage(image);
TextSelection selection = document.FindString(stringToReplace, false, true);
TextRange range = selection.GetAsOneRange();
int index = range.OwnerParagraph.ChildObjects.IndexOf(range);
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);
}
Call it with the image path:
ReplaceTextWithImage(document, "#photo#", "portrait.png");
4. Save and Release
Finally, save the document as a new file and release resources:
document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);
document.Dispose();
Complete Code
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace CreateWordByReplacingTextPlaceholders
{
class Program
{
static void Main(string[] args)
{
Document document = new Document();
document.LoadFromFile("Template.docx");
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "#name#", "Zhang San" },
{ "#gender#", "Male" },
{ "#birthdate#", "January 15, 1990" },
{ "#address#", "Pudong New Area, Shanghai" },
{ "#city#", "Shanghai" },
{ "#state#", "Municipality" },
{ "#postal#", "200120" },
{ "#country#", "China" }
};
foreach (var kvp in replaceDict)
{
document.Replace(kvp.Key, kvp.Value, true, true);
}
ReplaceTextWithImage(document, "#photo#", "portrait.png");
document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);
document.Dispose();
}
static void ReplaceTextWithImage(Document document, string stringToReplace, string imagePath)
{
Image image = Image.FromFile(imagePath);
DocPicture pic = new DocPicture(document);
pic.LoadImage(image);
TextSelection selection = document.FindString(stringToReplace, false, true);
TextRange range = selection.GetAsOneRange();
int index = range.OwnerParagraph.ChildObjects.IndexOf(range);
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);
}
}
}
Notes and Extensions
-
Template Design : In the Word template, placeholders must exactly match the strings in the code (including case and special symbols). It is recommended to use obvious markers like
#or{{}}to avoid unintended replacements. -
Image Handling : The
ReplaceTextWithImagemethod assumes that the placeholder exists independently within a paragraph. If the placeholder shares a line with other text, inserting an image may affect layout; you can adjust the insertion position according to your business logic. -
Performance Optimization : For bulk document generation, you may reuse the
Documentobject or work with memory streams. -
Fonts and Styles : After text replacement, the new content inherits the style of the original placeholder. If custom styling is needed, you can manipulate the
CharacterFormatproperty of theTextRange.
Summary
With the concise APIs provided by Spire.Doc, we have implemented data population for Word templates in just a few dozen lines of code, supporting both text and images. This approach greatly improves the efficiency and accuracy of document generation, making it well‑suited for enterprise‑level reporting, certificate printing, bulk correspondence, and more. Developers only need to focus on template design and data sources; the rest is handled by the code.
If you are looking for a lightweight, Office‑independent solution for Word manipulation, Spire.Doc is certainly worth trying. We hope this article helps you get started quickly and adds automated document generation capabilities to your projects.
Top comments (0)