Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set printer margin in java

Tags:

java

printing

when trying to print using the Print API - the margins seem to be something not in our control!.. Please help me out to set printer margins or is there any way to set margins at Operating system level.

By default all the four left, right, top and bottom are set to 1.

like image 717
BaoNC Avatar asked Aug 13 '14 09:08

BaoNC


2 Answers

I'm using the Java Printing API, but have problems setting print margins.

...

Solution

I had to provide additional print attributes to override the default print margins, MediaPrintableArea.

Most printers cannot print on the entire surface of the media, due to printer hardware limitations.

MediaPrintableArea can be used to query the acceptable values for a supposed print job, and to request an area within the constraints of the printable area to be used in a print job.

HashPrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
attr.add(new MediaPrintableArea(0f, 0f, w/72f, h/72f, MediaPrintableArea.INCH));       
PrinterJob job = PrinterJob.getPrinterJob();    
job.setPrintService(ps);
job.setPrintable(this);
job.setJobName(jobName);
job.print(attr);
j.setVisible(false);
j.dispose();

The key was to provide the attributes along with the print() command.

Source Help with print margins

like image 163
DavidPostill Avatar answered Sep 19 '22 12:09

DavidPostill


PageFormat defaultPF = printJob.defaultPage();
Paper paper = defaultPF.getPaper();
if (isPortrait)
{
    defaultPF.setOrientation(PageFormat.PORTRAIT);
    paper.setImageableArea(0, 0, defaultPF.getWidth(), defaultPF.getHeight());
}
else
{
    defaultPF.setOrientation(PageFormat.LANDSCAPE);
    paper.setImageableArea(0, 0, defaultPF.getHeight(), defaultPF.getWidth());
}
defaultPF.setPaper(paper);
defaultPF = printJob.validatePage(defaultPF);

// now dialog has margins set to minimum
PageFormat pf = printJob.pageDialog(defaultPF);
like image 21
WorthlessScum Avatar answered Sep 20 '22 12:09

WorthlessScum