We're sorry Aspose doesn't work properply without JavaScript enabled.

# Inserting document into a specific place in a different document

I’m trying to import a document and insert it into a specific position using a place holder in a different document.

So my destination is a document like:

{{content}}

Where content is where I want to insert the paragraphs from the source document.

First I extract the content of the Source using the code found here:

so I do:
 var extractContent = ExtractDocuments.ExtractContent(body.FirstChild, body.LastChild, true);

This leaves me with a list of Paragraphs.

I then traverse to the position:

            var documentBuilder = new DocumentBuilder(destinationDoc);
documentBuilder.MoveToMergeField("Content");


and when I run:

foreach (Node node in extractContent)
{
var importedNode = importer.ImportNode(node, true);
documentBuilder.InsertNode(importedNode);
}


I get the error:

‘Cannot insert a node of this type at this location.’

I’ve tried multiple different iterations of this, with the same result. If i append it at the body it works but in the wrong place:
destinationDocument.FirstSection.Body.AppendChild(importedNode); //Works! but wrong place!

Any help would be appreciated.

@Devpoint DocumentBuilder.InsertNode methods inserts a text level node (Run, Shape etc) inside the current paragraph before the cursor. In your case you need to insert a Paragraph node. To achieve this you should use CompositeNode.InsertArter or CompositeNode.InsertBefore methods. For example see the following code:

Document doc = new Document(@"C:\Temp\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

// Create a list of paragraphs to insert. In your case you import them from another document.
List<Paragraph> paragraphs = new List<Paragraph>();
for (int i = 0; i < 5; i++)
{
Paragraph para = new Paragraph(doc);
para.AppendChild(new Run(doc, string.Format("paragraph {0}", i)));
}

builder.MoveToMergeField("content");
foreach (Paragraph para in paragraphs)
{
builder.CurrentParagraph.ParentNode.InsertBefore(para, builder.CurrentParagraph);
}

// If the paragraph where DocumentBuilder cursor was moved is empty, remove it.
if (!builder.CurrentParagraph.HasChildNodes)
builder.CurrentParagraph.Remove();

doc.Save(@"C:\Temp\out.docx");