首先,请确保您将
Graphics上下文翻译成适合可成像的区域…
g2d.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());
接下来,请确保您使用的是
imageableWidth和
imageableHeight的
PageFormat
double width = pageFormat.getImageableWidth();double height = pageFormat.getImageableHeight();
而不是
width/
height属性。其中许多东西都是从不同的上下文中翻译过来的…
graphics.drawImage(image, 0, 0, (int)width, (int)height, null);
该
getImageableWidth/Height页面方向的范围内返回页面大小
打印几乎都假设dpi为72(不要强调,打印API可以处理更高的分辨率,但是核心API假设72dpi)
这意味着10x15cm的页面应转换为
283.46456664x425.19684996像素。您可以通过使用
System.out.println并转储结果
getImageableWidth/Height到控制台来验证此信息。
如果您获得不同的设置,则可能是Java覆盖了默认页面属性
你有两个选择
你可以…
显示
PrintDialog并确保选择了正确的页面设置
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();aset.add(new PrinterResolution(300, 300, PrinterResolution.DPI));aset.add(new MediaPrintableArea(0, 0, 150, 100, MediaPrintableArea.MM));PrinterJob pj = PrinterJob.getPrinterJob();pj.setPrintable(new PrintTask()); // You Printable hereif (pj.printDialog(aset)) { try { pj.print(aset); } catch (PrinterException ex) { ex.printStackTrace(); }}或者你可以…
只需手动设置纸张/页面值…
public static void main(String[] args) { PrinterJob pj = PrinterJob.getPrinterJob(); PageFormat pf = pj.defaultPage(); Paper paper = pf.getPaper(); // 10x15mm double width = cmsToPixel(10, 72); double height = cmsToPixel(15, 72); paper.setSize(width, height); // 10 mm border... paper.setImageableArea( cmsToPixel(0.1, 72), cmsToPixel(0.1, 72), width - cmsToPixel(0.1, 72), height - cmsToPixel(0.1, 72)); // Orientation pf.setOrientation(PageFormat.PORTRAIT); pf.setPaper(paper); PageFormat validatePage = pj.validatePage(pf); pj.setPrintable(new Printable() { @Override public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { // Your pre here return NO_SUCH_PAGE; } }, validatePage); try { pj.print(); } catch (PrinterException ex) { ex.printStackTrace(); }}// The number of CMs per Inchpublic static final double CM_PER_INCH = 0.393700787d;// The number of Inches per CMspublic static final double INCH_PER_CM = 2.545d;// The number of Inches per mm'spublic static final double INCH_PER_MM = 25.45d;public static double pixelsToCms(double pixels, double dpi) { return inchesToCms(pixels / dpi);}public static double cmsToPixel(double cms, double dpi) { return cmToInches(cms) * dpi;}public static double cmToInches(double cms) { return cms * CM_PER_INCH;}public static double inchesToCms(double inch) { return inch * INCH_PER_CM;}


