Search code examples
javajasper-reports

how to Change Page Format in Runtime?(jasperreport)


I created a report page with A4 format in iReport4.5 and use in java application.

how to change A4 to A5 format on runtime in java application?


Solution

  • Before I show you how to do this, please note that just changing the Page Size is probably not going to give you what your want. It will make the page larger or smaller depending on what you want, put the positioning of elements will not change. IN your case the report may not even compile depending on where you have items laid out.

    You do have a couple options though:

    1. First you could create a second report for the A5 format, and then at run time grab the appropriate report depending on what you want. This is probably the easiest solution, but it does mean you end up with almost 2 identical reports. Meaning any changes in the future you would have to do in two places.
    2. Second if it is a fairly straight forward report with a typical layout you could use something like Dynamic Jasper to generate your report in java code.
    3. Lastly you could work directly against the Jasper Report's API to generate your report at run time.


    Now to answer your question. First load up the JRXml file into a JasperDesign object:

    //Note JRXMLLoader could also take a File object or 
    //InputStream instead of a String as the parameter.
    JasperDesign design = JRXmlLoader.load("report.jrxml");
    

    Once you have the JasperDesign you can set the page size to what ever you want. A5 paper from what I can tell is 5.83" × 8.27". To convert this to a size that JasperReports understands multiply each by 72, getting you 420 x 596 (I rounded as we have to set Integers).

    design.setPageHeight(596);
    design.setPageWidth(420);
    

    From there you cointinue on your exporting adventure as you normally would.