0
votes

Unable to use Microsoft.Office.Interop.Word, I'm using Xceed DocX to take data from WPF fields and write them to a Word file. I need to replace a «field» in a Word file with the text and formatting from a RTB. If I use something simple like this:

/// <summary>
/// Replaces field location with given formatted text
/// </summary>
/// <param name="mergeField">Target location</param>
/// <param name="textToWrite">Rich, formatted text to process and insert</param>
public static void FindReplaceRich(string mergeField, string textToWrite)
{
    while (document.FindAll(mergeField).Count > 0)
    {
        document.ReplaceText("«" + mergeField + "»", textToWrite);                
    }
}

The code above is used for unformatted text and so in this instance my Word file gets a silly, RTF blurb added right onto the document like so: {\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff0{\fonttbl{\f0\fcharset0 Times New Roman;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;\red124\green252\blue0;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f0\cf0 \cf0\ql{\f0 {\ltrch This is }{\highlight2\ltrch really }{\ltrch dumb. }\li0\ri0\sa0\sb0\fi0\ql\par} } }

So how do I process this rich text so I can insert it into my Word file using Xceed's DocX library?

So far I've tried using the Clibboard as described here but I'm not sure if I'm copying the text correctly or how I go about applying the pasted content. I'm also trying to use DocX's InsertParagraph but that just looks like it appends a paragraph to the document (and I still haven't solved the formatting issue). Any help would be much appreciated.

1
It's not worth the trouble. Dump DocX and pickup Open XML SDK.dadiletta

1 Answers

0
votes

If you want to replace tags by values, I recommend you to use a "templating engine" for docx. I happen to have created one myself : https://github.com/open-xml-templating/docxtemplater

With the open-source version, you will mostly be fine if you want to replace tags by simple text or do loops/conditions (other advanced features such as HTML insertion are paid extensions).