新接手一个打印终端的项目,要求可以打印A4格式的单据和 70mm * 40mm 规格的条码。
整体流程可分两种情况,
一种是将打印模板转换为pdf文档二进制数组,进而生成为pdf文档,保存到本地,然后再读取到程序中,打印,最后删除生成的pdf文档(不然随着打印次数的增多,本地磁盘岂不爆满);
另一种是省略保存中间步骤,直接将打印模板转换得到的pdf文档二进制数组用于程序打印。
显然,第二种情况较为简单,项目最后也是采用的这种。
先说打印A4的情况。
打印A4的情况比较简单,本地有一台惠普的A4打印,直接上代码。
package com.jiuqi.dna.gams.GXH.yndx.printing.util;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.print.PrintService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import net.sf.json.JSONObject;
/**
* 自助打印终端打印工具类
* @author wangjiao01
*
*/
public class PDFPrintUtil {
/**
* 获取临时生成的pdf文件路径
* @param pdfData
* @return
*/
public static String getNewPDFPath(byte[] pdfData) {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newPdfName = df.format(new Date());
String newPdfPath = "E:\\pdf\\" + newPdfName + ".pdf";// 随具体环境变化
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(newPdfPath);
outputStream.write(pdfData);
}catch(IOException e) {
e.printStackTrace();
}finally {
if(outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return newPdfPath;
}
/**
* 执行打印
* @param pdfData pdf文档对应的二进制数组
* @param printerName 打印机标识
* @param copyCount 打印份数
* @return
* @throws IOException
*/
public static String doPrintByPDFBox(byte[] pdfData, String printerName, Integer copyCount) throws IOException {
String result = null;
PDDocument document = null;
try {
document = PDDocument.load(pdfData);
PrinterJob printerJob = PrinterJob.getPrinterJob();
// 查找并设置打印机
PrintService[] printServices = PrinterJob.lookupPrintServices();
if(printServices == null || printServices.length == 0) {
result = getPrintMessage(false, "打印失败,计算机未安装打印机,请检查。");