关于JAVA在打印图片时只能打印部分图片的问题

打印图片时只能打印部分是因为打印区域和图片的大小没有转换造成的,下面以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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值