Inserting one document into another at a bookmark

Here is subdoc1.doc.

Hi
Thanks you for additional information. This occurs because your subdocument contains only one paragraph. This was my mistake, sorry for that. Please try using the following code.

Sub InsertDocumentAtBookamrk(ByVal bookmarkName As String, ByVal dstDoc As Document, ByVal srcDoc As Document)
'Create DocumentBuilder
Dim builder As DocumentBuilder = New DocumentBuilder(dstDoc)
'Move cursor to bookmark and insert paragraph break
builder.MoveToBookmark(bookmarkName)
builder.Writeln()
'Content of srcdoc will be inserted after this node
Dim insertAfterNode As Node = builder.CurrentParagraph.PreviousSibling
'Content of first paragraph of srcDoc will be apended to this parafraph
Dim insertAfterParagraph As Paragraph = CType(insertAfterNode, Paragraph)
'Content of last paragraph of srcDoc will be apended to this parafraph
Dim insertBeforeParagraph As Paragraph = builder.CurrentParagraph
'We will be inserting into the parent of the destination paragraph.
Dim dstStory As CompositeNode = insertAfterNode.ParentNode
'Remove empty paragraphs from the end of document
While (Not srcDoc.LastSection.Body.LastParagraph.HasChildNodes)
srcDoc.LastSection.Body.LastParagraph.Remove()
End While
'Loop through all sections in the source document.
Dim srcSection As Section
For Each srcSection In srcDoc.Sections
'Loop through all block level nodes (paragraphs and tables) in the body of the section.
Dim srcNode As Node
For Each srcNode In srcSection.Body
'Do not insert node if it is a last empty paragarph in the section.
Dim para As Paragraph = CType(srcNode, Paragraph)
If (Not para Is Nothing) AndAlso para.IsEndOfSection AndAlso (Not para.HasChildNodes) Then
Exit For
End If
'If current paragraph is first paragraph of srcDoc 
'then appent its content to insertAfterParagraph
If (para.Equals(srcDoc.FirstSection.Body.FirstParagraph)) Then
Dim node As Node
For Each node In para.ChildNodes
Dim dstNode As Node = dstDoc.ImportNode(node, True, ImportFormatMode.KeepSourceFormatting)
insertAfterParagraph.AppendChild(dstNode)
Next
'If subdocument contains only one paragraph 
'then copy content of insertBeforeParagraph to insertAfterParagraph
'and remove insertBeforeParagraph
If (srcDoc.FirstSection.Body.FirstParagraph.Equals(srcDoc.LastSection.Body.LastParagraph)) Then
While (insertBeforeParagraph.HasChildNodes)
insertAfterParagraph.AppendChild(insertBeforeParagraph.FirstChild)
End While
insertBeforeParagraph.Remove()
End If
'If current paragraph is last paragraph of srcDoc 
'then appent its content to insertBeforeParagraph
ElseIf (para.Equals(srcDoc.LastSection.Body.LastParagraph)) Then
Dim previouseNode As Node
Dim node As Node
For Each node In para.ChildNodes
Dim dstNode As Node = dstDoc.ImportNode(node, True, ImportFormatMode.KeepSourceFormatting)
If (previouseNode Is Nothing) Then
insertBeforeParagraph.InsertBefore(dstNode, insertBeforeParagraph.FirstChild)
Else
insertBeforeParagraph.InsertAfter(dstNode, previouseNode)
End If
previouseNode = dstNode
Next
Else
'This creates a clone of the node, suitable for insertion into the destination document.
Dim newNode As Node = dstDoc.ImportNode(srcNode, True, ImportFormatMode.KeepSourceFormatting)
'Insert new node after the reference node.
dstStory.InsertAfter(newNode, insertAfterNode)
insertAfterNode = newNode
End If
Next
Next
End Sub

Best regards.

Alexey, thank you, thank you, THANK YOU!!! It works perfectly now!
You’re awesome! Thank you SO much for your help!
Cheers!
C.

Can you provide this function by JAVA code ?
I’m force this issue, Please help …
Thanks

Hi
Thanks for your request. Please try using the following code:

