Sunday, November 21, 2010

Using DocX to insert text into an existing document.

Maybe I'm just slow, but I found this hard to do. Here is a simple bit of code that finally did it. It seemed to me that I should have been able to use some simpler, more obvious methods to achieve this, but they just didn't work for me.


private void button1_Click(object sender, RoutedEventArgs e)
{
using (DocX doc = DocX.Load(@"..\..\Templates\source.docx"))
{

int index = FindParagraphIndexContaining("@Marker@", doc);

Paragraph p = doc.Paragraphs[index];

Paragraph p2 = p.InsertParagraphAfterSelf("");
p2.Append("Here is a new paragraph.").Font(new System.Drawing.FontFamily("Verdana")).FontSize(11);
p2.IndentationBefore = 1.0f;

p.Remove(false);

doc.SaveAs(@"..\..\Templates\saved.docx");

MessageBox.Show("Done!");
}
}

private int FindParagraphIndexContaining(string text, DocX doc)
{
int i;

for (i = 0; i < doc.Paragraphs.Count; i++)
{
if (doc.Paragraphs[i].FindAll(text).Count > 0)
{
return i;
}
}
return -1;
}