Problem when importing a document to replace a bookmark

Hello,

I want to replace a bookmark by the entire content of a document.

I use this code finded on this forum, it’s coded in C# at the base but i have simply converted it to Java without logic modification :
----

Node node = documentBuilder.getCurrentNode();
Section insertedSection = null;
int index = 0;
if (node.getAncestor(Cell.class) != null || node.getAncestor(Shape.class) != null) {
    // Insertion point is tracked to Cell or Shape level:
    // - insert appended document on node by node basis.
    index = node.getParentNode().getChildNodes().indexOf(node);
    for (int j = 0; j < nestedDocument.getSections().getCount(); j++) {
        Section section = nestedDocument.getSections().get(j);
        for (Node sourceNode : section.getBody().getChildNodes()) {
            // Only Paragraph or Table nodes can be inserted
            // into Cell or Shape
            if ((sourceNode instanceof Paragraph) || (sourceNode instanceof Table)) {
                // Do not insert node if it is a last empty
                // paragarph in the section.
                if ((sourceNode instanceof Paragraph)
                        && sourceNode == section.getBody().getLastChild())
                    break;
                Node insertedNode = document.importNode(sourceNode, true,
                        ImportFormatMode.KEEP_SOURCE_FORMATTING);
                node.getParentNode().getChildNodes().insert(index++, insertedNode);
            }
        }
    }
} else {
    // Insertion point is tracked to Section.Body level:
    // - insert appended document on section by section
    // basis.
    Section dstSection = null;
    Body body = (Body) node.getAncestor(Body.class);
    if (body.getLastChild() != node) {
        DocumentBuilder builder = new DocumentBuilder(document);
        builder.moveTo(node);
        builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
        dstSection = builder.getCurrentParagraph().getParentSection();
    } else {
        dstSection = (Section) node.getAncestor(Section.class);
    }
    index = document.getSections().indexOf(dstSection);
    int index0 = index;
    for (int k = 0; k < nestedDocument.getSections().getCount(); k++) {
        Section section = nestedDocument.getSections().get(k);
        insertedSection = (Section) document.importNode(section, true,
                ImportFormatMode.KEEP_SOURCE_FORMATTING);
        // Uncomment this line if you want to get rid of
        // headers/footers in the inserted section
        insertedSection.clearHeadersFooters();
        document.getSections().insert(index++, insertedSection);
    }
    document.getSections().get(index0).getPageSetup().setSectionStart(SectionStart.CONTINUOUS);
}
// Delete the bookmark

document.getRange().getBookmarks().get(bookmarkReplacementSetting.getName()).remove();

----
In the above code :

  • nestedDocument is the Document object that i want to import
  • document is the current document that will receive the content of the nestedDocument variable
  • bookmarkReplacementSetting.getName() return the name of the bookmark to replace

When is check in debug mode the sections of the nestedDocument variable are imported in the document variable BUT when i save the target document to a file and i open it i didn’t see the imported content and the bookmark it still present…

Note : When i display the content of document.getText() the content of the document is present.

Thanks in advance.

Dominique Righetto

Hi
Thanks for your inquiry. I tested your code on my side and it seems that all works fine. Could you please attach your documents for testing?
Also I think that the following method could be useful for you. See the following thread:
https://forum.aspose.com/t/106758
Just change the following line

builder.moveToMergeField(mergeFieldName);

to

builder.moveToBookmark(bookmarkName);

and this code will work for you.
Best regards.

Hello,

First thanks for the quickly response.

I have tested the method but i have the same problem.

In attach you will find 2 samples A & C, my test is to replace the bookmark TYPE_ENVOI in the sample file A with the content of the sample file C.

I use the v2.42 of Aspose.Words for Java with a JDK 1.5.x

It seem also that the method throw a Exception when the source document to import contains Table because it try to cast a Table objet to a Paragraph and the method only manage Paragraph

Thanks in advance.

Dominique Righetto

Hi
Thanks you for additional information. You can’t see the inserted document because the document was inserted into the field. (press Alt+F9 to see its content). To workaround this you can use the following code for moving cursor to the field end.

// Move cursor to the bookmark
documentBuilder.moveToBookmark("TYPE_ENVOI");
// Move cursor to the end of field
while (documentBuilder.getCurrentNode().getNodeType() != NodeType.FIELD_END)
{
    documentBuilder.moveTo(documentBuilder.getCurrentNode().getNextSibling());
}
documentBuilder.moveTo(documentBuilder.getCurrentNode().getNextSibling());
And the following code for removing field from the document.
Node currentNode = document.getRange().getBookmarks().get("TYPE_ENVOI").getBookmarkStart();
// Search for field strat
while (currentNode.getNodeType() != NodeType.FIELD_START)
{
    currentNode = currentNode.getPreviousSibling();
}
// Remove whole field
while (currentNode.getNodeType() != NodeType.FIELD_END)
{
    currentNode = currentNode.getNextSibling();
    currentNode.getPreviousSibling().remove();
}
currentNode.remove();

