栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

java PrinterJob无法打印以适合纸张

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java PrinterJob无法打印以适合纸张

首先,请确保您将

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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/609904.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号