Browse Source

-024-08-01打印pdf文档

master
zhousq 4 months ago
parent
commit
49b545ef32
  1. 8
      pom.xml
  2. 1623
      sql/winps_20240801.sql
  3. 15
      win-admin/src/main/java/com/win/web/controller/print/WinPrintServerControler.java
  4. 9
      win-admin/src/main/java/com/win/web/controller/print/WinPrintServerControlerTest.java
  5. 8
      win-print/pom.xml
  6. 1
      win-print/src/main/java/com/win/print/controller/WinPrintClientPrintersController.java
  7. 39
      win-print/src/main/java/com/win/print/controller/WinPrintTasksLogsController.java
  8. 30
      win-print/src/main/java/com/win/print/domain/WinPrintModel.java
  9. 77
      win-print/src/main/java/com/win/print/service/PrintService.java
  10. 95
      win-print/src/main/java/com/win/print/service/PrintServiceWin.java
  11. 94
      win-print/src/main/java/com/win/print/service/PrintTaskProcesser.java
  12. 54
      win-print/src/main/java/com/win/print/util/PdfModelUitl.java
  13. 41
      win-print/src/main/java/com/win/print/util/PdfPrintUtil.java
  14. 49
      win-print/src/main/java/com/win/print/util/PrinterUtil.java
  15. 2
      win-print/src/main/java/com/win/print/util/WinPrintJobListener.java
  16. 2
      win-print/src/main/resources/mapper/print/WinPrintClientPrintersMapper.xml
  17. 15
      win-print/src/main/resources/mapper/print/WinPrintModelMapper.xml
  18. 2
      win-print/src/main/resources/templates/print/logmanager/logmanager.html
  19. 9
      win-print/src/main/resources/templates/print/modelmanager/add.html
  20. 9
      win-print/src/main/resources/templates/print/modelmanager/edit.html

8
pom.xml

@ -259,8 +259,12 @@
<artifactId>ognl</artifactId>
<version>3.2.21</version>
</dependency>
</dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.32</version>
</dependency> </dependencies>
</dependencyManagement>

1623
sql/winps_20240801.sql

File diff suppressed because it is too large

15
win-admin/src/main/java/com/win/web/controller/print/WinPrintServerControler.java

