none
Generating a Word document from Template replacing the PlaceHolders RRS feed

  • Question

  • Hi,

     

    I have a scenario where I need to generate a word document in the server side from a template replaceing the plcaeholders with the mapped data at runtime

     

    I approach I followed is

    I am making a copy of the template and creating a new file with as the output file

    then opening the word document using the

    WordprocessingDocument.Open (.....) and after that I am reading the MainDocumentPart and loading that into a XMLDocument. Then I am reading the placeholders using the xpath query for ( //w:fldSimple) and replacing the text with the mapped data

     

    Is my approach correct one?

    Is there any better way or explosed API to get all the placeholders instead of doing the xml read of the file?

     

    Here is the code  I am using

     

    File.Copy(template, outFile, true);

    docObj = WordprocessingDocument.Open(outFile, true);

    MainDocumentPart mainDoc = docObj.MainDocumentPart;

    StreamReader strRdr = new StreamReader(mainDoc.GetStream());

    string str = strRdr.ReadToEnd();

    xmlDoc.LoadXml(str);

    nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);

    NSMgr();

     

    //Select all field level nodes in the recipient XML structure

    XmlNodeList incomingNodeList = recXML.SelectNodes("/" + "Receipent" + "/*");

    XmlNodeList lstFlds = xmlDoc.SelectNodes("//w:fldSimple", nsmgr);

    XmlNode textElement = xmlDoc.SelectSingleNode("//w:body", nsmgr);

    foreach (XmlNode incomingNode in incomingNodeList)

    {

    ///This will doing the string operation for replacing the placeholder text with the mapped data

    ReplaceText(incomingNode, textElement);

    }

    xmlDoc.Save(mainDoc.GetStream(FileMode.Create, FileAccess.Write));

     

     

    Please help me in this.

     

     

    Friday, July 4, 2008 3:22 PM

All replies