Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Thu May 03, 2012 8:47 am

Dears,

we need to replace placeholders within a word document by RichText Data (XHTML) out of a website. Whats the best way to do the replacing, means finding placeholder and replace them with xhtml data?

Thanx

HMP
 
Posts: 6
Joined: Tue Aug 10, 2010 10:19 am

Fri May 04, 2012 7:52 am

Hi,

Thanks for your inquiry.
You could use doc.FindAllPattern method to find your placeholders by regular expression and use a blank section to load your XHTML data, a full demo is attached. You could get the document template fax.doc in the attachment.
Code: Select all
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SALESSUPPORT_464
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document(@"..\..\fax.doc");

            Dictionary<String, String> data = new Dictionary<String, String>
            {
                {"To", "<b>Harry Hu</b>"},
                {"Fax", "<i>+1</i> <b>(69)</b> <u>123456</u>"},
                {"From", "<span style='color: red'>Stephen Chen</span>"},
                {"Date", "2012-05-04"},
                {"Subject", "Spire.Doc demo."},
                {"Message0", "<p style='color: red'>Message0 line1.</p><p>Message0 line2.</p>"},
                {"Message1", "<p style='color: red'>Message1 line1.</p><p><span style='color: blue'>Message1 line2.</span></p>"},
                {"Message2", "<p style='color: red'>Message2 line1.</p><p><span style='color: blue'>Message2 line2.</span></p><p><span style='color: green'>Message2 line3.</span></p>"},
                {"Message3", "<p style='color: red'>Message3 line1.</p><p><span style='color: blue'>Message3 line2.</span></p><p><span style='color: green'>Message3 line3.</span></p><table><tr><td>Simple table</td></tr></table>"},
            };

            Replace(doc, data);
            doc.SaveToFile("test.doc");
            System.Diagnostics.Process.Start("test.doc");
        }

        public static void Replace(Document doc, Dictionary<String, String> data)
        {
            doc.XHTMLValidateOption = XHTMLValidationType.None;
            Regex placeholderPattern = new Regex(@"\{\{(\w+)}}");
            TextSelection[] placeholders = doc.FindAllPattern(placeholderPattern);

            Section tempSection = doc.AddSection();

            foreach (TextSelection placeholder in placeholders)
            {
                Match match = placeholderPattern.Match(placeholder.SelectedText);
                String dataKey = match.Groups[1].Value;
                TextRange textRange = placeholder.GetAsOneRange();
                if (data.ContainsKey(dataKey))
                {
                    String value = data[dataKey];
                    tempSection.AddParagraph().AppendHTML(value);
                    ReplaceByHTML(textRange, tempSection);
                }
                else
                {
                    textRange.Text = "";
                }
            }
            doc.Sections.Remove(tempSection);
        }

        public static void ReplaceByHTML(TextRange textRange, Section tempSection)
        {
            Paragraph owner = textRange.OwnerParagraph;
            int index = owner.Items.IndexOf(textRange);
            Body ownerBody = owner.OwnerTextBody;
            int paragraphIndex = ownerBody.ChildObjects.IndexOf(owner);
            int nextParagraphInHTML = 1;
            if (owner.ChildObjects.Count == 1)
            {
                //the paragraph only includes one place holder, replace the paragraph
                owner.ChildObjects.Clear();
                ownerBody.ChildObjects.RemoveAt(paragraphIndex);
                ownerBody.ChildObjects.Insert(paragraphIndex, tempSection.Body.ChildObjects[0]);
                nextParagraphInHTML = 0;
            }
            else
            {
                owner.Items.RemoveAt(index);
                //the paragraph has many elements, insert these elements in the first paragraph of tempSection
                while ((tempSection.Body.ChildObjects[0] as Paragraph).Items.Count > 0)
                {
                    ParagraphBase item = tempSection.Paragraphs[0].Items[0] as ParagraphBase;
                    owner.Items.Insert(index++, item);
                }
            }

            if (tempSection.Body.ChildObjects.Count > nextParagraphInHTML)
            {
                //html has multiple paragraphs
                for (int i = nextParagraphInHTML; i < tempSection.Body.ChildObjects.Count; )
                {
                    ownerBody.ChildObjects.Insert(++paragraphIndex, tempSection.Body.ChildObjects[i]);
                }

                //split the paragrah of the place holder
                if (owner.ChildObjects.Count > index)
                {
                    Paragraph lastParagraph = ownerBody.ChildObjects[paragraphIndex] as Paragraph;
                    if (lastParagraph == null)
                    {
                        //new paragraph
                        lastParagraph = owner.Clone() as Paragraph;
                        for (int i = 0; i < index; i++)
                        {
                            lastParagraph.ChildObjects.RemoveAt(0);
                        }


                        for (int i = index; i < owner.ChildObjects.Count;)
                        {
                            owner.ChildObjects.RemoveAt(i);
                        }
                        ownerBody.ChildObjects.Insert(paragraphIndex, lastParagraph);
                    }
                    else
                    {
                        for (int i = 0, length = owner.ChildObjects.Count - index; i < length; i++)
                        {
                            lastParagraph.ChildObjects.Add(owner.ChildObjects[index]);
                        }
                    }
                }
            }

            tempSection.Body.ChildObjects.Clear();
        }
    }
}
Harry
Technical Support / Developer,
e-iceblue Support Team
User avatar

harry.support
 
Posts: 180
Joined: Mon Nov 08, 2010 3:11 pm

Return to Spire.Doc

cron