使用300dpi在java中打印到硬打印机

时间:2013-04-15 23:05:01

标签: java graphics printing hardware

好的,所以我刚刚开始研究一个可以打印出图形的程序。我的几乎与位于此处的Oracle版权所有者相同 http://docs.oracle.com/javase/tutorial/2d/printing/examples/HelloWorldPrinter.java

<小时/> 所以基本上我是一个完整的菜鸟,并试图找出如何将我的页面设置为8​​.5x11in和300dpi,但无济于事:(在我所有失败的尝试后,我甚至没有关于这个主题的工作代码。我知道它有一些东西与Paper.setSize()PrinterResolution有关但我无法从javadocs那里了解到这些。请帮助。

编辑:我相信我发现Paper.setSize(72*8.5,72*11);将页面大小设置为8.5x11,但dpi仍然是72.这是我目前为止的代码。

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 个答案:

答案 0 :(得分:3)

您需要使用Print Services API。这允许您请求PrintJob的某些属性,包括DPI。

这是一个 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();
    }
}

请查看Working with Print Services and Attribues了解详情