Okay, so i just started working on a program that is supossed to print out its graphics. Mine is almost identical to the copyrighted one at Oracle located here
http://docs.oracle.com/javase/tutorial/2d/printing/examples/HelloWorldPrinter.java
So basically I am a complete noob and have tried to figure out how to set my page to be 8.5x11in and 300dpi but to no avail :( I dont even have working code on this topic after all my failed attempts. I know it has something to do with Paper.setSize() and PrinterResolution But i cannot glean enough from the javadocs to understand these. Please help.
EDIT: I believe i discovered that Paper.setSize(72*8.5,72*11); Sets the page size to 8.5x11 but the dpi is still 72. This is my code so far.
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;
}
解决方案
You need to make use of the Print Services API. This allows you to request certain properties for a PrintJob, including the DPI.
This is a RELLAY basic example...
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();
}
}