I hope this could help you.
Best regards.

Thanks for this answer. It seem also that the method throw a Exception when the source document
to import contains Table because it try to cast a Table objet to a
Paragraph and the method only manage Paragraph

I have updated the method initialy found on this forum with your informations to remove field and now all work fine…

I post below the final method in order to help if someone encounter the same “problem” :

/**
    * Method to insert a document at the position of a bookmark
    *
    * @param bookmarkName Bookmark name
    * @param document Target document
    * @param nestedDocument Source document
    * @throws Exception
    */
publicvoid insertDocumentAtBookmarkPosition(String bookmarkName, Document document, Document nestedDocument)
        throws Exception {

    // Check input parameters
    if (StringUtils.isEmpty(bookmarkName) || document == null || nestedDocument == null) {
        throw new PWEException("All parameters cannot be null or empty !");
    }
    // Create DocumentBuilder for the target document
    DocumentBuilder documentBuilder = new DocumentBuilder(document);

    /**
        * Move to the position after the bookmark, note that a FormField is
        * associated wit each bookmark
        */
    // Move cursor to the bookmark
    if (!documentBuilder.moveToBookmark(bookmarkName)) {
        throw new PWEException("Target bookmark '" + bookmarkName + "’ cannot be found in file '"
                + document.getOriginalFileName() + "’");
    }
    // Move cursor to the end of field
    while (documentBuilder.getCurrentNode().getNodeType() != NodeType.FIELD_END) {
        documentBuilder.moveTo(documentBuilder.getCurrentNode().getNextSibling());
    }
    documentBuilder.moveTo(documentBuilder.getCurrentNode().getNextSibling());
    // Get the current node (the position after the bookmark)
    Node node = documentBuilder.getCurrentNode();

    /**
        * Import document by importing all nodes of the source document in
        * target document
        */
    int index = 0;
    if (node.getAncestor(Cell.class) != null || node.getAncestor(Shape.class) != null) {
        // Insertion point is tracked to Cell or Shape level:
        // - insert appended document on node by node basis.
        index = node.getParentNode().getChildNodes().indexOf(node);
        for (int j = 0; j < nestedDocument.getSections().getCount(); j++) {
            Section section = nestedDocument.getSections().get(j);
            for (Node sourceNode : section.getBody().getChildNodes()) {
                // Only Paragraph or Table nodes can be inserted
                // into Cell or Shape
                if ((sourceNode instanceof Paragraph) || (sourceNode instanceof Table)) {
                    // Do not insert node if it is a last empty
                    // paragarph in the section.
                    if ((sourceNode instanceof Paragraph) && sourceNode == section.getBody().getLastChild())
                        break;
                    Node insertedNode = document.importNode(sourceNode, true,
                            ImportFormatMode.KEEP_SOURCE_FORMATTING);
                    node.getParentNode().getChildNodes().insert(index++, insertedNode);
                }
            }
        }
    } else {
        // Insertion point is tracked to Section.Body level:
        // - insert appended document on section by section
        // basis.
        Section dstSection = null;
        Body body = (Body) node.getAncestor(Body.class);
        if (body.getLastChild() != node) {
            DocumentBuilder builder = new DocumentBuilder(document);
            builder.moveTo(node);
            builder.insertBreak(BreakType.SECTION_BREAK_CONTINUOUS);
            dstSection = builder.getCurrentParagraph().getParentSection();
        } else {
            dstSection = (Section) node.getAncestor(Section.class);
        }
        index = document.getSections().indexOf(dstSection);
        int index0 = index;
        for (int k = 0; k < nestedDocument.getSections().getCount(); k++) {
            Section section = nestedDocument.getSections().get(k);
            Section insertedSection = (Section) document.importNode(section, true,
                    ImportFormatMode.KEEP_SOURCE_FORMATTING);
            // Uncomment this line if you want to get rid of
            // headers/footers in the inserted section
            insertedSection.clearHeadersFooters();
            document.getSections().insert(index++, insertedSection);
        }
        document.getSections().get(index0).getPageSetup().setSectionStart(SectionStart.CONTINUOUS);

        /* Search to remove the field associated with the bookmark */
        Node currentNode = document.getRange().getBookmarks().get(bookmarkName).getBookmarkStart();
        // Search for field start
        while (currentNode.getNodeType() != NodeType.FIELD_START) {
            currentNode = currentNode.getPreviousSibling();
        }
        // Remove whole field
        while (currentNode.getNodeType() != NodeType.FIELD_END) {
            currentNode = currentNode.getNextSibling();
            currentNode.getPreviousSibling().remove();
        }
        currentNode.remove();
    }
}

For finish i would like to thanks you Alexey for your quick and precious help !!!

Best regards,
Dominique