Search code examples
javajasper-reports

Report Books with JasperReport - How to use $V{MASTER CURRENT_PAGE} ignoring index pages


I am developing an Report Books in JasperReport,

I need each page to have its page number in the Page Footer Band , I have been trying to do it with PAGE_NUMBER variable and with Now, Report, Page, etc Evaluation time, however the page number has always done incorrect.

I read that in Report Books, you should use $V{MASTER CURRENT_PAGE} variable with the Master Evaluation Time, I worked fine, but when I use this variable the numeration begins in the first page (Naturally it works of this way), however I have a cover page and index pages and I would like the numeration begins after the index pages.

I thought in solve my problem of this way:

$V{MASTER CURRENT_PAGE} - 2

However like the index page can have more pages, this will certainly fail.

Does someone know how can I configurate the $V{MASTER CURRENT_PAGE} to begins after the index.

Regards.


Solution

  • You can use a variable to store the number of pages in the index section and then subtract it from $V{MASTER_CURRENT_PAGE}

    To do that, you'd create a variable such as this one in the master/book reports:

    <variable name="IndexPages" class="java.util.concurrent.atomic.AtomicInteger" calculation="System">
        <initialValueExpression>new java.util.concurrent.atomic.AtomicInteger()</initialValueExpression>
    </variable>
    

    Note that we're using AtomicInteger as a mutable integer, we need an object in which to update the value.

    Then the variable should be passed as a parameter to the index part as a parameter:

                <p:subreportPart xmlns:p="http://jasperreports.sourceforge.net/jasperreports/parts" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/parts http://jasperreports.sourceforge.net/xsd/parts.xsd" usingCache="true">
                    <subreportParameter name="IndexPages">
                        <subreportParameterExpression>$V{IndexPages}</subreportParameterExpression>
                    </subreportParameter>
                    <subreportExpression><![CDATA[...]]></subreportExpression>
                </p:subreportPart>
    

    The index report needs to define the parameter and use an expression to set the $V{PAGE_NUMBER} value in the object. The expression should belong to an element or band that prints on the last page of the report, for instance the print when expression of an element in the page header/footer:

    <parameter name="IndexPages" class="java.util.concurrent.atomic.AtomicInteger"/>
    ...
        <reportElement ...>
            <printWhenExpression><![CDATA[$P{IndexPages}.getAndSet($V{PAGE_NUMBER}) > 0]]></printWhenExpression>
    

    Then the same variable needs to be passed as parameter in the same way to the other report parts, which need to declare the parameter and then display $V{MASTER_CURRENT_PAGE} - $P{IndexPages}.get() as page number.