Add paragraph, total paragraph in a page

I have a new paragraph added to my document and this paragraph ends between 2 pages, as I can do so that once the paragraph is added if it is between 2 paragraphs, insert a line break so that it does not split into 2.

@jmbeas

Thanks for your inquiry. Could you please share some more detail about your query along with input and expected output documents? We will then provide you more information about your query.

Captura.JPG (31.7 KB)

the code that I’m using

asposeDoc.updatePageLayout();
final Paragraph lastPara = asposeDoc.getLastSection().getBody().getLastParagraph();

        insertDocument(lastPara, doc, keepFormat, breakLine);

private void insertDocument(final Node insertAfterNode, final Document srcDoc,
final boolean keepSourceFormat, final boolean breakLine) throws Exception {
// Make sure that the node is either a paragraph or table.
if ((insertAfterNode.getNodeType() != NodeType.PARAGRAPH)
&& (insertAfterNode.getNodeType() != NodeType.TABLE)) {
throw new IllegalArgumentException(
“The destination node should be either a paragraph or table.”);
}

    // We will be inserting into the parent of the destination paragraph.
    final CompositeNode<?> dstStory = insertAfterNode.getParentNode();

    // This object will be translating styles and lists during the import.
    int format = ImportFormatMode.KEEP_SOURCE_FORMATTING;
    if (!keepSourceFormat) {
        format = ImportFormatMode.KEEP_DIFFERENT_STYLES;
    }

    srcDoc.getFirstSection().getPageSetup().setSectionStart(SectionStart.CONTINUOUS);

    final NodeImporter importer =
            new NodeImporter(srcDoc, insertAfterNode.getDocument(), format);

    Node currentNode = insertAfterNode;

    // Loop through all sections in the source document.
    for (final Section srcSection : srcDoc.getSections()) {
        // Loop through all block level nodes (paragraphs and tables) in the body of the
        // section.
        for (final Node srcNode : srcSection.getBody()) {
            // Let's skip the node if it is a last empty paragraph in a section.
            final boolean isList = false;

            if (srcNode.getNodeType() == (NodeType.PARAGRAPH)) {
                final Paragraph para = (Paragraph) srcNode;

                // TODO 30/08/2017 Se comenta esto para mantener el formato y que no borre las
                // listas que van contenidas en un parrafo.
                // isList = para.isListItem();

                if (para.isEndOfSection() && !para.hasChildNodes()) {
                    continue;
                }
            }

            // This creates a clone of the node, suitable for insertion into the destination
            // document.
            final Node newNode = importer.importNode(srcNode, true);

            // Insert new node after the reference node
            dstStory.insertAfter(newNode, currentNode);

            // Este comprobacion es si se quiere borrar el salto de lineas entre parafo o entre
            // tabla
            if (breakLine && (currentNode != null)
                    && (newNode.getNodeType() == NodeType.PARAGRAPH)) {
                appendNextParagraph(currentNode);
            } else if (breakLine && (currentNode != null)
                    && (newNode.getNodeType() == NodeType.TABLE)) {
                appendNextTable(currentNode);
            }
            currentNode = newNode;
        }
    }
}

@jmbeas

Thanks for sharing the detail. We suggest you please use the DocumentBuilder.insertDocument method instead of the method you shared. If you still face problem, please attach the following resources here for testing:

  • Your input Word document.
  • Please attach the output Word file that shows the undesired behavior.
  • Please attach the expected output Word file that shows the desired behavior.
  • Please create a simple Java application ( source code without compilation errors ) that helps us to reproduce your problem on our end and attach it here for testing.

As soon as you get these pieces of information ready, we will start investigation into your issue and provide you more information. Thanks for your cooperation.

PS: To attach these resources, please zip and upload them.

Thanks for your response. In the file attached is my software for testing. In doc1.xml I want to add doc2.xml, deleting the breakline between doc1.xml and doc2.xml. Document output.xml is the file that I hope, but the test throw an exception
java.lang.IllegalArgumentException: The reference node is not a child of this node.
at com.aspose.words.CompositeNode.zzZ(Unknown Source)
at com.aspose.words.CompositeNode.insertAfter(Unknown Source)
at prueba.Main.insertDocument(Main.java:116)
at prueba.Main.main(Main.java:37)

If you need more information, please write me.
Aspose.zip (36.2 KB)

Thanks so much.

@jmbeas

Thanks for sharing the detail. We suggest you please use the DocumentBuilder.InsertDocument method as shown below. Hope this helps you.

Document doc1 = new Document(MyDir + "doc1.xml");
DocumentBuilder builder = new DocumentBuilder(doc1);
Document doc2 = new Document(MyDir + "doc2.xml");

builder.insertDocument(doc2, ImportFormatMode.KEEP_SOURCE_FORMATTING);

Hello, I have used the DocumentBuilder.InsertDocument method, but the document is different than expected it. When I run the code
public static void main(final String[] args) {
try {
final Document doc1 = getDocument(“doc1.xml”);
final Document doc2 = getDocument(“doc2.xml”);

        final DocumentBuilder builder = new DocumentBuilder(doc1);
        builder.insertDocument(doc2, ImportFormatMode.KEEP_SOURCE_FORMATTING);

        // Save the document in tmp directory.
        try (FileOutputStream oStream = new FileOutputStream(
                File.createTempFile("outputMain", ".xml", new File("C:\\tmp")))) {
            final SaveOptions options =
                    SaveOptions.createSaveOptions(com.aspose.words.SaveFormat.WORD_ML);
            doc1.updatePageLayout();
            doc1.save(oStream, options);
        }
    } catch (final Exception ex) {
        ex.printStackTrace();
    }
}

I obtain the file “outputMain.xml” but I hope the file “outputHope.xml”. test.zip (26.0 KB)

I would like to delete the line break between both documents when “doc2.xml” is inserted in “doc1.xml”.

Thanks so much.

@jmbeas

In your case, we suggest you following solution.

  1. Insert the bookmark at the end of document (doc1.xml).
  2. Move the cursor to the end of document (doc1.xml) and insert the second document.
  3. Get the paragraph node using the inserted bookmark and merge it with next paragraph.

Hope this helps you.

Document doc1 = new Document(MyDir + "document1.docx");
DocumentBuilder builder = new DocumentBuilder(doc1);
builder.moveToDocumentEnd();
builder.startBookmark("bookmark");
builder.endBookmark("bookmark");
Document doc2 = new Document(MyDir + "document2.docx");

builder.insertDocument(doc2, ImportFormatMode.KEEP_SOURCE_FORMATTING);

doc1.updatePageLayout();
Paragraph paragraph = (Paragraph) doc1.getRange().getBookmarks().get("bookmark").getBookmarkStart().getParentNode();
mergeParagraphs(paragraph, (Paragraph) paragraph.getNextSibling());

doc1.save(MyDir + "output.docx");

public static void mergeParagraphs(Paragraph dstPar, Paragraph srcPar)
{
    //move all content from source paragraph into the destination paragraph
    while (srcPar.hasChildNodes())
        dstPar.appendChild(srcPar.getFirstChild());

    //Remove source paragraph
    srcPar.remove();
}