Search code examples
xsltxsl-foapache-fop

XSL-FO: how to do not begin a chapter in last line


I have a xml document with chapters, and sub-chapters.

I have created an XSL-FO to convert the document to PDF with apache-fop. In the PDF, chapters begin always in a new page using "break-before".

I would like sub-chapters to only start on a page if there is at least 5-10 lines free: sub-chapters do not need to begin on a new page, but it is ugly to have a title in the last line and the first paragraph in the next page.

enter image description here

Any idea how to perform that?

Very simple example of XML file:

<document>
    <chapter title="Intro">
        <sub-chapter title="any-sub-title">
            Any text here
        </sub-chapter>
    </chapter>
</document>

XSL-FO section:

...
<xsl:for-each select="chapter">
    <fo:block font-weight="bold" break-before="odd-page">
        <xsl:value-of select="@title"/>
    </fo:block>
    <xsl:apply-templates/>
</xsl:for-each>
...
<xsl:template match="sub-chapter">
    <fo:block font-weight="bold">
        <xsl:value-of select="@title"/>
    </fo:block>
    <xsl:apply-templates/>
</xsl:template>

Solution

  • What I think you are looking for is widow and orphan protection. With widows and orphans, you specify the number of lines in a block that cannot be left alone on one page.

    <fo:block widows="4" orphans="4">
       your content here.
    </fo:block>
    

    You might get a similar behavior with the keep-together or keep-with-next attributes. See the link for a quick how-to.