Commit dbbf101b authored by 周亚武's avatar 周亚武

url pdf打印

parent ac26adaf
...@@ -143,6 +143,30 @@ ...@@ -143,6 +143,30 @@
<version>3.0.9</version> <version>3.0.9</version>
</dependency> </dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>RELEASE</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
</dependencies> </dependencies>
......
...@@ -44,28 +44,47 @@ public class ApiController extends BaseAbstractApiController { ...@@ -44,28 +44,47 @@ public class ApiController extends BaseAbstractApiController {
String getType = (String) reqMap.getOrDefault("GetType", ""); String getType = (String) reqMap.getOrDefault("GetType", "");
String reqJson = (String) reqMap.getOrDefault("PrinterJson", ""); String reqJson = (String) reqMap.getOrDefault("PrinterJson", "");
String printerName = (String) reqMap.getOrDefault("printerName", ""); String printerName = (String) reqMap.getOrDefault("printerName", "");
log.info("req==>getType:{},body=>{}", getType, JSON.toJSONString(reqMap)); String waitTime = (String) reqMap.getOrDefault("waitTime", "120");
String signType = (String) reqMap.getOrDefault("signType", "");
String socialType = (String) reqMap.getOrDefault("socialType", "");
log.info("getType:" + getType);
try { try {
switch (BusizTypeEnum.getByValue(getType)) { switch (BusizTypeEnum.getByValue(getType)) {
case BUSIZ_ASSESSMENT: case BUSIZ_CAPTURE: //高拍仪
ApiResp<Object> assessResp = handle(JSON.toJSONString(reqMap), "busizAssessmentReqHandler"); ApiResp<Object> captureResp = handle(waitTime, "busizCaptureReqHandler");
return captureResp;
case BUSIZ_ASSESSMENT: //评价
ApiResp<Object> assessResp = handle(JSON.parseObject(reqJson, new TypeReference<PrintReq>() {
}), "busizAssessmentReqHandler");
return assessResp; return assessResp;
case BUSIZ_PRINT: case BUSIZ_PRINT: //打印
ApiResp<Object> rest = handle(JSON.parseObject(reqJson, PrintReq.class), "busizPrintReqHandler"); ApiResp<Object> rest = handle(JSON.parseObject(reqJson, new TypeReference<PrintReq>() {
}), "busizPrintReqHandler");
return rest; return rest;
case BUSIZ_PRINTLIST: case BUSIZ_PRINTLIST: //打印机列表
//获取打印机列表 //获取打印机列表
ApiResp<Object> printListResp = handle("", "busizPrintListReqHandler"); ApiResp<Object> printListResp = handle("", "busizPrintListReqHandler");
return printListResp; return printListResp;
case BUSIZ_PRINT_QUEUE: case BUSIZ_PRINT_QUEUE: //查看指定打印机打印队列
ApiResp<Object> printQueueResp = handle(printerName, "busizPrintQueueReqHandler"); ApiResp<Object> printQueueResp = handle(printerName, "busizPrintQueueReqHandler");
return printQueueResp; return printQueueResp;
case BUSIZ_IDCARD_RECOGNITION: case BUSIZ_IDCARD_RECOGNITION: //身份证读取
ApiResp<Object> idCardResp = handle("", "busizIdcardRecognitionReqHandler"); ApiResp<Object> idCardResp = handle("", "busizIdcardRecognitionReqHandler");
return idCardResp; return idCardResp;
case BUSIZ_CAPTURE: case BUSIZ_CAMERA: //双目摄像头
ApiResp<Object> captureResp = handle("", "busizCaptureReqHandler"); log.info("双目摄像头");
return captureResp; return null;
case BUSIZ_SIGN: //签名板
ApiResp<Object> signResp = handle(signType, "busizSignReqHandler");
return signResp;
case BUSIZ_SOCIAL: //社保卡 德卡T10三合一
ApiResp<Object> socialResp = handle(socialType, "busizSocialReqHandler");
return socialResp;
case BUSIZ_FINGER: //指纹
log.info("指纹");
return null;
} }
} catch (Exception e) { } catch (Exception e) {
log.error("接收数据失败", e); log.error("接收数据失败", e);
......
...@@ -16,6 +16,10 @@ public enum BusizTypeEnum { ...@@ -16,6 +16,10 @@ public enum BusizTypeEnum {
BUSIZ_PRINTLIST("73", "打印机列表"), BUSIZ_PRINTLIST("73", "打印机列表"),
BUSIZ_CAPTURE("3", "高拍仪"), BUSIZ_CAPTURE("3", "高拍仪"),
BUSIZ_PRINT_QUEUE("74", "查看指定打印机打印队列"), BUSIZ_PRINT_QUEUE("74", "查看指定打印机打印队列"),
BUSIZ_SIGN("61", "签名板"),
BUSIZ_CAMERA("51", "双目摄像头"),
BUSIZ_FINGER("41", "指纹"),
BUSIZ_SOCIAL("31", "社保卡"),
; ;
private String value; private String value;
private String desc; private String desc;
......
package com.mortals.xhx.common.utils;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import java.io.*;
import static com.mortals.framework.service.IMessageProduceService.log;
/**
* @author ZYW
* @date 2024-10-30 15:04
*/
public class PdfUtil {
/**
* windows系统word转pdf
* @param wordPath 转换后的pdf文件
* @param pdfPath word源文件
*/
public static void winWordToPdf( String wordPath, String pdfPath) {
File inputWord = new File(wordPath);
File outputFile = new File(pdfPath);
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
outputStream.close();
log.info("word转换成PDF成功!");
} catch (Exception e) {
log.error("word转pdf失败",e);
e.printStackTrace();
}
}
/**
* linux系统word转pdf
   * 使用LibreOffice转换。系统需安装LibreOffice
   * 转换命令 libreoffice --invisible --convert-to pdf --outdir output_dir source_path
   * 转换后的pdf文件名使用的是源文件的名称,所以如果要指定输出文件名称,就需把源文件名称改成想要输出的名称
* @param wordPath 转换后的pdf文件夹
* @param pdfPath word源文件
*/
public static void linuxWordToPdf(String wordPath, String pdfPath) {
// 构建LibreOffice的命令行工具命令
String command = "libreoffice --invisible --convert-to pdf --outdir " + pdfPath + " " + wordPath;
log.info(command);
// 执行转换命令
try {
executeLinuxCmd(command);
log.info("word转换成PDF成功!");
} catch (Exception e) {
log.error("linuxWordToPdf linux环境word转换为pdf时出现异常:", e);
}
}
/**
* 执行命令行
*
* @param cmd 命令行
* @return
*/
private static boolean executeLinuxCmd(String cmd) {
try {
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
} catch (InterruptedException e) {
log.error("executeLinuxCmd 执行Linux命令异常:", e);
Thread.currentThread().interrupt();
return false;
} catch (IOException e) {
log.error("获取系统命令执行环境异常", e);
}
return true;
}
/**
* word转pdf
* @param imgPath 图片路径
* @param pdfPath pdf路径
*/
public static void imgToPdf(String imgPath, String pdfPath){
try {
// 创建PDF文档
PDDocument document = new PDDocument();
// 添加一个页面
PDPage page = new PDPage();
document.addPage(page);
// 加载图片并添加到PDF页面上
PDImageXObject pdImage = PDImageXObject.createFromFile(imgPath, document);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight());
contentStream.close();
// 保存PDF文档
document.save(pdfPath);
document.close();
log.info("图片转换成PDF成功!");
} catch (IOException e) {
log.error("转换过程中发生错误:" + e.getMessage());
}
}
}
package com.mortals.xhx.module.print.service.PrintComponent; package com.mortals.xhx.module.print.service.PrintComponent;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException; import com.mortals.framework.exception.AppException;
import com.mortals.xhx.common.code.PrintTypeEnum; import com.mortals.xhx.common.code.PrintTypeEnum;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
...@@ -20,7 +21,7 @@ public abstract class BasePrintComponent { ...@@ -20,7 +21,7 @@ public abstract class BasePrintComponent {
} }
public abstract void print(ComponentCons cons); public abstract Rest<Void> print(ComponentCons cons);
protected PrintService getPrintService(ComponentCons cons) { protected PrintService getPrintService(ComponentCons cons) {
PrintService printService = null; PrintService printService = null;
...@@ -68,4 +69,5 @@ public abstract class BasePrintComponent { ...@@ -68,4 +69,5 @@ public abstract class BasePrintComponent {
public abstract String getType(); public abstract String getType();
} }
...@@ -2,8 +2,13 @@ package com.mortals.xhx.module.print.service.PrintComponent; ...@@ -2,8 +2,13 @@ package com.mortals.xhx.module.print.service.PrintComponent;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil; import cn.hutool.http.HttpUtil;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.common.code.PrintTypeEnum; import com.mortals.xhx.common.code.PrintTypeEnum;
import com.mortals.xhx.common.utils.PdfUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import javax.print.*; import javax.print.*;
import javax.print.attribute.DocAttributeSet; import javax.print.attribute.DocAttributeSet;
...@@ -11,6 +16,11 @@ import javax.print.attribute.HashDocAttributeSet; ...@@ -11,6 +16,11 @@ import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies; import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.Sides;
import java.awt.print.*;
import java.io.File;
import java.io.IOException;
@Slf4j @Slf4j
public class UrlPrintComponent extends BasePrintComponent { public class UrlPrintComponent extends BasePrintComponent {
...@@ -19,33 +29,162 @@ public class UrlPrintComponent extends BasePrintComponent { ...@@ -19,33 +29,162 @@ public class UrlPrintComponent extends BasePrintComponent {
super(type); super(type);
} }
public static String word[] = {"doc", "dot", "wps", "wpt", "docx", "dotx", "docm", "dotm"};
public static String imgs[] = {"jpg", "png", "jpeg", "gif"};
public static String pdf[] = {"pdf"};
// 获取当前系统名称
static String osName = System.getProperty("os.name").toLowerCase();
@Override @Override
public void print(ComponentCons cons) { public Rest<Void> print(ComponentCons cons) {
PrintService printService = getPrintService(cons);
//通过网络下载附件地址
byte[] fileBytes = HttpUtil.downloadBytes(cons.getUrl());
//获取文件后缀 //获取文件后缀
String suffixName = FileUtil.getSuffix(cons.getUrl()); String suffixName = FileUtil.getSuffix(cons.getUrl());
log.info("file lens:{}", fileBytes.length);
String samplePath = "/root/sourceFile."+suffixName; //源文件下载地址
//通过网络下载附件地址
File file = HttpUtil.downloadFileFromUrl(cons.getUrl(),"/root/sourceFile."+suffixName);
log.info("file name:{}",file.getAbsolutePath());
log.info("file suffixName:{}", suffixName); log.info("file suffixName:{}", suffixName);
String pdfPath = "/root/target.pdf";
//判断文件类型是否为doc pdf jpg png 等
if (this.isExsitArry(suffixName, word)) {
// 根据系统选择执行方法
if (osName.contains("win")) {
PdfUtil.winWordToPdf(samplePath,pdfPath);
} else if (osName.contains("nux") || osName.contains("nix")) {
pdfPath = "/root/sourceFile.pdf"; //linux下不会指定新文件名称 会以原文件名+.pdf生成一个新文件
PdfUtil.linuxWordToPdf(samplePath,"/root/");
}
} else if (this.isExsitArry(suffixName, pdf)) {
pdfPath = samplePath;
}else if(this.isExsitArry(suffixName, imgs)){
PdfUtil.imgToPdf(samplePath,pdfPath);
}
//打印文件 PDDocument document = null;
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
DocPrintJob job = printService.createPrintJob();
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
DocAttributeSet das = new HashDocAttributeSet();
pras.add(new Copies(1));
Doc doc = new SimpleDoc(fileBytes, flavor, das);
try { try {
job.print(doc, pras); // 加载PDF文档
} catch (PrintException e) { File pdfFile = new File(pdfPath);
throw new RuntimeException(e); document = PDDocument.load(pdfFile);
// 创建一个打印任务
PrinterJob job = PrinterJob.getPrinterJob();
// 查找并设置打印机
PrintService defaultPrintService = getPrintService(cons);
if (defaultPrintService != null) {
job.setPrintService(defaultPrintService);
}else {
return Rest.fail("未找到打印机");
}
job.setJobName(pdfFile.getName());
//设置纸张
PDFPrintable pdfPrintable = new PDFPrintable(document);
//设置多页打印
Book book = new Book();
PageFormat pageFormat = new PageFormat();
Paper paper = getPaper();
pageFormat.setPaper(paper);
book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
job.setPageable(new PDFPageable(document));
job.setPageable(book);
job.setCopies(1);//设置打印份数
HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
pars.add(Sides.ONE_SIDED); // 设置单双页
pars.add(MediaSizeName.ISO_A4);//默认A4纸打印
// 执行打印
job.print(pars);
log.info("打印成功!");
return Rest.ok();
}catch (PrinterException e){
log.error("打印异常", e);
return Rest.fail("打印异常");
}catch (IOException e){
log.error("文件处理异常", e);
return Rest.fail("文件处理异常");
}finally {
if (document != null) {
try {
// 关闭PDF文档
document.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
} }
}
private Paper getPaper() {
Paper paper = new Paper();
// 默认为A4纸张,对应像素宽和高分别为 595, 842
int width = 595;
int height = 842;
// 设置边距,单位是像素,10mm边距,对应 28px
int marginLeft = 12;
int marginRight = 12;
int marginTop = 12;
int marginBottom = 12;
paper.setSize(width, height);
// 下面一行代码,解决了打印内容为空的问题
paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
return paper;
}
public boolean isExsitArry(String chex, String arry[]) {
for (String ex : arry) {
if (chex.equalsIgnoreCase(ex)) {
return true;
}
}
return false;
}
@Override @Override
public String getType() { public String getType() {
return PrintTypeEnum.PRINT_URL.getValue(); return PrintTypeEnum.PRINT_URL.getValue();
} }
public static void main(String[] args) throws PrinterException, IOException {
ComponentCons cons = new ComponentCons();
cons.setUrl("http://192.168.0.98:11091/file/fileupload/1730257895855.docx");
cons.setPapertype("A4");
new UrlPrintComponent("url").print(cons);
// // 加载PDF文档
// File pdfFile = new File("H:\\test.pdf");
// PDDocument document = PDDocument.load(pdfFile);
//
// // 创建一个打印任务
// PrinterJob job = PrinterJob.getPrinterJob();
// job.setPageable(new PDFPageable(document));
//
// // 查找并设置打印机
// PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
// if (defaultPrintService != null) {
// job.setPrintService(defaultPrintService);
// }
//
// // 执行打印
// job.print();
//
// // 关闭PDF文档
// document.close();
}
} }
...@@ -34,9 +34,7 @@ public class PrintServiceImpl implements PrintService { ...@@ -34,9 +34,7 @@ public class PrintServiceImpl implements PrintService {
BasePrintComponent basePrintComponent = BasePrintComponent.createType(printReq.getPrintertype()); BasePrintComponent basePrintComponent = BasePrintComponent.createType(printReq.getPrintertype());
ComponentCons componentCons = new ComponentCons(); ComponentCons componentCons = new ComponentCons();
BeanUtils.copyProperties(printReq,componentCons, BeanUtil.getNullPropertyNames(printReq)); BeanUtils.copyProperties(printReq,componentCons, BeanUtil.getNullPropertyNames(printReq));
basePrintComponent.print(componentCons); return basePrintComponent.print(componentCons);
//获取打印的类型
return Rest.ok();
} }
@Override @Override
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment