@Slf4j
public class DrivePrintService {
// 传入文件和打印机名称
public void print(File[] files, String printerName) throws PrintException, IOException {
List<InputStream> streams = fileStreams(files);
if (CollUtil.isEmpty(streams)) {
log.warn("缺少打印文件");
throw new NullPointerException("缺少打印文件");
}
DocFlavor flavor = getDocFlavor();
PrintRequestAttributeSet aset = getPrintRequestAttribute();
for (InputStream in : streams) {
DocPrintJob docPrintJob = getPrintJob(printerName);
docPrintJob.print(new SimpleDoc(in, flavor, null), aset);
}
}
private List<InputStream> fileStreams(File[] files) {
if (ArrayUtil.isEmpty(files)) {
log.warn("缺少打印文件");
throw new NullPointerException("缺少打印文件");
}
List<InputStream> ins = new ArrayList<>();
try {
for (File file : files) {
ins.add(new FileInputStream(file));
}
} catch (FileNotFoundException e) {
log.warn("打印文件缺失:{}", e.getMessage());
}
return ins;
}
private DocFlavor getDocFlavor() {
// 设置打印格式,如果未确定类型,可选择autosense
return DocFlavor.INPUT_STREAM.AUTOSENSE;
}
private PrintRequestAttributeSet getPrintRequestAttribute() {
// 设置打印参数
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1)); //份数
//aset.add(MediaSize.ISO.A4); //纸张
// aset.add(Finishings.STAPLE);//装订
aset.add(Sides.DUPLEX);//单双面
return aset;
}
private DocPrintJob getPrintJob(String printerName) {
if (printerName == null) {
log.warn("请选择打印机");
throw new NullPointerException("请选择打印机");
}
//获得本台电脑连接的所有打印机
PrintService[] printServices = PrinterJob.lookupPrintServices();
if (printServices == null || printServices.length == 0) {
log.warn("打印失败,未找到可用打印机,请检查。");
throw new NullPointerException("打印失败,未找到可用打印机,请检查。");
}
//匹配指定打印机
PrintService printService = null;
for (PrintService service : printServices) {
if (printerName.equals(service.getName())) {
printService = service;
break;
}
}
if (printService == null) {
String format = StrUtil.format("打印失败,未找到名称为 [{}] 的打印机,请检查。", printerName);
log.warn(format);
throw new NullPointerException(format);
}
return printService.createPrintJob();
}
}
监听打印
@Slf4j
public class MyPrintJobListener implements PrintJobListener {
@Override
public void printDataTransferCompleted(PrintJobEvent pje) {
log.warn("通知客户端数据已成功传输到打印服务,客户端可以释放为该数据分配的本地资源");
}
@Override
public void printJobCompleted(PrintJobEvent pje) {
log.warn("通知客户该作业成功完成。");
}
@Override
public void printJobFailed(PrintJobEvent pje) {
log.warn("通知客户该作业未成功完成,必须重新提交。");
}
@Override
public void printJobCanceled(PrintJobEvent pje) {
log.warn("通知客户该作业被用户或程序取消。");
}
@Override
public void printJobNoMoreEvents(PrintJobEvent pje) {
log.warn("通知客户不会再发送任何事件。");
}
@Override
public void printJobRequiresAttention(PrintJobEvent pje) {
log.warn("通知客户某些可能出现用户纠正的问题(例如打印机缺纸)。");
}
}
网友评论