I try to set the size to zero or remove the border of a printed document in java. It always has a standard white border.
Here is my function printing a JPanel and some components:
public void printComponent(){
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Print Component ");
pj.setPrintable (new Printable() {
@Override
public int print(Graphics pg, PageFormat pf, int pageNum) throws PrinterException {
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
TournamentView.this.paint(g2);
return Printable.PAGE_EXISTS;
}
});
if (pj.printDialog() == false)
return;
try {
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.LANDSCAPE);
PrinterResolution pr = new PrinterResolution(200, 200, PrinterResolution.DPI);
aset.add(pr);
pj.print( aset);
} catch (PrinterException ex) {
// handle exception
}
}
I am using Adobe PDF printer since I haven’t any printer here. Any suggestions?
Use the version of PrinterJob.setPrintable() that takes a
PageFormatargument.In the PageFormat, set the paper’s imageable area have no border (x=0, y=0, width=paper’s width, height=paper’s height).
You might want to feed that through PrinterJob.validatePage(), which:
This is a good idea because the printer might not support borderless printing and it will this method will adjust your
PageFormatso that settings are compatible with the printer.Here is an example that prints some text on a page with removed borders:
Tested with a Postscript -> File printer on Windows. There was still a small border left but that is likely a limitation of the printer driver.