Error: Cannot insert the requested break outside of the main story

Hello! I have some Document and when I want to do this:

builder.insertBreak(BreakType.PAGE_BREAK);

I receive this ERROR @java.lang.IllegalStateException: Cannot insert the requested break outside of the main story.@
What does it mean and how to fix it?

In another Documents everything works fine
Thank you

@cagecrew

The error message “Cannot insert the requested break outside of the main story” typically indicates that you are trying to insert a page break in a part of the document that is not the main body, such as a header, footer, or a different story type.

To resolve this issue, ensure that you are moving the DocumentBuilder cursor to the main body of the document before attempting to insert the page break. You can do this by using the moveToSection or moveToDocumentStart methods to position the cursor correctly.

Here’s an example of how to properly insert a page break in the main story:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Move to the main body of the document
builder.moveToDocumentStart(); // or builder.moveToSection(0);

// Now you can safely insert a page break
builder.insertBreak(BreakType.PAGE_BREAK);

Make sure that the cursor is positioned in the main body of the document when you call insertBreak. If you are working with headers or footers, you will need to move the cursor back to the main body before inserting the break.

If you continue to experience issues, please check the structure of your document to ensure that you are not inadvertently trying to insert breaks in non-body sections.

I understand that the problem is in one of the documents. How can I find out what exactly is wrong with this document?

Problem is, that we are using this code:

    private void addPageNumbering(DocumentBuilder builder) {
        builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST);
        builder.insertField("PAGE", "");
        builder.getCurrentParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);
        builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
        builder.insertField("PAGE", "");
        builder.getCurrentParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.RIGHT);
    }

And line builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST); moves cursor ouside of a body, how to return it back?

P.S. Document is empty when addPageNumbering executing

@cagecrew You should simply call builder.moveToDocumentStart(); to return DocumentBuilder’s cursor back into the main body.

1 Like