打印不起作用Java

时间:2015-03-06 16:02:48

标签: java printing

我想要打印一份文件。下面的代码显示了“打印”对话框,但是当我单击“打印”时,没有打印任何内容。

PrinterJob job;
job = PrinterJob.getPrinterJob();
if (job.printDialog()){
  try{
     job.print();
  }catch(Exception e){
  }
}

我错过了什么吗?喜欢格式页?

由于

1 个答案:

答案 0 :(得分:2)

您必须为要打印的内容实现可打印接口,并将其设置为作业:

job.setPrintable(printable);

我通常会像这样开始我的可打印代码:

public int print(Graphics g, PageFormat pf, int i) throws PrinterException {
        if (i > getPrintableImages(pf).size() - 1) {
            //returning this stops printing
            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());