How to change printing margins with JasperReports

jasper-reports

I'm generating a report straight to printer, but am encountering some problems. If I render it to screen and print the resulting PDF, it prints fine. However, when I print directly, I get weird margin problems. The target is a Zebra with 4"x3" labels.

If I set the paper size like so:

MediaSizeName mediaSizeName=MediaSize.findMedia(4, 3, MediaPrintableArea.INCH);
printRequestAttributeSet.add(mediaSizeName);

The result is a label up against the top margin, with a half inch left margin (should be none), the right margin is about .25" with part of the label chopped off, and the bottom maring is 1.5" with a lot of label chopped off.

If I don't set the paper size, then the top and left margins are perfect (meaning, there aren't any, goes to the edge of the label), but I still end up with the big bottom margin (with stuff chopped off), and my right margin gets a lot bigger (chopped off at the same point in regards to the printed information).

What am I missing here?

Best Answer

You can try to use setBottomMargin, setTopMargin, setRightMargin, setLeftMargin methods of JasperDesign class or the same methods from JasperPrint class.

You can see the sample here.

You can also set margins in report's template, for example with help of iReport.
The snippet of report template:

<jasperReport ... language="groovy" pageWidth="595" pageHeight="842" columnWidth="593" leftMargin="1" rightMargin="1" topMargin="1" bottomMargin="1">

You can also look at the MediaPrintableArea class constructor and read this post.

UPDATED:

The another solution how to remove margins from this discussion:

    PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
    Paper paper = new Paper();
    paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margin = no scaling
    pf.setPaper(paper);
Related Topic