package com.eluotuo.utils;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.print.PrintServiceLookup;
import javax.swing.ImageIcon;
/**
* 打印类
* @author wanglei
* @version [版本号, 2016年3月29日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class EPrint implements Printable
{
public static void main(String[] args)
throws Exception
{
new EPrint("C:/Users/wanglei/Documents/XY/3.jpg").ePrint();
// PrintLabel(new FileInputStream(new File("C:/Users/wanglei/Documents/XY/3.jpg")));
}
/**
* 打印方法---已经写死了宽度和高度
*/
public void ePrint()
{
Book book = new Book();
PageFormat pageFormat = new PageFormat();
pageFormat.setOrientation(PageFormat.PORTRAIT); // LANDSCAPE表示竖打;PORTRAIT表示横打;REVERSE_LANDSCAPE表示打印空白
Paper paper = pageFormat.getPaper();
//设置宽度和高度 PageFormat指明打印页格式(页面大小以点为计量单位,1点为1英寸的1/72,1英寸为25.4毫米 如果是设置厘米的自己换算一下
paper.setSize(170, 111.8);
paper.setImageableArea(0, 0, 170, 111.8);
pageFormat.setPaper(paper);
PrinterJob printerJob = PrinterJob.getPrinterJob();
book.append(this, pageFormat,1);
printerJob.setPageable(book);
try
{
printerJob.setPrintService(PrintServiceLookup.lookupDefaultPrintService());
printerJob.print();
}
catch (PrinterException e)
{
e.printStackTrace();
}
}
/**
* 需要打印的图片路径
*/
private String imgSRC;
public EPrint(String imgSrc)
{
this.imgSRC = imgSrc;
}
@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(imgSRC);
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;
}
}
JAVA打印二维码图片自定义高度
最新推荐文章于 2022-06-16 22:23:29 发布