最近跟着项目组在做项目,分到了打印机这个任务,顺便记录一下。
首先本地最好安装一下打印机的驱动,然后连上打印机开始测试!
Java调用打印机打印图片,文本都是很简单的,如下代码:
/**
* 通过 IP+端口 连接打印机打印文件
* @param filePath
* @throws Exception
*/
public static void print2(String filePath) throws Exception{
String ip="192.168.1.1";//打印机ip
File file = new File(filePath); // 获取选择的文件
Socket socket = new Socket(ip, 9100);
OutputStream out = socket.getOutputStream();
FileInputStream fis = new FileInputStream(file);
//建立数组
byte[] buf = new byte[1024];
int len = 0;
//判断是否读到文件末尾
while((len=fis.read(buf)) != -1)
{
out.write(buf, 0, len);
}
//告诉服务端,文件已传输完毕
socket.shutdownOutput();
socket.close();
fis.close();
}
然后我的任务是需要打印PDF,这个就有点麻烦,因为JDK自带的输入输出流是搞不定的,里面有文本还有有图片这种二进制文件,所以得采取其他办法。刚开始的思路是曲线实现,就是Java调用打印机服务API,而后发现也有点麻烦,一上百度之后发现Apache有个PDFBox的工具包,立马Download,由于项目紧,就直接贴上别人用的例子:
/* 打印指定的文件 */
public static void printPDF(String FilePath) throws PrintException, FileNotFoundException {
PDDocument document = null;
try {
File file=new File(FilePath);
document = PDDocument.load(file);
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName("快递面单打印");
PrintService printService = PrintServiceLookup
.lookupDefaultPrintService();
if (printService != null) {
printJob.setPrintService(printService);
} else {
System.out.print("打印失败,未找到默认打印机,请检查。");
return;
}
// }
//设置纸张及缩放
PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.SCALE_TO_FIT);
//设置多页打印
Book book = new Book();
PageFormat pageFormat = new PageFormat();
//设置打印方向
pageFormat.setOrientation(PageFormat.PORTRAIT);//纵向
pageFormat.setPaper(getPaper());//设置纸张
book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
printJob.setPageable(book);
printJob.setCopies(1);//设置打印份数
//添加打印属性
HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
//pars.add(Sides.DUPLEX); //设置单双页
printJob.print(pars);
} catch (PrinterException | IOException e) {
e.printStackTrace();
}
}
public static Paper getPaper() {
Paper paper = new Paper();
// 默认为A4纸张,对应像素宽和高分别为 595, 842
int width = 595;
int height = 842;
// 设置边距,单位是像素,10mm边距,对应 28px
int marginLeft = 5;
int marginRight = 0;
int marginTop = 5;
int marginBottom = 0;
paper.setSize(width, height);
// 下面一行代码,解决了打印内容为空的问题
paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
return paper;
}
Maven项目可以直接加上PDFbox的依赖,普通项目可以去Apache官网把包下载下来。