By the help of some very kind community members here I managed to programatically create a function to replace text inside content controls in a Word document using open xml. After the document is generated it removes the formatting of the text after I replace the text.
Any ideas on how I can still keep the formatting in word and remove the content control tags ?
This is my code:
using (var wordDoc = WordprocessingDocument.Open(mem, true))
{
var mainPart = wordDoc.MainDocumentPart;
ReplaceTags(mainPart, "FirstName", _firstName);
ReplaceTags(mainPart, "LastName", _lastName);
ReplaceTags(mainPart, "WorkPhoe", _workPhone);
ReplaceTags(mainPart, "JobTitle", _jobTitle);
mainPart.Document.Save();
SaveFile(mem);
}
private static void ReplaceTags(MainDocumentPart mainPart, string tagName, string tagValue)
{
//grab all the tag fields
IEnumerable<SdtBlock> tagFields = mainPart.Document.Body.Descendants<SdtBlock>().Where
(r => r.SdtProperties.GetFirstChild<Tag>().Val == tagName);
foreach (var field in tagFields)
{
//remove all paragraphs from the content block
field.SdtContentBlock.RemoveAllChildren<Paragraph>();
//create a new paragraph containing a run and a text element
Paragraph newParagraph = new Paragraph();
Run newRun = new Run();
Text newText = new Text(tagValue);
newRun.Append(newText);
newParagraph.Append(newRun);
//add the new paragraph to the content block
field.SdtContentBlock.Append(newParagraph);
}
}
Text
, the text is not added to the document file, but single value texts are added and they keep the style they got. Any idea how I can keep multi text value text added also with the style intact? – Ilyas Mar 17 '15 at 07:50some awsome text
Yo yo
. I tried to remove the html-encoding, but then of course it will all come in the same line without the paragraph, so trying to sort out how to have html-encoded text without showing the html-tags.
– Ilyas Mar 17 '15 at 15:42element you have create a new `Paragraph`, `Run` and `Text`. You can use `InsertAfter` to insert each paragraph after the previous one. If you assign the `RunProperties` to each `Run` you'll keep your styles as well.
– petelids Mar 17 '15 at 17:43