打印图片时只能打印部分是因为打印区域和图片的大小没有转换造成的,下面以mm为例(A4:210mm * 297mm)解决上述问题:
下面是示例代码(printable类的print方法):
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
// 读取图片文件,转为BufferedImage
//Frame f=new Frame();
BufferedImage img;
try {
img = ImageIO.read(outf); //outf为图片文件 可这样获得 File outf = new File("D:/TEST.JPG");
Font font1 = new Font("Dialog", Font.PLAIN, 12);
//g2.drawString(this.info,30,50);
int offset = 3;
Double pw, ph;
// 现在pw ph是mm
pw = 210d;
ph = 297d;
pw = pw / 25.4 * 72;
ph = ph / 25.4 * 72;
Rectangle rect1 = new Rectangle();
rect1.x = offset;
rect1.y = offset;
rect1.width = pw.intValue() - 2 * offset;
rect1.height = ph.intValue() - 2 * offset;
int width = img.getWidth();
int height = img.getHeight();
double rx = (double) (rect1.width-30) / width;
double ry = (double) (rect1.height - 60) / height;
Graphics2D gtmp = (Graphics2D) g2.create(rect1.x, rect1.y,
rect1.width, rect1.height);
gtmp.scale(rx, ry);
gtmp.setFont(font1);
gtmp.drawString("test",30,50);
gtmp.drawImage(img, 30, 60, null);
gtmp.dispose();
//Graphics g2=img.getGraphics();
//g2.drawImage(img,30,60,f);
} catch (IOException e) {
e.printStackTrace();
}
return PAGE_EXISTS;
}