Java printing - setting border size

I am trying to set the size to zero or remove the border of the printed document in java. It always has a standard white frame.

Here is my print function of 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 an Adobe PDF printer since I do not have a printer. Any suggestions?

+4
source share
1 answer

Use the version of PrinterJob.setPrintable () , which takes a PageFormat argument.

In PageFormat, set the paper to the image area that does not have a border (x = 0, y = 0, width = paper width, height = paper height).

You might want to pass this through PrinterJob.validatePage () , which:

Returns a clone of a page with settings configured for compatibility with the current printer of this PrinterJob. For example, the returned PageFormat may have its image area adjusted to match the physical area of ​​the paper used by the current printer.

This is a good idea because the printer may not support borderless printing, and this method will configure your PageFormat so that the settings are compatible with the printer.

Here is an example that prints text on a page with borders removed:

 PrinterJob pj = PrinterJob.getPrinterJob(); PageFormat format = pj.getPageFormat(null); Paper paper = format.getPaper(); //Remove borders from the paper paper.setImageableArea(0.0, 0.0, format.getPaper().getWidth(), format.getPaper().getHeight()); format.setPaper(paper); 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()); int textHeight = g2.getFontMetrics().getHeight(); g2.drawString("Good morning, what will be for eating?", 0, textHeight); return Printable.PAGE_EXISTS; } }, format); if (!pj.printDialog()) return; pj.print(); 

Tested with Postscript -> File Printer on Windows. There is a small margin left, but this is probably a limitation of the printer driver.

+6
source

Source: https://habr.com/ru/post/1384019/


All Articles