日期:2014-05-20  浏览次数:20712 次

java图片打印问题
好不容易把图片打印打代码给搞出来了,还是被一个问题给打倒了,图片是打印出来了,大小也差不多了,可图片的左边部分居然是空白的,不知道是打印机的默认页边距问题还是代码有问题,大师们能不能帮忙看下.

我重写的打印类:
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (pageIndex > 0) {  
return NO_SUCH_PAGE;  
}
Graphics2D g2d = (Graphics2D)graphics;
pageFormat.setOrientation(PageFormat.PORTRAIT); 
  g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); 
  ImageIcon image = new ImageIcon(imgpath); 
  Paper paper = pageFormat.getPaper(); 
  paper.setSize(3.90*72, 8.65*72); 
  paper.setImageableArea(0, 0, 3.90*72, 8.65*72);
  pageFormat.setPaper(paper); 
  double pageW= pageFormat.getImageableWidth();
  double pageH = pageFormat.getImageableHeight(); 
  double imageW = image.getIconWidth();
  double imageH = image.getIconHeight();
  double scaleX = pageW/imageW;
  double scaleY = pageH/imageH; 
  double scaleFactor = Math.min(scaleX, scaleY); 
  g2d.scale(scaleFactor, scaleFactor); 
  g2d.drawImage(image.getImage(), 0, 0, null);
return Printable.PAGE_EXISTS; 
}

我的打印方法:
/** 
* 画图片的方法 
* @param fileName[图片的路径] 
*/ 
public static void print(String fileName){ 
PrinterJob printerJob = PrinterJob.getPrinterJob();  
Book book = new Book();  
ScaleImage scale = new ScaleImage(); 
scale.setImgpath(fileName);
book.append(scale, printerJob.defaultPage());  
printerJob.setPageable(book);  
HashAttributeSet hs = new HashAttributeSet(); 
//获取指定打印机
Properties properties = FileManager.getProperties();
String printer=properties.getProperty("printurl");
hs.add(new PrinterName(printer,null));
PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, hs);
if(pss.length==0)
{
return ;
}
try {
printerJob.setPrintService(pss[0]);
printerJob.print();
} catch (PrinterException e) {

}  
}

------解决方案--------------------
慢慢调节打印的打印纸规格尺寸