我有以下代码可以简单地打印二维码,但打印机会释放一个空白页。将文本添加到图形效果很好并且可以打印,但不是图像。如果我取消注释 ImageIO 部分,图像也会正确保存。
private BufferedImage printImg;
public Print(BufferedImage img) {
try {
this.printImg = img;
// ask for print
PrinterJob pjob = PrinterJob.getPrinterJob();
if (pjob.printDialog() == false) return;
pjob.setPrintable(this);
//File f = new File("MyFile.png");
//ImageIO.write(printImg, "PNG", f);
pjob.print();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if (page > 0)
return NO_SUCH_PAGE;
try {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(this.printImg, 0, 0, null);
} catch (Exception e) {
return NO_SUCH_PAGE;
}
return PAGE_EXISTS;
}
原始图像是 RGBA 格式的 PNG,我是这样读的:
BufferedImage in = ImageIO.read(qr.file());
Print p = new Print(in);