flavio.donze
flavio.donze

Reputation: 8100

How to remove a page break?

I have this simplified code, which creates one big document out of different word files using a com.aspose.words.DocumentBuilder.

for (Document contentDocument : documents) {
    ...
    builder.insertDocument(contentDocument, ImportFormatMode.KEEP_SOURCE_FORMATTING);
    builder.insertBreak(BreakType.PAGE_BREAK);
}

After each document a page break is inserted.

Is there a way to remove the last page break?

Upvotes: 0

Views: 1565

Answers (4)

Zeeshan Mahboob
Zeeshan Mahboob

Reputation: 194

You can remove Last page break of the document with the following piece of code:

        var doc = new Aspose.Words.Document();
        //last page break in document
        var run = doc.GetChildNodes(NodeType.Run, true)
                .Cast<Run>().Where(obj => obj.Text.Contains(ControlChar.PageBreak)).LastOrDefault();
           //Replace Page break chracter with empty string
            run.Text = run.Text.Replace("" + ControlChar.PageBreak, " ");

Upvotes: 0

Olimpiu POP
Olimpiu POP

Reputation: 5067

Wouldn't something like:

for (int i=0; i< documents.length; i++) {
    ...
    builder.insertDocument(documents[i], ImportFormatMode.KEEP_SOURCE_FORMATTING);
    if (i == documents.length - 1) {
       continue;
    } 
    builder.insertBreak(BreakType.PAGE_BREAK);
}

work? Or to avoid the check at every iteration:

for (int i=0; i< documents.length -1; i++) {
    ...
    builder.insertDocument(documents[i], ImportFormatMode.KEEP_SOURCE_FORMATTING);
    builder.insertBreak(BreakType.PAGE_BREAK);
}
builder.insertDocument(documents[documents.length - 1], ImportFormatMode.KEEP_SOURCE_FORMATTING);

The provided solution assumes that documents is an array.

Upvotes: 1

gvlachakis
gvlachakis

Reputation: 474

I prefer to use POI, but take a look at this .

note the following section

 private static void removeSectionBreaks(Document doc) throws Exception
{
    // Loop through all sections starting from the section that precedes the last one
    // and moving to the first section.
    for (int i = doc.getSections().getCount() - 2; i >= 0; i--)
    {
        // Copy the content of the current section to the beginning of the last section.
        doc.getLastSection().prependContent(doc.getSections().get(i));
        // Remove the copied section.
        doc.getSections().get(i).remove();
    }
}

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26946

You can loop using the old version of loop. Here I suppose that documents is a List.

for (int i = 0; i < documents.size(); i++) {
    Document contentDocument = documents.get(i);
    builder.insertDocument(contentDocument, ImportFormatMode.KEEP_SOURCE_FORMATTING);

    if (i < documents.size() - 1) {
         builder.insertBreak(BreakType.PAGE_BREAK);
    }
}

Upvotes: 1

Related Questions