Search code examples
c#htmlms-wordspire.doc

Insert HTML instead of key from Template.docx in the Spire.Doc


I want to create a Word document from Template.docx with Spire.Doc. For this, I coded like this:

//sample file path
string samplePath = Application.StartupPath + Path.DirectorySeparatorChar + "Template.docx";
//result docs paths
string docxPath = Application.StartupPath + Path.DirectorySeparatorChar + "Result.docx";

Button Submit event:

private void btnSubmit_Click(object sender, EventArgs e)
{
    //initialize word object
    document = new Document();
    document.LoadFromFile(samplePath);
    //get strings to replace
    Dictionary<string, string> dictReplace = GetReplaceDictionary();
    //Replace text
    foreach (KeyValuePair<string, string> kvp in dictReplace)
    {
        document.Replace(kvp.Key, kvp.Value, true, true);
    }
    //Save doc file.
    document.SaveToFile(docxPath, FileFormat.Docx);
    document.Close();

}

And lastly content of GetReplaceDictionary() method:

Dictionary<string, string> GetReplaceDictionary()
{
    Dictionary<string, string> replaceDict = new Dictionary<string, string>();
    replaceDict.Add("#name#", txtName.Text.Trim());
    replaceDict.Add("#age#",txtAge.Text);
    replaceDict.Add("#address#", txtAddress.Text.Trim());
    replaceDict.Add("#phonenumber#",txtPhonenumber.Text);
    replaceDict.Add("#emailaddress#",txtEmailaddress.Text);
    replaceDict.Add("#experience#", txtExperience.Text.Trim());
    replaceDict.Add("#position#", txtPosition.Text.Trim());
    replaceDict.Add("#salary#", txtSalary.Text);
    replaceDict.Add("#applydate#",dateTimePicker.Text);
    string isEmployed= this.radio_isEmployed_Yes.Checked ? "Yes" : "No";
    replaceDict.Add("#isemployed#", isEmployed);
    replaceDict.Add("#education#", txtEducation.Text.Trim());

    return replaceDict;
}

I want to write to Work Experience textbox like this:

Lorem ipsum <b>dolor sit amet</b>, consectetur <i>adipiscing</i> elit.

Here is the screen: enter image description here

And I want to show dolor sit amet to bold and adipiscing to italic in the word document, like this: enter image description here

But unfortunately, the HTML tags are shown in the Word document like this: enter image description here

And here is my Template.docx file: enter image description here

How can I show correctly HTML text instead of #experience# variable?


Solution

  • Unfortunately, there isn't an easy way to do this with Spire as far as I can tell. The document.Replace just replaces a string with another string as you've already discovered. The Spire program guide does suggest a solution to this but it's not particularly elegant.

    You'll need to add in bookmarks to your template document for the text you want to replace. So if you select the text #experience# and add this as a bookmark named experience:

    enter image description here

    You could then use something like the function below to replace the text with the supplied html:

    public void ReplaceBookmarkHTML(Document doc, string bookmarkName, string htmlString)
        {
            Section tempSection = doc.AddSection();
            tempSection.AddParagraph().AppendHTML(htmlString);
    
            ParagraphBase replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
            ParagraphBase replacementLastItem = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
            TextBodySelection selection = new TextBodySelection(replacementFirstItem, replacementLastItem);
            TextBodyPart part = new TextBodyPart(selection);
    
            BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
            bookmarkNavigator.MoveToBookmark(bookmarkName);
            bookmarkNavigator.ReplaceBookmarkContent(part);
            doc.Sections.Remove(tempSection);
        }
    

    You could then call this like below to get your HTML to replace the bookmark:

    ReplaceBookmarkHTML(document, "experience", "Lorem ipsum <b>dolor sit amet</b>, consectetur <i>adipiscing</i> elit.");