DaveDev
DaveDev

Reputation: 42175

How to prevent new lines appearing after inserting Paragraphs with OpenXML?

I'm trying to insert text into Bookmarks in an OpenXML .docx file, but it's inserting a new line after each Paragraph. How can I prevent this?

e.g.: enter image description here

I add the text to the document by finding the Bookmarks with the following:

var bmk= body.Descendants<BookmarkStart>().FirstOrDefault(xx => xx.Name == "myBMK");
var parent = bmk.Parent;

parent.InsertBeforeSelf(GetText("DaveCompany"));

where GetText is defined as:

public static Paragraph GetText(string cellText)
{
    var run = new Run(new Text(cellText));

    return new Paragraph(run);
}

I've tried stripping the text out of a Paragraph, e.g.

    parent.InsertBeforeSelf(new Run(new Text("DaveCompany")));

but that produced an invalid document.

How can I prevent the new line from being inserted?

Upvotes: 0

Views: 2270

Answers (1)

DaveDev
DaveDev

Reputation: 42175

It turns out it was adding the extra line because the Bookmark was in its own paragraph. When I added the new paragraph with

parent.InsertBeforeSelf(GetText("DaveCompany"));

The container table cell had 2 paragraphs in it, and the document displayed this as it effectively should have.

The solution is to remove the bookmark's parent paragraph after I have inserted the text, e.g.

var bmk= body.Descendants<BookmarkStart>().FirstOrDefault(xx => xx.Name == "myBMK");
var parent = bmk.Parent;

parent.InsertBeforeSelf(GetText("DaveCompany"));
parent.Remove();

Upvotes: 1

Related Questions