How to set margins to jasper report in java?

2019-02-26 06:13发布

问题:

How to set margins to jasper report in java!

I have reports.jasper with margins,but when print I must change margins!

JasperPrint.setTopMargins(myMarginsValue) doesn't work!!!

I use JRPrintServiceExporter to send to the printer!

Current code:

InputStream reportStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/rep‌​orts/" + "myReport"+".jasper"); 
JasperReport template = (JasperReport) JRLoader.loadObject(reportStream);
template.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);

回答1:

Load the jrxml (note not the .jasper) into the JasperDesign using the JRXmlLoader

JasperDesign design = JRXmlLoader.load(stream); //Location of jrxml file example FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/rep‌​orts/" + "myReport"+".jrxml");
design.setBottomMargin(bottomMargin); //set the margins
design.setTopMargin(topMargin)
design.setLeftMargin(leftMargin)
design.setRightMargin(rightMargin);
design.setColumnWidth(design.getPageWidth()-leftMargin-rightMargin);//if you change your left and right margin you need to set new correct columnWidth

//compile the report
JasperReport report = JasperCompileManager.compileReport(design); //this is what you called template

Then fill it and export it as you wish.

Naturally textField may be out side of design, band may not fit the page height if you increase your margins to much, this needs to be attended to as appropriate.

This is another similar question with full code if the purpose is moving layout to adapt to pre-printed form: How can I move the whole layout to adapt to pre-printed form on different printers