Insert new paragraph in XWPFDocument (C# NPOI.OOXML)

Viewed 434

I am trying to use XWPFDocument.InsertNewParagraph(XmlDocument cursor) but the method is asking for XmlDocument cursor, and I don't know where to find it, or what to use.

All the documentation I have found on internet is about the Java version of the library, and says to use XWPFParagraph.getCTP().newCursor(), but there is no method named newCursor in the object returned by getCTP().

2 Answers

Looking at the source of the NPOI I found that the package didn't implement InsertNewParagraph / InsertNewTbl / IsCursorInTableCell methods of the XWPFTableCell which receives the argument type XmlDocument but the name is cursor (it is also strange). Below is my suggestion:

Call AddParagraph, create run(s) (IRun) inside it, at the end call SetParagraph instead of InsertNewParagraph.

Here's how I solved it

//Assumes it's currently the last paragraph, as in - just created
void insertParagraph(XWPFDocument doc, XWPFParagraph par, int pos)
{
    var idx = doc.GetPosOfParagraph(par);
    for (int i = idx; i > pos; i--)
    {
        doc.SetParagraph(doc.Paragraphs[i - 1],i);
    }
    doc.SetParagraph(par, pos);
}

This is intended to be called after first adding the new paragraph to the end with doc.CreateParagraph(), but the basic idea is to shift every paragraph down by one, starting from end, until the desired position. Then set the new paragraph in that position.

Related