@ -102,6 +102,8 @@ public class WinPrintServerControler extends BaseController {
String taskId=Optional.ofNullable(dataVo.getTaskId()).orElse(IdUtil.fastSimpleUUID());
String modelPage=winPrintModel.getmPageSize();
String isPageRolated=winPrintModel.getIsPageRotate();
int fontSize=Optional.ofNullable(winPrintModel.getFontSize()).orElse(14);
String fontName=Optional.ofNullable(winPrintModel.getFontName()).orElse("STSong-Light");
Date printeDate=null;
try{
printeDate = DateUtil.parse(dataVo.getPrintDate()); //转换时间
@ -127,7 +129,7 @@ public class WinPrintServerControler extends BaseController {
String pdfPath = pdfDir + "/" ;
if ("1".equals(dataVo.getDocModel())) { //单文单件务打印
String fileName= clientCode + "_" + modelCode + "_"+String.valueOf(System.currentTimeMillis()) + ".pdf";
printMutilPage(winPrintModelParamsList, printData, modelName, pageSize, pdfPath +fileName, modelTypeSrc, templateDir,modelType);
printMutilPage(winPrintModelParamsList, printData, modelName, pageSize, pdfPath +fileName, modelTypeSrc, templateDir,modelType, fontSize, fontName);
//printTaskService.putTaskToQueue(info, DateUtil.now(),fileName,remoteAddr,"model",winPrintModel.getmPageSize(),winPrintModel.getmPageRotate(),1);
iPrintTasksLogsService.createTaskLog(clientCode,fileName,taskId,"model",modelCode,printerName, requestType,copyCounts, modelPage, isPageRolated, "",printeDate, fileServer);
} else {
@ -137,7 +139,7 @@ public class WinPrintServerControler extends BaseController {
printData.forEach(pdata -> {
String pdfFileName = clientCode + "_" + modelCode + "_"+ String.valueOf(fileCount.getAndIncrement()) + "_" + String.valueOf(System.currentTimeMillis()) + ".pdf";
File file = new File(pdfPath+pdfFileName);
printOneByOne(winPrintModelParamsList,file, modelType, pdata, pageSize, finalModelName, modelTypeSrc, templateDir);
printOneByOne(winPrintModelParamsList,file, modelType, pdata, pageSize, finalModelName, modelTypeSrc, templateDir, fontSize, fontName);
iPrintTasksLogsService.createTaskLog(clientCode,pdfFileName,taskId,"model",modelCode,printerName, requestType,copyCounts, modelPage, isPageRolated, "", finalPrinteDate,fileServer);
});
@ -198,6 +200,7 @@ public class WinPrintServerControler extends BaseController {
{
String pdfDir = DataUnitl.getWorkingDir(printFilepath)+"/";
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//response.setContentType(MediaType.APPLICATION_PDF_VALUE);
FileUtils.setAttachmentResponseHeader(response, fileName);
FileUtils.writeBytes(pdfDir+fileName, response.getOutputStream());
//return AjaxResult.success("任务成功下发!");
@ -241,10 +244,10 @@ public class WinPrintServerControler extends BaseController {
/**
* 单页打印
*/
private void printOneByOne(List<WinPrintModelParams> paramList,File pdfFileName, String modeType, JSONObject data, PageSize pageSize, String modelName, String modeTypeSrc, String templatePath) {
private void printOneByOne(List<WinPrintModelParams> paramList,File pdfFileName, String modeType, JSONObject data, PageSize pageSize, String modelName, String modeTypeSrc, String templatePath,int fontSize,String fontName) {
try {
if ("PDF".equalsIgnoreCase(modeType)) {
pdfModelUitl.pdfMdelFromRender(paramList,pdfFileName,data,modelName,templatePath);
pdfModelUitl.pdfMdelFromRender(paramList,pdfFileName,data,modelName,templatePath, fontSize, fontName);
log.info("处理PDF模版");
} else if ("freemarker".equalsIgnoreCase(modeType)) {
log.info("处理freemarker模版");
@ -296,7 +299,7 @@ public class WinPrintServerControler extends BaseController {
/**
* 多以合并
*/
private void printMutilPage(List<WinPrintModelParams> paramList, List<JSONObject> dataList, String modelName, PageSize pageSize, String fileName, String modeTypeSrc, String templatePath,String modelType) {
private void printMutilPage(List<WinPrintModelParams> paramList, List<JSONObject> dataList, String modelName, PageSize pageSize, String fileName, String modeTypeSrc, String templatePath,String modelType, int fontSize, String fontName) {
try {
PdfDocument destDoc = new PdfDocument(new PdfWriter(fileName));
destDoc.setDefaultPageSize(pageSize);
@ -305,7 +308,7 @@ public class WinPrintServerControler extends BaseController {
try {
File tempFile = File.createTempFile("temp_" + String.valueOf(System.currentTimeMillis()), ".pdf");
if("PDF".equalsIgnoreCase(modelType)){
pdfModelUitl.pdfMdelFromRender(paramList,tempFile,pdata,modelName,templatePath);
pdfModelUitl.pdfMdelFromRender(paramList,tempFile,pdata,modelName,templatePath, fontSize, fontName);
}else{
Map<String, String> modelData = new HashMap<>();
paramList.forEach(item -> {

9
win-admin/src/main/java/com/win/web/controller/print/WinPrintServerControlerTest.java

@ -177,10 +177,11 @@ public class WinPrintServerControlerTest extends BaseController {
}
private void putJob(String fileName,String printerName,PrintRequestAttributeVo vo) throws PrintException, IOException {
FileInputStream fileIn = new FileInputStream(fileName);
DocPrintJob pringJobByName = PrinterUtil.getPringJobByName(printerName);
DocFlavor docFlavor = PrinterUtil.getDocFlavor(EnumDocFlavor.IS_AUTOSENSE);
PrintRequestAttributeSet printRequestAttribute = PrinterUtil.getPrintRequestAttribute(vo,"test");
PrinterUtil.sendJobtoPrinter(pringJobByName, PrinterUtil.getSimpleDoc(fileIn, docFlavor), printRequestAttribute);
PrinterUtil printerUtil=new PrinterUtil();
DocPrintJob pringJobByName = printerUtil.getPringJobByName(printerName);
DocFlavor docFlavor = printerUtil.getDocFlavor(EnumDocFlavor.IS_AUTOSENSE);
PrintRequestAttributeSet printRequestAttribute = printerUtil.getPrintRequestAttribute(vo,"test");
printerUtil.sendJobtoPrinter(pringJobByName, printerUtil.getSimpleDoc(fileIn, docFlavor), printRequestAttribute);
fileIn.close();
}
/**

8
win-print/pom.xml

@ -77,7 +77,13 @@
<version>2.2.21</version>
<scope>compile</scope>
</dependency>
<!-- <dependency>-->
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>ognl</groupId>-->
<!-- <artifactId>ognl</artifactId>-->
<!-- </dependency>-->

1
win-print/src/main/java/com/win/print/controller/WinPrintClientPrintersController.java

@ -130,4 +130,5 @@ public class WinPrintClientPrintersController extends BaseController
{
return toAjax(winPrintClientPrintersService.deleteWinPrintClientPrintersByIds(ids));
}
}

39
win-print/src/main/java/com/win/print/controller/WinPrintTasksLogsController.java

@ -141,9 +141,10 @@ public class WinPrintTasksLogsController extends BaseController {
@ResponseBody
public AjaxResult print(@PathVariable("id") Long id) {
WinPrintTasksLogs tasksLog = winPrintTasksLogsService.selectWinPrintTasksLogsById(id);
if (ObjectUtil.isNotEmpty(tasksLog)) {
if (null!=tasksLog) {
tasksLog.setPrintTime(DateUtil.date());
tasksLog.setTaskStatus("0");
winPrintTasksLogsService.updateWinPrintTasksLogs(tasksLog);
return AjaxResult.success("打印已经发送到打印机!");
} else {
return AjaxResult.error("打印失败!没有可以补打的记录!");
@ -156,24 +157,24 @@ public class WinPrintTasksLogsController extends BaseController {
public AjaxResult doprint(@RequestParam("id") Long id,@RequestParam("printer") String printer) {
WinPrintTasksLogs tasksLog = winPrintTasksLogsService.selectWinPrintTasksLogsById(id);
if (ObjectUtil.isNotEmpty(tasksLog)) {
try {
FileInputStream fileIn = new FileInputStream(printer);
DocPrintJob pringJobByName = PrinterUtil.getPringJobByName(tasksLog.getPrinterName());
DocFlavor docFlavor = PrinterUtil.getDocFlavor(EnumDocFlavor.IS_AUTOSENSE);
PrintRequestAttributeVo printAttribute = iSettingsService.getPrintAttribute(tasksLog.getSettingCode(), tasksLog.getModelPage(), tasksLog.getIsPageRolated(), tasksLog.getCopyCounts());
PrintRequestAttributeSet printRequestAttribute = PrinterUtil.getPrintRequestAttribute(printAttribute, tasksLog.getTaskId());
PrinterUtil.sendJobtoPrinter(pringJobByName, PrinterUtil.getSimpleDoc(fileIn, docFlavor), printRequestAttribute);
fileIn.close();
return AjaxResult.success("打印已经发送到打印机!");
} catch (FileNotFoundException fe) {
return AjaxResult.error("打印失败!打印文件不存在或者已经被删除!");
} catch (SecurityException se) {
return AjaxResult.error("打印失败!打印文件访问受限!");
} catch (PrintException e) {
return AjaxResult.error("打印失败!打印机错误!");
} catch (IOException e) {
return AjaxResult.error("打印失败!文件IO错误!");
}
// try {
// FileInputStream fileIn = new FileInputStream(printer);
//// DocPrintJob pringJobByName = PrinterUtil.getPringJobByName(tasksLog.getPrinterName());
//// DocFlavor docFlavor = PrinterUtil.getDocFlavor(EnumDocFlavor.IS_AUTOSENSE);
//// PrintRequestAttributeVo printAttribute = iSettingsService.getPrintAttribute(tasksLog.getSettingCode(), tasksLog.getModelPage(), tasksLog.getIsPageRolated(), tasksLog.getCopyCounts());
//// PrintRequestAttributeSet printRequestAttribute = PrinterUtil.getPrintRequestAttribute(printAttribute, tasksLog.getTaskId());
//// PrinterUtil.sendJobtoPrinter(pringJobByName, PrinterUtil.getSimpleDoc(fileIn, docFlavor), printRequestAttribute);
// fileIn.close();
// return AjaxResult.success("打印已经发送到打印机!");
// } catch (FileNotFoundException fe) {
// return AjaxResult.error("打印失败!打印文件不存在或者已经被删除!");
// } catch (SecurityException se) {
// return AjaxResult.error("打印失败!打印文件访问受限!");
// } catch (PrintException e) {
// return AjaxResult.error("打印失败!打印机错误!");
// } catch (IOException e) {
return AjaxResult.error("打印失败!文件IO错误!");
// }
} else {
return AjaxResult.error("打印失败!没有可以补打的记录!");

30
win-print/src/main/java/com/win/print/domain/WinPrintModel.java

@ -69,6 +69,12 @@ public class WinPrintModel extends BaseEntity
private String mPageValue;
@Excel(name = "是否横向")
private String isPageRotate;
@Excel(name = "字体名称")
private String fontName;
@Excel(name = "字体大小")
private int fontSize;
@Excel(name = "是否加粗")
private String fontBlock;
private String mData;
/** 模版参数管理信息 */
private List<WinPrintModelParams> winPrintModelParamsList;
@ -243,6 +249,30 @@ public class WinPrintModel extends BaseEntity
this.mData = mData;
}
public String getFontName() {
return fontName;
}
public void setFontName(String fontName) {
this.fontName = fontName;
}
public int getFontSize() {
return fontSize;
}
public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}
public String getFontBlock() {
return fontBlock;
}
public void setFontBlock(String fontBlock) {
this.fontBlock = fontBlock;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)

77
win-print/src/main/java/com/win/print/service/PrintService.java

@ -1,77 +0,0 @@
package com.win.print.service;
public class PrintService {
// // 传入文件和打印机名称
// 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();
// }
}

95
win-print/src/main/java/com/win/print/service/PrintServiceWin.java

@ -0,0 +1,95 @@
package com.win.print.service;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;
import java.awt.print.PrinterJob;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class PrintServiceWin {
private static final Logger log = LoggerFactory.getLogger(PrintTaskProcesser.class);
// 传入文件和打印机名称
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();
}
}

94
win-print/src/main/java/com/win/print/service/PrintTaskProcesser.java

@ -1,31 +1,35 @@
package com.win.print.service;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.itextpdf.io.IOException;
import com.win.common.config.WinConfig;
import com.win.common.utils.http.HttpUtils;
import com.win.print.domain.*;
import com.win.print.util.PrintTaskCacheUtil;
import cn.hutool.core.io.FileUtil;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfStream;
import com.win.print.domain.PrintRequestAttributeVo;
import com.win.print.domain.WinPrintTasksLogs;
import com.win.print.util.DataUnitl;
import com.win.print.util.PdfPrintUtil;
import com.win.print.util.PrinterUtil;
import com.win.print.util.WinPrintJobListener;
import jakarta.annotation.Resource;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.*;
import javax.print.attribute.PrintRequestAttributeSet;
import java.awt.*;
import java.awt.print.PrinterException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLStreamHandler;
import java.util.Optional;
/**
* 打印队列的处理和日志处理
@ -44,37 +48,49 @@ public class PrintTaskProcesser {
* */
@Value("${win.clientCode}")
private String clientCode;
@Value("${win.path.print}")
private String printFilepath; //生成的打印文件存储路径
@Scheduled(fixedRate = 3000)
public void process(){
public void process() throws IOException, PrinterException, PrintException {
WinPrintTasksLogs tasksLogs = iPrintTasksLogsService.selectWinPrintTasksLogsByClientCode(clientCode);
if(null!=tasksLogs){
try {
String url=tasksLogs.getIpAddr()+"/"+tasksLogs.getDataFile();
HttpRequest get = HttpUtil.createGet(url);
HttpResponse response = get.execute();
InputStream inputStream = response.bodyStream();
//FileInputStream fileIn = new FileInputStream(tasksLogs.getDataFile());
DocPrintJob pringJobByName = PrinterUtil.getPringJobByName(tasksLogs.getPrinterName());
DocFlavor docFlavor = PrinterUtil.getDocFlavor(EnumDocFlavor.IS_AUTOSENSE);
PrintRequestAttributeVo printAttribute = iSettingsService.getPrintAttribute(tasksLogs.getSettingCode(), tasksLogs.getModelPage(), tasksLogs.getIsPageRolated(), tasksLogs.getCopyCounts());
PrintRequestAttributeSet printRequestAttribute = PrinterUtil.getPrintRequestAttribute(printAttribute,tasksLogs.getTaskId());
PrinterUtil.sendJobtoPrinter(pringJobByName, PrinterUtil.getSimpleDoc(inputStream, docFlavor), printRequestAttribute);
//fileIn.close();
log.info("PrintTaskProcesser-打印任务成功发送!",tasksLogs.getTaskId());
iPrintTasksLogsService.setStatusLock(tasksLogs.getId(),"1");
inputStream.close();
}catch(Exception e){
log.error("PrintTaskProcesser-error",e.toString());
iPrintTasksLogsService.setStatusLock(tasksLogs.getId(),"2");
String filePath = DataUnitl.getWorkingDir(printFilepath)+"/"+tasksLogs.getDataFile();
File file=new File(filePath);
String type = Optional.ofNullable(FileUtil.getType(file)).orElse("");
PrinterUtil printerUtil = new PrinterUtil();
PrintService printService = printerUtil.getPrintService(tasksLogs.getPrinterName());
PrintRequestAttributeVo printAttribute = iSettingsService.getPrintAttribute(tasksLogs.getSettingCode(), tasksLogs.getModelPage(), tasksLogs.getIsPageRolated(), tasksLogs.getCopyCounts());
PrintRequestAttributeSet printRequestAttribute = printerUtil.getPrintRequestAttribute(printAttribute,"winTask");
if("pdf".equalsIgnoreCase(type)){
PdfPrintUtil pdfPrintUtil=new PdfPrintUtil();
pdfPrintUtil.print(file,printService,printRequestAttribute);
}else{
DocPrintJob pringJobByName = printService.createPrintJob();
Doc simpleDoc = new SimpleDoc(new FileInputStream(file), getDocFlavor(type), null);
pringJobByName.print(simpleDoc, printRequestAttribute);
iPrintTasksLogsService.setStatusLock(tasksLogs.getId(), "1");
}
log.info("打印{}文档,文件名称:{}", type,filePath);
log.info("{}-打印任务成功发送到打印机!",tasksLogs.getTaskId());
iPrintTasksLogsService.setStatusLock(tasksLogs.getId(),"1");
}else{
//log.info("PrintTaskProcesser-打印任务池无任务!");
log.info("*****打印服务任务运行中*****");
}
}
/*
* 获取打印机配置
* */
private DocFlavor getDocFlavor(String type){
if("JPEG".equalsIgnoreCase(type)|| "JPG".equalsIgnoreCase(type)){
return DocFlavor.INPUT_STREAM.JPEG;
}
if("GIF".equalsIgnoreCase(type)){
return DocFlavor.INPUT_STREAM.GIF;
}
if("PNG".equalsIgnoreCase(type)){
return DocFlavor.INPUT_STREAM.PNG;
}
if("TXT".equalsIgnoreCase(type)||"HTML".equalsIgnoreCase(type)){
return DocFlavor.INPUT_STREAM.TEXT_HTML_UTF_8;
}
return DocFlavor.INPUT_STREAM.AUTOSENSE;
}
}

54
win-print/src/main/java/com/win/print/util/PdfModelUitl.java

@ -63,7 +63,7 @@ public class PdfModelUitl {
* 待填充的PDF模板文档
*/
public void pdfMdelFromRender(List<WinPrintModelParams> paramsList,File tempFile, JSONObject data, String modelName, String templatePath) throws IOException {
public void pdfMdelFromRender(List<WinPrintModelParams> paramsList,File tempFile, JSONObject data, String modelName, String templatePath,int fontSize,String fontName) throws IOException {
PdfReader reader = new PdfReader(templatePath+"/"+modelName);
PdfWriter writer = new PdfWriter(tempFile);
PdfDocument pdf = new PdfDocument(reader, writer);
@ -76,23 +76,14 @@ public class PdfModelUitl {
String value = Optional.ofNullable(data.getString(item.getParamCode())).orElse("");
if(null!=field) {
Rectangle rtl = field.getWidgets().get(0).getRectangle().toRectangle(); // 获取表单域的xy坐标
field.setFont(defaultFont());
if(Optional.ofNullable(field.getFontSize()).isEmpty()){
field.setFontSize(16);
}
field.setFont(getFont(fontName));
field.setFontSize(fontSize);
//field.setFontSizeAutoScale()
if ("QRIMG".equals(item.getParamType())) {
//渲染Qr图片
if(!value.isEmpty() && !value.isBlank()) {
try {
// JSONObject jsonObject = JSONObject.parseObject(Optional.ofNullable(item.getParamDesc()).orElse("{\"width\":\"172\",\"height\":\"172\",\"type\":\"png\"}"));
// int width = 172;
// int height = 172;
// String type = "png";
// if (null != jsonObject) {
// width = Integer.valueOf(Optional.ofNullable(jsonObject.getString("width")).orElse("172"));
// height = Integer.valueOf(Optional.ofNullable(jsonObject.getString("height")).orElse("172"));
// type = Optional.ofNullable(jsonObject.getString("type")).orElse("png");
// }
BufferedImage bufferedImage = qrCodeService.generateQRCode(value, (int)rtl.getWidth(), (int)rtl.getHeight());
byte[] imgBytes = qrCodeService.getImgBuffer("png", bufferedImage);
com.itextpdf.layout.element.Image image =new com.itextpdf.layout.element.Image(ImageDataFactory.create(imgBytes));//getImage(field, bufferedImage, rtl);
@ -281,6 +272,7 @@ public class PdfModelUitl {
//PdfFontFactory.register(DEFAULT_FONT_PATH);
//baseFont = PdfFontFactory.createFont(DEFAULT_FONT_PATH, PdfEncodings.IDENTITY_H);
baseFont=PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");
//baseFont=PdfFontFactory.createFont("SimHei", "UniGB-UCS2-H");
} catch (Exception e) {
throw new RuntimeException("无法获取默认字体:" + e.getMessage(),e);
}
@ -292,23 +284,23 @@ public class PdfModelUitl {
* @return PdfFont
*/
String extendPath = "D:\\fonts\\";
private PdfFont getFont(PdfFont font) {
String fontName = font.getFontProgram().getFontNames().getFontName();
String fontKey = FONTS_MAP.get(fontName);
if(fontKey==null){
font = defaultFont();
}else {
try {
if(fontKey.toLowerCase().endsWith("ttc")){
font = PdfFontFactory.createFont(this.extendPath + fontKey + ",0", PdfEncodings.IDENTITY_H);
}else {
font = PdfFontFactory.createFont(this.extendPath + fontKey, PdfEncodings.IDENTITY_H);
}
} catch (IOException e) {
font = defaultFont();
e.printStackTrace();
}
}
private PdfFont getFont(String fontName) {
PdfFont font = defaultFont();
// String fontKey = FONTS_MAP.get(fontName);
// if(fontKey==null){
// font = defaultFont();
// }else {
// try {
// if(fontKey.toLowerCase().endsWith("ttc")){
// font = PdfFontFactory.createFont(this.extendPath + fontKey + ",0", PdfEncodings.IDENTITY_H);
// }else {
// font = PdfFontFactory.createFont(this.extendPath + fontKey, PdfEncodings.IDENTITY_H);
// }
// } catch (IOException e) {
// font = defaultFont();
// e.printStackTrace();
// }
// }
return font;
}
/**

41
win-print/src/main/java/com/win/print/util/PdfPrintUtil.java

@ -0,0 +1,41 @@
package com.win.print.util;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import javax.print.PrintService;
import javax.print.attribute.PrintRequestAttributeSet;
import java.awt.print.*;
import java.io.File;
import java.io.IOException;
public class PdfPrintUtil {
public void print(File pdfFile, PrintService printService, PrintRequestAttributeSet attrs) throws IOException {
// 加载PDF文档
PDDocument document = PDDocument.load(pdfFile);
try {
// 创建一个打印任务
PrinterJob job = PrinterJob.getPrinterJob();
PDFPrintable pdfPrintable = new PDFPrintable(document);
// 查找并设置打印机
if (printService != null) {
job.setPrintService(printService);
}
job.setPrintable(pdfPrintable);
job.setJobName("标签打印");
job.setCopies(1);
// 执行打印
job.print(attrs);
} catch (PrinterException printerException) {
throw new RuntimeException(printerException);
} finally {
// 关闭PDF文档
document.close();
}
}
}

49
win-print/src/main/java/com/win/print/util/PrinterUtil.java

@ -21,7 +21,11 @@ import java.awt.print.PrinterJob;
public class PrinterUtil {
private static final Logger log = LoggerFactory.getLogger(PrinterUtil.class);
public static DocPrintJob getPringJobByName(String printerName) {
public DocPrintJob getPringJobByName(String printerName) {
return getPrintService(printerName).createPrintJob();
}
public PrintService getPrintService(String printerName) {
PrintService printService = null;
//获得本台电脑连接的所有打印机
PrintService[] printServices = PrinterJob.lookupPrintServices();
@ -45,9 +49,8 @@ public class PrinterUtil {
}
}
}
return printService.createPrintJob();
return printService;
}
/**
* Copies: 指定要打印的副本数量
* OrientationRequested: 指定页面的方向如横向或纵向
@ -58,29 +61,29 @@ public class PrinterUtil {
* PrinterResolution: 指定打印机的分辨率
* Chromaticity: 指定颜色模式如彩色或黑白
*/
public static PrintRequestAttributeSet getPrintRequestAttribute(PrintRequestAttributeVo atrrSet,String jobName) {
public PrintRequestAttributeSet getPrintRequestAttribute(PrintRequestAttributeVo atrrSet,String jobName) {
// 设置打印参数
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(atrrSet.getCopyCount())); //份数
aset.add(atrrSet.getPaperType().getMediaSizeName());
// aset.add(atrrSet.getPaperType().getMediaSizeName());
aset.add(new JobName(jobName,null));
if (atrrSet.getIsDuplicates()) {
aset.add(Sides.DUPLEX);//单双面
} else {
aset.add(Sides.ONE_SIDED);
}
if (atrrSet.getIsPortrait()) {
aset.add(OrientationRequested.PORTRAIT);//横向
} else {
aset.add(OrientationRequested.LANDSCAPE);//纵向
}
// if (atrrSet.getIsDuplicates()) {
// aset.add(Sides.DUPLEX);//单双面
// } else {
// aset.add(Sides.ONE_SIDED);
// }
// if (atrrSet.getIsPortrait()) {
// aset.add(OrientationRequested.PORTRAIT);//横向
// } else {
// aset.add(OrientationRequested.LANDSCAPE);//纵向
// }
return aset;
}
/**
* 打印的文件数据类型
**/
public static DocFlavor getDocFlavor(EnumDocFlavor flavorType) {
public DocFlavor getDocFlavor(EnumDocFlavor flavorType) {
// 设置打印格式,如果未确定类型,可选择autosense
DocFlavor.INPUT_STREAM type;
switch (flavorType) {
@ -120,16 +123,14 @@ public class PrinterUtil {
* 获取打印文档
* */
public static Doc getSimpleDoc(Object printData, DocFlavor docFlavor) throws PrintException {
if(ObjectUtil.isEmpty(printData) || ObjectUtil.isEmpty(docFlavor) ){
throw new PrintException("空的打印内容!不能打印!");
}
public Doc getSimpleDoc(Object printData, DocFlavor docFlavor) throws PrintException {
return new SimpleDoc(printData,docFlavor,null);
}
/**
* 发送作业到打印机
*/
public static boolean sendJobtoPrinter(DocPrintJob printJob, PrintJobListener printJobListener, Doc doc, PrintRequestAttributeSet propertySet) {
public boolean sendJobtoPrinter(DocPrintJob printJob, PrintJobListener printJobListener, Doc doc, PrintRequestAttributeSet propertySet) {
try {
printJob.addPrintJobListener(printJobListener);
printJob.print(doc, propertySet);
@ -138,7 +139,7 @@ public class PrinterUtil {
return false;
}
}
public static boolean sendJobtoPrinterNormal(DocPrintJob printJob, Doc doc, PrintRequestAttributeSet propertySet) {
public boolean sendJobtoPrinterNormal(DocPrintJob printJob, Doc doc, PrintRequestAttributeSet propertySet) {
try {
printJob.print(doc, propertySet);
return true;
@ -146,7 +147,7 @@ public class PrinterUtil {
return false;
}
}
public static boolean sendJobtoPrinter(DocPrintJob printJob, Doc doc, PrintRequestAttributeSet propertySet) {
public boolean sendJobtoPrinter(DocPrintJob printJob, Doc doc, PrintRequestAttributeSet propertySet) {
WinPrintJobListener printJobListener=new WinPrintJobListener();
try {
printJob.addPrintJobListener(printJobListener);
@ -156,7 +157,7 @@ public class PrinterUtil {
return false;
}
}
public static MediaSize getStardMediaSize(String pageName){
public static MediaSize getStardMediaSize(String pageName){
if("A0".equals(pageName)){
return MediaSize.ISO.A0;
}

2
win-print/src/main/java/com/win/print/util/WinPrintJobListener.java

@ -24,7 +24,7 @@ public class WinPrintJobListener implements javax.print.event.PrintJobListener {
@Override
public void printJobFailed(PrintJobEvent pje) {
log.warn("通知客户该作业未成功完成,必须重新提交。");
log.warn("通知客户该作业未成功完成,必须重新提交{}。",pje.getPrintJob());
}
@Override

2
win-print/src/main/resources/mapper/print/WinPrintClientPrintersMapper.xml

@ -109,7 +109,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<delete id="deleteWinPrintClientPrintersByIds" parameterType="String">
delete from win_print_client_printers where id in
<foreach item="ids" collection="array" open="(" separator="," close=")">
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>

15
win-print/src/main/resources/mapper/print/WinPrintModelMapper.xml

@ -22,6 +22,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="mPageValue" column="m_page_value" />
<result property="isPageRotate" column="is_page_rotate" />
<result property="mData" column="m_data" />
<result property="fontName" column="font_name" />
<result property="fontSize" column="font_size" />
<result property="fontBlock" column="font_block" />
</resultMap>
<resultMap type="WinPrintModelSimple" id="WinPrintModelWinPrintSimple">
<result property="mName" column="m_name" />
@ -49,7 +52,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<sql id="selectWinPrintModelVo">
select tenant_id, revision, created_by, created_time, updated_by, updated_time, id, m_name, m_code, m_type, m_filename, is_dyparam,m_type_src,m_page_size,m_page_value,is_page_rotate,m_data from win_print_model
select tenant_id, revision, created_by, created_time, updated_by, updated_time, id, m_name, m_code, m_type, m_filename, is_dyparam,m_type_src,m_page_size,m_page_value,is_page_rotate,m_data,font_name,font_size,font_block from win_print_model
</sql>
<select id="selectWinPrintModelList" parameterType="WinPrintModel" resultMap="WinPrintModelResult">
@ -102,7 +105,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="mPageValue != null and mPageValue != ''">m_page_value,</if>
<if test="isPageRotate != null and isPageRotate != ''">is_page_rotate,</if>
<if test="mData != null and mData != ''">m_data,</if>
<if test="fontName != null and fontName != ''">font_name,</if>
<if test="fontSize != null ">font_size,</if>
<if test="fontBlock != null and fontBlock != ''">font_block,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="tenantId != null">#{tenantId},</if>
@ -121,6 +126,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="mPageValue != null and mPageValue != ''">#{mPageValue},</if>
<if test="isPageRotate != null and isPageRotate != ''">#{isPageRotate},</if>
<if test="mData != null and mData != ''">#{mData},</if>
<if test="fontName != null and fontName != ''">#{fontName},</if>
<if test="fontSize != null ">#{fontSize},</if>
<if test="fontBlock != null and fontBlock != ''">#{fontBlock},</if>
</trim>
</insert>
@ -143,6 +151,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="mPageValue != null and mPageValue != ''">m_page_value=#{mPageValue},</if>
<if test="isPageRotate != null and isPageRotate != ''">is_page_rotate=#{isPageRotate},</if>
<if test="mData != null and mData != ''">m_data=#{mData},</if>
<if test="fontName != null and fontName != ''">font_name=#{fontName},</if>
<if test="fontSize != null ">font_size=#{fontSize},</if>
<if test="fontBlock != null and fontBlock != ''">font_block=#{fontBlock},</if>
</trim>
where id = #{id}
</update>

2
win-print/src/main/resources/templates/print/logmanager/logmanager.html

@ -102,7 +102,7 @@
title: '客户端编码'
},
{
field: 'taskID',
field: 'taskId',
title: '任务ID'
},
{

9
win-print/src/main/resources/templates/print/modelmanager/add.html

@ -97,7 +97,14 @@
</div>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<label class="col-sm-3 control-label">字体大小:</label>
<div class="col-sm-8">
<input name="fontSize" class="form-control" type="number" >
</div>
</div>
</div>
<!-- <div class="col-xs-12">-->
<!-- <div class="form-group">-->
<!-- <label class="col-sm-3 control-label is-required">是否动态参数:</label>-->

9
win-print/src/main/resources/templates/print/modelmanager/edit.html

@ -89,7 +89,14 @@
</div>
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<label class="col-sm-3 control-label">字体大小:</label>
<div class="col-sm-8">
<input name="fontSize" class="form-control" type="number" th:field="*{fontSize}" >
</div>
</div>
</div>
<!-- <div class="col-xs-12">-->
<!-- <div class="form-group">-->
<!-- <label class="col-sm-3 control-label is-required">是否动态参数:</label>-->

Loading…
Cancel
Save