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

Free Support Forum - aspose.com

Can't copy paragraph from one document to Another

My code: (c#)

string dataDir = @"C:\Users\leah_b\Documents\";
string fileName = "TryingAspose.docx";
Aspose.Words.Document doc = new Aspose.Words.Document(dataDir + fileName);
Aspose.Words.Document subDoc = new Aspose.Words.Document();
var allpara = doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true);
for (int i = 0; i < allpara.Count; i++)
{
    if (((Paragraph)allpara[i]).ParagraphFormat.OutlineLevel == OutlineLevel.Level1)
    {
        subDoc.Save(@"C:\Users\leah_b\Documents\a\" + i + ".docx");
        subDoc.RemoveAllChildren();
        subDoc.AppendChild(subDoc.ImportNode(allpara[i], true, ImportFormatMode.KeepSourceFormatting));
    }
    else
    {
        subDoc.AppendChild(subDoc.ImportNode(allpara[i], true, ImportFormatMode.KeepSourceFormatting));
    }
}

returns error: cannot insert a node of this type at this location

@leahb you are trying to append the paragraph direct in the root of the document, the lower level allowed in where a paragraph could be is in the Body of a Section, for that reason when you create a new Document it contains by default a Section with a Body. To solve your issue, please try the following code:

string dataDir = @"C:\Temp\";
string fileName = "TryingAspose.docx";
Aspose.Words.Document doc = new Aspose.Words.Document(dataDir + fileName);
Aspose.Words.Document subDoc = new Aspose.Words.Document();
NodeImporter importer = new NodeImporter(doc, subDoc, ImportFormatMode.KeepSourceFormatting);
int index = 1;
foreach (Paragraph node in doc.GetChildNodes(NodeType.Paragraph, true))
{
    Node importNode = importer.ImportNode(node, true);

    if (node.ParagraphFormat.OutlineLevel == OutlineLevel.Level1)
    {
        subDoc.Save(@"C:\Temp\output_" + index++ + ".docx");
        subDoc.FirstSection.Body.RemoveAllChildren();
    }
    
    subDoc.FirstSection.Body.AppendChild(importNode);
}

subDoc.Save(@"C:\Temp\output_" + index + ".docx");

As a sidenote, please try to not post relevant data as Usernames in public forums (see loading and saving addresses), all the files that you upload are only visible for the Aspose Support Team, but the text in your post is visible for everyone.