2013-08-23 33 views
1

我想知道是否有正確的方式在Java中打印BufferedImage。 基本上我創建了一個可以正常工作的照片處理程序,我可以保存圖像等。 但是我真正的目標是將它發送到打印機軟件,以便您可以選擇要打印的頁面數量和頁面類型。在Java中打印BufferedImage的正確方法

所以我縮短的問題是,如何發送緩衝的圖像到打印機,以便打印機選擇屏幕將彈出等,然後能夠打印?

如果有人能告訴我一個這樣的例子,將不勝感激。

+4

[打印](http://docs.oracle.com/javase/tutorial/2d/printing/)可能是一個很好的起點。 – mre

+2

@mre這是我用於從java應用程序打印的相同教程,它非常好。我還建議另一個資源:http://www.javaworld.com/jw-10-2000/jw-1020-print.html。這兩篇文章都假設了一些Java知識,但不知道如何使用打印API,並且應該是一個很好的指導和基礎。 –

回答

10

這是我的一個Java項目。此代碼將縮放並在打印機頁面上打印一個圖像。

你這樣稱呼它:

printButton.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent event) { 
      //Start a Thread 
      new Thread(new PrintActionListener(image)).start();   
     } 
    }); 

這裏了Runnable:

import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.awt.print.PageFormat; 
import java.awt.print.Printable; 
import java.awt.print.PrinterException; 
import java.awt.print.PrinterJob; 

public class PrintActionListener implements Runnable { 

    private BufferedImage  image; 

    public PrintActionListener(BufferedImage image) { 
     this.image = image; 
    } 

    @Override 
    public void run() { 
     PrinterJob printJob = PrinterJob.getPrinterJob(); 
     printJob.setPrintable(new ImagePrintable(printJob, image)); 

     if (printJob.printDialog()) { 
      try { 
       printJob.print(); 
      } catch (PrinterException prt) { 
       prt.printStackTrace(); 
      } 
     } 
    } 

    public class ImagePrintable implements Printable { 

     private double   x, y, width; 

     private int    orientation; 

     private BufferedImage image; 

     public ImagePrintable(PrinterJob printJob, BufferedImage image) { 
      PageFormat pageFormat = printJob.defaultPage(); 
      this.x = pageFormat.getImageableX(); 
      this.y = pageFormat.getImageableY(); 
      this.width = pageFormat.getImageableWidth(); 
      this.orientation = pageFormat.getOrientation(); 
      this.image = image; 
     } 

     @Override 
     public int print(Graphics g, PageFormat pageFormat, int pageIndex) 
       throws PrinterException { 
      if (pageIndex == 0) { 
       int pWidth = 0; 
       int pHeight = 0; 
       if (orientation == PageFormat.PORTRAIT) { 
        pWidth = (int) Math.min(width, (double) image.getWidth()); 
        pHeight = pWidth * image.getHeight()/image.getWidth(); 
       } else { 
        pHeight = (int) Math.min(width, (double) image.getHeight()); 
        pWidth = pHeight * image.getWidth()/image.getHeight(); 
       } 
       g.drawImage(image, (int) x, (int) y, pWidth, pHeight, null); 
       return PAGE_EXISTS; 
      } else { 
       return NO_SUCH_PAGE; 
      } 
     } 

    } 

}