public static void InsertDocumentAtBookmark(String bookmarkName, Document dstDoc, Document srcDoc) throws Exception
{
    // Create DocumentBuilder
    DocumentBuilder builder = new DocumentBuilder(dstDoc);
    // Move cursor to bookmark and insert paragraph break
    builder.moveToBookmark(bookmarkName);
    builder.writeln();
    // Content of srcdoc will be inserted after this node
    Node insertAfterNode = builder.getCurrentParagraph().getPreviousSibling();
    // Content of first paragraph of srcDoc will be apended to this parafraph
    Paragraph insertAfterParagraph = (Paragraph)insertAfterNode;
    // Content of last paragraph of srcDoc will be apended to this parafraph
    Paragraph insertBeforeParagraph = builder.getCurrentParagraph();
    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.getParentNode();
    // Create temporary list
    List srcTmpList = null;
    List dstTmpList = null;
    // Remove empty paragraphs from the end of document
    while (!srcDoc.getLastSection().getBody().getLastParagraph().hasChildNodes())
    {
        srcDoc.getLastSection().getBody().getLastParagraph().remove();
    }
    // Loop through all sections in the source document.
    int sectCount = srcDoc.getSections().getCount();
    for(int sectIndex=0; sectIndex<sectCount; sectIndex++)
                                                {
                                                Section srcSection=srcDoc.getSections().get(sectIndex);
                                                // Loop through all block level nodes (paragraphs and tables) in the body of the section.
                                                int nodeCount=srcSection.getBody().getChildNodes().getCount();
                                                for(int nodeIndex=0; nodeIndex<nodeCount; nodeIndex++)
        {
            Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
            // Do not insert node if it is a last empty paragarph in the section.
            Paragraph para = (Paragraph)srcNode ;
            if ((para != null) && para.isEndOfSection() && (!para.hasChildNodes()))
            {
                break;
            }
            // If current paragraph is first paragraph of srcDoc
            // then appent its content to insertAfterParagraph
            if (para.equals(srcDoc.getFirstSection().getBody().getFirstParagraph()) && insertAfterParagraph.hasChildNodes())
            {
                int firstParaChildCount = para.getChildNodes().getCount();
                for(int childIndex = 0; childIndex<firstParaChildCount; childIndex++)
                {
                    Node node = para.getChildNodes().get(childIndex);
                    Node dstNode = dstDoc.importNode(node, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                    insertAfterParagraph.appendChild(dstNode);
                }
                // If subdocument contains only one paragraph
                // then copy content of insertBeforeParagraph to insertAfterParagraph
                // and remove insertBeforeParagraph
                if (srcDoc.getFirstSection().getBody().getFirstParagraph().equals(srcDoc.getLastSection().getBody().getLastParagraph()))
                {
                    while (insertBeforeParagraph.hasChildNodes())
                    {
                        insertAfterParagraph.appendChild(insertBeforeParagraph.getFirstChild());
                    }
                    insertBeforeParagraph.remove();
                }
            }
            // If current paragraph is last paragraph of srcDoc
            // then appent its content to insertBeforeParagraph
            else if (para.equals(srcDoc.getLastSection().getBody().getLastParagraph()) && insertBeforeParagraph.hasChildNodes())
            {
                Node previouseNode = null;
                int firstParaChildCount = para.getChildNodes().getCount();
                for(int childIndex = 0; childIndex<firstParaChildCount; childIndex++)
                {
                    Node node = para.getChildNodes().get(childIndex);
                    Node dstNode = dstDoc.importNode(node, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                    if (previouseNode == null)
                    {
                        insertBeforeParagraph.insertBefore(dstNode, insertBeforeParagraph.getFirstChild());
                    }
                    else
                    {
                        insertBeforeParagraph.insertAfter(dstNode, previouseNode);
                    }
                    previouseNode = dstNode;
                }
            }
            else
            {
                // This creates a clone of the node, suitable for insertion into the destination document.
                Node newNode = dstDoc.importNode(srcNode, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                if(srcNode.getNodeType() == NodeType.PARAGRAPH)
                {
                    Paragraph srcTmpPar = (Paragraph)srcNode;
                    Paragraph dstTmpPar = (Paragraph)newNode;
                    if(srcTmpPar.getListFormat().getList()==srcTmpList)
                    {
                        dstTmpPar.getListFormat().setList(dstTmpList);
                    }
                    else
                    {
                        srcTmpList = srcTmpPar.getListFormat().getList();
                        dstTmpList = dstTmpPar.getListFormat().getList();
                    }
                }
                // Insert new node after the reference node.
                dstStory.insertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
        if(!insertAfterParagraph.hasChildNodes())
            insertAfterParagraph.remove();
        if(!insertBeforeParagraph.hasChildNodes())
            insertBeforeParagraph.remove();
    }
}

Best regards.

Thanks a lot …
But this method i discover some issue, when my srcDoc document file have “Table”.
It will return below exception.
com.aspose.words.Table cannot be cast to com.aspose.words.Paragraph

Can you help to fix this?
.

Hi
Thanks for your request. Please try using the following code.

public static void InsertDocumentAtBookmark(String bookmarkName, Document dstDoc, Document srcDoc) throws Exception
{
    // Create DocumentBuilder
    DocumentBuilder builder = new DocumentBuilder(dstDoc);
    // Move cursor to bookmark and insert paragraph break
    builder.moveToBookmark(bookmarkName);
    builder.writeln();
    // Content of srcdoc will be inserted after this node
    Node insertAfterNode = builder.getCurrentParagraph().getPreviousSibling();
    // Content of first paragraph of srcDoc will be apended to this parafraph
    Paragraph insertAfterParagraph = null;
    if(insertAfterNode.getNodeType() == NodeType.PARAGRAPH)
        insertAfterParagraph = (Paragraph)insertAfterNode;
    // Content of last paragraph of srcDoc will be apended to this parafraph
    Paragraph insertBeforeParagraph = builder.getCurrentParagraph();
    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.getParentNode();
    // Remove empty paragraphs from the end of document
    while (!((CompositeNode)srcDoc.getLastSection().getBody().getLastChild()).hasChildNodes())
    {
        srcDoc.getLastSection().getBody().getLastParagraph().remove();
        if (srcDoc.getLastSection().getBody().getLastChild() == null)
            break;
    }
    // Loop through all sections in the source document.
    for(Section srcSection : srcDoc.getSections())
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        for (int nodeIdx=0; nodeIdx<srcSection.getBody().getChildNodes().getCount(); nodeIdx++)
                                                                                        {
                                                                                        Node srcNode=srcSection.getBody().getChildNodes().get(nodeIdx);
                                                                                        // Do not insert node if it is a last empty paragarph in the section.
                                                                                        Paragraph para=null;
                                                                                        if(srcNode.getNodeType()= =NodeType.PARAGRAPH)
                                                                                        para=(Paragraph)srcNode;
                                                                                        if ((para !=null) && para.isEndOfSection() && (!para.hasChildNodes()))
                                                                                        break;
                                                                                        // If current paragraph is first paragraph of srcDoc
                                                                                        // then appent its content to insertAfterParagraph
                                                                                        if (para !=null && para.equals(srcDoc.getFirstSection().getBody().getFirstChild()))
                                                                                        {
                                                                                        for (int i=0; i<para.getChildNodes().getCount(); i++)
                {
                    Node node = para.getChildNodes().get(i);
                    Node dstNode = dstDoc.importNode(node, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                    insertAfterParagraph.appendChild(dstNode);
                }
                // If subdocument contains only one paragraph
                // then copy content of insertBeforeParagraph to insertAfterParagraph
                // and remove insertBeforeParagraph
                if (srcDoc.getFirstSection().getBody().getFirstParagraph().equals(srcDoc.getLastSection().getBody().getLastChild()))
                {
                    while (insertBeforeParagraph.hasChildNodes())
                        insertAfterParagraph.appendChild(insertBeforeParagraph.getFirstChild());
                    insertBeforeParagraph.remove();
                }
            }
            // If current paragraph is last paragraph of srcDoc
            // then appent its content to insertBeforeParagraph
            if (para != null && para.equals(srcDoc.getLastSection().getBody().getLastChild()))
            {
                Node previouseNode = null;
                for (int i=0; i<para.getChildNodes().getCount(); i++)
                {
                    Node node = para.getChildNodes().get(i);
                    Node dstNode = dstDoc.importNode(node, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                    if (previouseNode == null)
                        insertBeforeParagraph.insertBefore(dstNode, insertBeforeParagraph.getFirstChild());
                    else
                        insertBeforeParagraph.insertAfter(dstNode, previouseNode);
                    previouseNode = dstNode;
                }
            }
            else
            {
                // This creates a clone of the node, suitable for insertion into the destination document.
                Node newNode = dstDoc.importNode(srcNode, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                // Insert new node after the reference node.
                dstStory.insertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
    }
}

Hope this helps.
Best regards.

Hi alexey.noskov

I use your provide function to append document.
I discover have one minor issue, Can you help to fix this.

When srcDoc words/image no on any table, then append on the dest doc. Then the result will be incorrect.

Hi

Thanks for your request. Please attach your sample documents here for testing. I will investigate the issue and provide you more information.
Also, it would be great if you create simple application that will demonstrate the problem.
Best regards.

Hi Alexey!
It’s been over a year since I last talked to you and I’ve been using your InsertDocumentAtBookmark subroutine contiunally since then without any problems. However, now I have the need to also programmatically control the format of the document being inserted at the bookmark. I want to add an additional parameter to the subroutine call that contains a string of formatting information, e.g. “Bold,Italic,Underline”, and then within the subroutine, set the format of the text being inserted accordingly.
I have modified your InsertDocumentAtBookmark as below (my additions are shown below in purple):

Sub InsertDocumentAtBookmark(ByVal bookmarkName As String, ByVal dstDoc As Document, ByVal srcDoc As Document, ByVal strBookMarkStyle As String)
'Create DocumentBuilder
Dim builder As DocumentBuilder = New DocumentBuilder(dstDoc)
'Move cursor to bookmark and insert paragraph break
builder.MoveToBookmark(bookmarkName)
If InStr(strBookMarkStyle, "Bold") Then
builder.Bold = True
End If
If InStr(strBookMarkStyle, "Italic") Then
builder.Italic = True
End If
If InStr(strBookMarkStyle, "Underline") Then
builder.Underline = True
End If
builder.Writeln()
'Content of srcdoc will be inserted after this node
Dim insertAfterNode As Node = builder.CurrentParagraph.PreviousSibling
'Content of first paragraph of srcDoc will be apended to this parafraph
Dim insertAfterParagraph As Paragraph = CType(insertAfterNode, Paragraph)
'Content of last paragraph of srcDoc will be apended to this parafraph
Dim insertBeforeParagraph As Paragraph = builder.CurrentParagraph
'We will be inserting into the parent of the destination paragraph.
Dim dstStory As CompositeNode = insertAfterNode.ParentNode
'Remove empty paragraphs from the end of document
While (Not srcDoc.LastSection.Body.LastParagraph.HasChildNodes)
srcDoc.LastSection.Body.LastParagraph.Remove()
End While
'Loop through all sections in the source document.
Dim srcSection As Section
For Each srcSection In srcDoc.Sections
'Loop through all block level nodes (paragraphs and tables) in the body of the section.
Dim srcNode As Node
For Each srcNode In srcSection.Body
'Do not insert node if it is a last empty paragarph in the section.
Dim para As Paragraph = CType(srcNode, Paragraph)
If (Not para Is Nothing) AndAlso para.IsEndOfSection AndAlso (Not para.HasChildNodes) Then
Exit For
End If
'If current paragraph is first paragraph of srcDoc 
'then appent its content to insertAfterParagraph
If (para.Equals(srcDoc.FirstSection.Body.FirstParagraph)) Then
Dim node As Node
For Each node In para.ChildNodes
Dim dstNode As Node = dstDoc.ImportNode(node, True, ImportFormatMode.KeepSourceFormatting)
insertAfterParagraph.AppendChild(dstNode)
Next
'If subdocument contains only one paragraph 
'then copy content of insertBeforeParagraph to insertAfterParagraph
'and remove insertBeforeParagraph
If (srcDoc.FirstSection.Body.FirstParagraph.Equals(srcDoc.LastSection.Body.LastParagraph)) Then
While (insertBeforeParagraph.HasChildNodes)
insertAfterParagraph.AppendChild(insertBeforeParagraph.FirstChild)
End While
insertBeforeParagraph.Remove()
End If
'If current paragraph is last paragraph of srcDoc 
'then appent its content to insertBeforeParagraph
ElseIf (para.Equals(srcDoc.LastSection.Body.LastParagraph)) Then
Dim previouseNode As Node
Dim node As Node
For Each node In para.ChildNodes
Dim dstNode As Node = dstDoc.ImportNode(node, True, ImportFormatMode.KeepSourceFormatting)
If (previouseNode Is Nothing) Then
insertBeforeParagraph.InsertBefore(dstNode, insertBeforeParagraph.FirstChild)
Else
insertBeforeParagraph.InsertAfter(dstNode, previouseNode)
End If
previouseNode = dstNode
Next
Else
'This creates a clone of the node, suitable for insertion into the destination document.
Dim newNode As Node = dstDoc.ImportNode(srcNode, True, ImportFormatMode.KeepSourceFormatting)
'Insert new node after the reference node.
dstStory.InsertAfter(newNode, insertAfterNode)
insertAfterNode = newNode
End If
Next
Next
End Sub

I thought that setting the properties of the DocumentBuilder object would control the format of the inserted text, but it doesn’t seem to work for me. The inserted text remains as it is in the source document.
Any help you can give would be most appreciated.
Thanks very much!

Hi

Thanks for your request. To achieve this, I think, you should change font of the entire source document and then insert it into the destination document at bookmark. The best way to change font in the entire document, I think, is using DocumentVisitor. Here is simple example:

// Open source document
Document doc = new Document(@"Test200\in.doc");
// Create visitor that will change font in the docuemnt
// After processing font in the output document will be Bold Arial 24
FontChanger changer = new FontChanger("Arial", 24, true);
// Accept visitor
doc.Accept(changer);
// Save output document
doc.Save(@"Test200\out.doc");

FontChanger class is attached.
Best regards.

Hi Alexey,
Thanks so much for this! It’s exactly what I need. I wasn’t aware of the DocumentVisitor object, but it does exactly what I need it to do. I’ve even extended your sample class to allow me to set italics and underlining in addition to bolding and changing the font name and size.
So, thanks again, very much.
Cheers!

Hi Alexey,
I’m using your Java method insertDocumentAtBookmark.
I’ve noticed one problem. When the destination bookmark is on the list then the following paragraphs from source document are inserted as new positions on the list.
Can you modify the method to solve this problem ?

Thank you in advance.

Here is my code:

Document dest = new Document("E:\DEST.doc");
Document src = new Document("E:\SRC.doc");
dest.getRange().getBookmarks().get("bookmark").setText("");
insertDocumentAtBookmark("bookmark", dest, src); 
dest.save("E:\dest_result.doc");

I’m attaching these documents and expected result.

Hi
Thanks for your request. To get the expected result you should add the highlighted lined into your code:

public static void insertDocumentAtBookmark(String bookmarkName, Document dstDoc, Document srcDoc) throws Exception
{
    // Create DocumentBuilder
    DocumentBuilder builder = new DocumentBuilder(dstDoc);
    // Move cursor to bookmark and insert paragraph break
    builder.moveToBookmark(bookmarkName);
    builder.writeln();
    // If current paragraph is a list item, we should clear its formating.
    if(builder.getCurrentParagraph().isListItem())
        builder.getListFormat().removeNumbers();
    // Content of srcdoc will be inserted after this node
    Node insertAfterNode = builder.getCurrentParagraph().getPreviousSibling();
    // Content of first paragraph of srcDoc will be apended to this parafraph
    Paragraph insertAfterParagraph = null;
    if(insertAfterNode.getNodeType() == NodeType.PARAGRAPH)
        insertAfterParagraph = (Paragraph)insertAfterNode;
    // Content of last paragraph of srcDoc will be apended to this parafraph
    Paragraph insertBeforeParagraph = builder.getCurrentParagraph();
    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.getParentNode();
    // Remove empty paragraphs from the end of document
    while (!((CompositeNode)srcDoc.getLastSection().getBody().getLastChild()).hasChildNodes())
    {
        srcDoc.getLastSection().getBody().getLastParagraph().remove();
        if (srcDoc.getLastSection().getBody().getLastChild() == null)
            break;
    }
    // Loop through all sections in the source document.
    for(Section srcSection : srcDoc.getSections())
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        for (int nodeIdx=0; nodeIdx<srcSection.getBody().getChildNodes().getCount(); nodeIdx++)
                                                                                        {
                                                                                        Node srcNode=srcSection.getBody().getChildNodes().get(nodeIdx);
                                                                                        // Do not insert node if it is a last empty paragarph in the section.
                                                                                        Paragraph para=null;
                                                                                        if(srcNode.getNodeType()= =NodeType.PARAGRAPH)
                                                                                        para=(Paragraph)srcNode;
                                                                                        if ((para !=null) && para.isEndOfSection() && (!para.hasChildNodes()))
                                                                                        break;
                                                                                        // If current paragraph is first paragraph of srcDoc
                                                                                        // then appent its content to insertAfterParagraph
                                                                                        boolean nodeInserted=false;
                                                                                        if (para !=null && para.equals(srcDoc.getFirstSection().getBody().getFirstChild()))
                                                                                        {
                                                                                        nodeInserted=true; // set this flag to know that we already processed this node.
                                                                                        for (int i=0; i<para.getChildNodes().getCount(); i++)
                {
                    Node node = para.getChildNodes().get(i);
                    Node dstNode = dstDoc.importNode(node, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                    insertAfterParagraph.appendChild(dstNode);
                }
                // If subdocument contains only one paragraph
                // then copy content of insertBeforeParagraph to insertAfterParagraph
                // and remove insertBeforeParagraph
                if (srcDoc.getFirstSection().getBody().getFirstParagraph().equals(srcDoc.getLastSection().getBody().getLastChild()))
                {
                    while (insertBeforeParagraph.hasChildNodes())
                        insertAfterParagraph.appendChild(insertBeforeParagraph.getFirstChild());
                    insertBeforeParagraph.remove();
                }
            }
            // If current paragraph is last paragraph of srcDoc
            // then appent its content to insertBeforeParagraph
            if (para != null && para.equals(srcDoc.getLastSection().getBody().getLastChild()))
            {
                nodeInserted = true; // set this flag to know that we already processed this node.
                Node previouseNode = null;
                for (int i=0; i<para.getChildNodes().getCount(); i++)
                {
                    Node node = para.getChildNodes().get(i);
                    Node dstNode = dstDoc.importNode(node, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                    if (previouseNode == null)
                        insertBeforeParagraph.insertBefore(dstNode, insertBeforeParagraph.getFirstChild());
                    else
                        insertBeforeParagraph.insertAfter(dstNode, previouseNode);
                    previouseNode = dstNode;
                }
            }
            if(!nodeInserted)
            {
                System.out.println(nodeIdx);
                // This creates a clone of the node, suitable for insertion into the destination document.
                Node newNode = dstDoc.importNode(srcNode, true, ImportFormatMode.KEEP_SOURCE_FORMATTING);
                // Insert new node after the reference node.
                dstStory.insertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
    }
}

Hope this helps.
Best regards,

Hi
Thanks for the C# sample.
Is there a way to remove the inserted line (builder.WriteLn() after inserting the other document?

My code:

builder.MoveToDocumentStart();
builder.InsertParagraph();
var previousSibling = builder.CurrentParagraph.PreviousSibling;
this.InsertDocument(previousSibling, dataDocument);
previousSibling.Remove();

builder.MoveToDocumentEnd();
builder.InsertParagraph();
previousSibling = builder.CurrentParagraph.PreviousSibling;
this.InsertDocument(previousSibling, dataDocument);
previousSibling.Remove();

builder.MoveToBookmark(BookmarkName);
builder.Writeln();
previousSibling = builder.CurrentParagraph;
this.InsertDocument(builder.CurrentParagraph.PreviousSibling, dataDocument);
// previousSibling.Remove();

As you see for inserting the document at the beginning or end I could manage it with removing the paragraph after inserting.

Thanks in advance

Martin

Hi Martin,
Thanks for your request. I am not sure why you need to remove this paragraph. The paragraph that that is inserted by this method is not empty. Let’s suppose that we have a bookmark in the middle of some paragraph:
This is text before bookmark[mybookmark]this is text after bookmark.
After inserting a line break at the bookmark we get the following
This is text before bookmark[
]this is text after bookmark.
And when we insert content from the source document we get the following:
This is text before bookmark[This is content from source document]this is text after bookmark.
Or the following if the source document contains few paragraphs:
This is text before bookmark[This is content from source document
This is another paragraph]this is text after bookmark.
Please try using this version of the method:

public static void InsertDocumentAtBookmark(String bookmarkName, Document dstDoc, Document srcDoc)
{
    NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.UseDestinationStyles);
    // Create DocumentBuilder
    DocumentBuilder builder = new DocumentBuilder(dstDoc);
    // Move cursor to bookmark and insert paragraph break
    builder.MoveToBookmark(bookmarkName);
    builder.Writeln();
    // If current paragraph is a list item, we should clear its formating.
    if (builder.CurrentParagraph.IsListItem)
        builder.ListFormat.RemoveNumbers();
    // Content of srcdoc will be inserted after this node
    Node insertAfterNode = builder.CurrentParagraph.PreviousSibling;
    // Content of first paragraph of srcDoc will be apended to this parafraph
    Paragraph insertAfterParagraph = null;
    if (insertAfterNode.NodeType == NodeType.Paragraph)
        insertAfterParagraph = (Paragraph)insertAfterNode;
    // Content of last paragraph of srcDoc will be apended to this parafraph
    Paragraph insertBeforeParagraph = builder.CurrentParagraph;
    // We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;
    // Remove empty paragraphs from the end of document
    while (!((CompositeNode)srcDoc.LastSection.Body.LastChild).HasChildNodes)
    {
        srcDoc.LastSection.Body.LastParagraph.Remove();
        if (srcDoc.LastSection.Body.LastChild == null)
            break;
    }
    // Loop through all sections in the source document.
    foreach (Section srcSection in srcDoc.Sections)
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        for (int nodeIdx = 0; nodeIdx < srcSection.Body.ChildNodes.Count; nodeIdx++)
        {
            Node srcNode = srcSection.Body.ChildNodes[nodeIdx];
            // Do not insert node if it is a last empty paragarph in the section.
            Paragraph para = null;
            if (srcNode.NodeType == NodeType.Paragraph)
                para = (Paragraph)srcNode;
            if ((para != null) && para.IsEndOfSection && (!para.HasChildNodes))
                break;
            // If current paragraph is first paragraph of srcDoc
            // then appent its content to insertAfterParagraph
            bool nodeInserted = false;
            if (para != null && para.Equals(srcDoc.FirstSection.Body.FirstChild))
            {
                nodeInserted = true; // set this flag to know that we already processed this node.
                for (int i = 0; i < para.ChildNodes.Count; i++)
                {
                    Node node = para.ChildNodes[i];
                    Node dstNode = importer.ImportNode(node, true);
                    insertAfterParagraph.AppendChild(dstNode);
                }
                // If subdocument contains only one paragraph
                // then copy content of insertBeforeParagraph to insertAfterParagraph
                // and remove insertBeforeParagraph
                if (srcDoc.FirstSection.Body.FirstParagraph.Equals(srcDoc.LastSection.Body.LastChild))
                {
                    while (insertBeforeParagraph.HasChildNodes)
                        insertAfterParagraph.AppendChild(insertBeforeParagraph.FirstChild);
                    insertBeforeParagraph.Remove();
                }
            }
            // If current paragraph is last paragraph of srcDoc
            // then appent its content to insertBeforeParagraph
            if (para != null && para.Equals(srcDoc.LastSection.Body.LastChild))
            {
                nodeInserted = true; // set this flag to know that we already processed this node.
                Node previouseNode = null;
                for (int i = 0; i < para.ChildNodes.Count; i++)
                {
                    Node node = para.ChildNodes[i];
                    Node dstNode = importer.ImportNode(node, true);
                    if (previouseNode == null)
                        insertBeforeParagraph.InsertBefore(dstNode, insertBeforeParagraph.FirstChild);
                    else
                        insertBeforeParagraph.InsertAfter(dstNode, previouseNode);
                    previouseNode = dstNode;
                }
            }
            if (!nodeInserted)
            {
                // This creates a clone of the node, suitable for insertion into the destination document.
                Node newNode = dstDoc.ImportNode(srcNode, true);
                // Insert new node after the reference node.
                dstStory.InsertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
    }
}

Best regards,

Thanks a lot for the code - it works as expected.

The issues you have found earlier (filed as WORDSNET-5251) have been fixed in this .NET update and this Java update.

This message was posted using Notification2Forum from Downloads module by aspose.notifier.

A post was split to a new topic: Append all child nodes including paragraphs, tables, images etc

A post was split to a new topic: Replace range between bookmarks with another range