Printing to a hard printer in java with a resolution of 300 dpi

Good, so I just started working on a program that was forced to print my graphics. Mine is almost identical to copyrighted in Oracle located here http://docs.oracle.com/javase/tutorial/2d/printing/examples/HelloWorldPrinter.java


So basically I’m a complete noob and tried to figure out how to set my page to 8.5x11in and 300dpi, but to no avail :( I don’t even have working code in this thread after all the failed attempts. I know that it has something to do with Paper.setSize() and PrinterResolution But I cannot extract from javadocs correctly to understand them. Please help.

EDIT: I believe that I found that Paper.setSize(72*8.5,72*11); Sets the page size to 8.5x11, but the dpi is still 72. For now, this is my code.

 public int print(Graphics g, PageFormat pf, int page) throws PrinterException { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Paper pg = new Paper(); pg.setSize(72*8.5,72*11); pf.setPaper(pg); if (page > 0) { /* We have only one page, and 'page' is zero-based */ return NO_SUCH_PAGE; } /* User (0,0) is typically outside the imageable area, so we must * translate by the X and Y values in the PageFormat to avoid clipping */ //Graphics2D g2d = (Graphics2D)g; g2d.translate(pf.getImageableX(), pf.getImageableY()); /* Now we perform our rendering */ g.drawString("Hello world! :D", 100, 100); /* tell the caller that this page is part of the printed document */ return PAGE_EXISTS; } 
+1
source share
1 answer

You need to use the print services API. This allows you to request specific properties for PrintJob , including DPI.

This is an example of RELLAY ...

 PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); aset.add(MediaSizeName.ISO_A4); aset.add(new PrinterResolution(300, 300, PrinterResolution.DPI)); aset.add(new MediaPrintableArea(2, 2, 210 - 4, 297 - 4, MediaPrintableArea.MM)); PrinterJob pj = PrinterJob.getPrinterJob(); pj.setPrintable(new PrintTask()); if (pj.printDialog(aset)) { try { pj.print(aset); } catch (PrinterException ex) { ex.printStackTrace(); } } 

See Working with print services and attributes for more information.

+3
source

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


All Articles