diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java new file mode 100644 index 0000000..9c67a59 --- /dev/null +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -0,0 +1,116 @@ +package com.casic.missiles.controller.system; + + +import cn.afterturn.easypoi.entity.ImageEntity; +import com.casic.missiles.utils.PdfUtil; +import org.springframework.stereotype.Controller; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.*; + + +@Controller +@RequestMapping("/poi") +public class PoiController { + + private String filepath="C:\\upload"; + + @RequestMapping(value = "/convertWordToPdf") + public void convertWordToPdf(HttpServletResponse response) throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + String pdfDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + pdfDir = filepath + File.separator + "pdf"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = PdfUtil.exportWord(tf.getPath(), wordDir, fileName, params); + String pdfFileName = "convertDocx2Pdf.pdf"; + String downloadFile = "pdf导出.pdf"; + + if (word.equals("")) { + Assert.notNull(word, "word路径不能为空"); + } else { + PdfUtil.convertDocx2Pdf(word, pdfDir + File.separator + pdfFileName); + response.setContentType("application/force-download");// 设置强制下载不打开 + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8")); //中文名称下载 + byte[] buffer = new byte[1024]; + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream outputStream = null; + try { + fis = new FileInputStream(pdfDir + File.separator + pdfFileName); + bis = new BufferedInputStream(fis); + outputStream = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + outputStream.write(buffer, 0, i); + i = bis.read(buffer); + } + outputStream.flush(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fis != null) { + File file = new File(pdfDir); + if (file != null && file.isFile() && file.exists()) { + file.delete(); + } + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } +} diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java new file mode 100644 index 0000000..9c67a59 --- /dev/null +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -0,0 +1,116 @@ +package com.casic.missiles.controller.system; + + +import cn.afterturn.easypoi.entity.ImageEntity; +import com.casic.missiles.utils.PdfUtil; +import org.springframework.stereotype.Controller; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.*; + + +@Controller +@RequestMapping("/poi") +public class PoiController { + + private String filepath="C:\\upload"; + + @RequestMapping(value = "/convertWordToPdf") + public void convertWordToPdf(HttpServletResponse response) throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + String pdfDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + pdfDir = filepath + File.separator + "pdf"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = PdfUtil.exportWord(tf.getPath(), wordDir, fileName, params); + String pdfFileName = "convertDocx2Pdf.pdf"; + String downloadFile = "pdf导出.pdf"; + + if (word.equals("")) { + Assert.notNull(word, "word路径不能为空"); + } else { + PdfUtil.convertDocx2Pdf(word, pdfDir + File.separator + pdfFileName); + response.setContentType("application/force-download");// 设置强制下载不打开 + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8")); //中文名称下载 + byte[] buffer = new byte[1024]; + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream outputStream = null; + try { + fis = new FileInputStream(pdfDir + File.separator + pdfFileName); + bis = new BufferedInputStream(fis); + outputStream = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + outputStream.write(buffer, 0, i); + i = bis.read(buffer); + } + outputStream.flush(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fis != null) { + File file = new File(pdfDir); + if (file != null && file.isFile() && file.exists()) { + file.delete(); + } + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } +} diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index 7465202..b43f761 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -131,6 +131,46 @@ spring-test 5.3.15 + + + cn.afterturn + easypoi-base + 4.3.0 + + + cn.afterturn + easypoi-web + 4.3.0 + + + cn.afterturn + easypoi-annotation + 4.3.0 + + + + org.docx4j + docx4j-export-fo + 6.1.0 + + + + + org.apache.poi + poi + 4.1.2 + + + org.apache.poi + poi-ooxml + 4.1.2 + + + + + + + org.springframework.boot spring-boot-starter-data-redis diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java new file mode 100644 index 0000000..9c67a59 --- /dev/null +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -0,0 +1,116 @@ +package com.casic.missiles.controller.system; + + +import cn.afterturn.easypoi.entity.ImageEntity; +import com.casic.missiles.utils.PdfUtil; +import org.springframework.stereotype.Controller; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.*; + + +@Controller +@RequestMapping("/poi") +public class PoiController { + + private String filepath="C:\\upload"; + + @RequestMapping(value = "/convertWordToPdf") + public void convertWordToPdf(HttpServletResponse response) throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + String pdfDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + pdfDir = filepath + File.separator + "pdf"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = PdfUtil.exportWord(tf.getPath(), wordDir, fileName, params); + String pdfFileName = "convertDocx2Pdf.pdf"; + String downloadFile = "pdf导出.pdf"; + + if (word.equals("")) { + Assert.notNull(word, "word路径不能为空"); + } else { + PdfUtil.convertDocx2Pdf(word, pdfDir + File.separator + pdfFileName); + response.setContentType("application/force-download");// 设置强制下载不打开 + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8")); //中文名称下载 + byte[] buffer = new byte[1024]; + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream outputStream = null; + try { + fis = new FileInputStream(pdfDir + File.separator + pdfFileName); + bis = new BufferedInputStream(fis); + outputStream = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + outputStream.write(buffer, 0, i); + i = bis.read(buffer); + } + outputStream.flush(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fis != null) { + File file = new File(pdfDir); + if (file != null && file.isFile() && file.exists()) { + file.delete(); + } + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } +} diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index 7465202..b43f761 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -131,6 +131,46 @@ spring-test 5.3.15 + + + cn.afterturn + easypoi-base + 4.3.0 + + + cn.afterturn + easypoi-web + 4.3.0 + + + cn.afterturn + easypoi-annotation + 4.3.0 + + + + org.docx4j + docx4j-export-fo + 6.1.0 + + + + + org.apache.poi + poi + 4.1.2 + + + org.apache.poi + poi-ooxml + 4.1.2 + + + + + + + org.springframework.boot spring-boot-starter-data-redis diff --git a/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java b/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java index 938b88a..502ce1d 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java @@ -105,7 +105,7 @@ } } else if ("3".equals(jsonObject1.getString("type"))) { //按部门查询用户id - List> list = userMapper.selectUsers(null, null, null, targetId); + List> list = userMapper.selectUsers(null, null, null,null, targetId); if (!CollectionUtils.isEmpty(list)) { list.stream().forEach(m -> { String id = String.valueOf(m.get("id")); diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java new file mode 100644 index 0000000..9c67a59 --- /dev/null +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -0,0 +1,116 @@ +package com.casic.missiles.controller.system; + + +import cn.afterturn.easypoi.entity.ImageEntity; +import com.casic.missiles.utils.PdfUtil; +import org.springframework.stereotype.Controller; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.*; + + +@Controller +@RequestMapping("/poi") +public class PoiController { + + private String filepath="C:\\upload"; + + @RequestMapping(value = "/convertWordToPdf") + public void convertWordToPdf(HttpServletResponse response) throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + String pdfDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + pdfDir = filepath + File.separator + "pdf"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = PdfUtil.exportWord(tf.getPath(), wordDir, fileName, params); + String pdfFileName = "convertDocx2Pdf.pdf"; + String downloadFile = "pdf导出.pdf"; + + if (word.equals("")) { + Assert.notNull(word, "word路径不能为空"); + } else { + PdfUtil.convertDocx2Pdf(word, pdfDir + File.separator + pdfFileName); + response.setContentType("application/force-download");// 设置强制下载不打开 + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8")); //中文名称下载 + byte[] buffer = new byte[1024]; + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream outputStream = null; + try { + fis = new FileInputStream(pdfDir + File.separator + pdfFileName); + bis = new BufferedInputStream(fis); + outputStream = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + outputStream.write(buffer, 0, i); + i = bis.read(buffer); + } + outputStream.flush(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fis != null) { + File file = new File(pdfDir); + if (file != null && file.isFile() && file.exists()) { + file.delete(); + } + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } +} diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index 7465202..b43f761 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -131,6 +131,46 @@ spring-test 5.3.15 + + + cn.afterturn + easypoi-base + 4.3.0 + + + cn.afterturn + easypoi-web + 4.3.0 + + + cn.afterturn + easypoi-annotation + 4.3.0 + + + + org.docx4j + docx4j-export-fo + 6.1.0 + + + + + org.apache.poi + poi + 4.1.2 + + + org.apache.poi + poi-ooxml + 4.1.2 + + + + + + + org.springframework.boot spring-boot-starter-data-redis diff --git a/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java b/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java index 938b88a..502ce1d 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java @@ -105,7 +105,7 @@ } } else if ("3".equals(jsonObject1.getString("type"))) { //按部门查询用户id - List> list = userMapper.selectUsers(null, null, null, targetId); + List> list = userMapper.selectUsers(null, null, null,null, targetId); if (!CollectionUtils.isEmpty(list)) { list.stream().forEach(m -> { String id = String.valueOf(m.get("id")); diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java new file mode 100644 index 0000000..9e7ed3f --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java @@ -0,0 +1,309 @@ +package com.casic.missiles.utils; + +import java.io.*; +import java.util.*; +import java.util.Map.Entry; + +import cn.afterturn.easypoi.entity.ImageEntity; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.ooxml.POIXMLDocument; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.util.Units; +import org.apache.poi.xwpf.usermodel.*; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlToken; +import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; +import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; +import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; + +public class CustomXWPFDocumentUtil extends XWPFDocument { + + public CustomXWPFDocumentUtil(InputStream in) throws IOException { + super(in); + } + + public CustomXWPFDocumentUtil() { + super(); + } + + public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { + super(pkg); + } + + /** + * 根据指定的参数值、模板,生成 word 文档 + * + * @param param 需要替换的变量 + * @param template 模板 + */ + public static XWPFDocument generateWord(Map param, String template) { + XWPFDocument doc = null; + try { + OPCPackage pack = POIXMLDocument.openPackage(template); + doc = new CustomXWPFDocumentUtil(pack); + if (param != null && param.size() > 0) { + + //处理段落 + List paragraphList = doc.getParagraphs(); + processParagraphs(paragraphList, param, doc); + + //处理表格 + Iterator it = doc.getTablesIterator(); + while (it.hasNext()) { + XWPFTable table = it.next(); + List rows = table.getRows(); + for (XWPFTableRow row : rows) { + List cells = row.getTableCells(); + for (XWPFTableCell cell : cells) { + List paragraphListTable = cell.getParagraphs(); + processParagraphs(paragraphListTable, param, doc); + } + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return doc; + } + + /** + * 处理段落 + * + * @param paragraphList + * @param + * @throws FileNotFoundException + * @throws InvalidFormatException + */ + public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { + if (paragraphList != null && paragraphList.size() > 0) { + for (XWPFParagraph paragraph : paragraphList) { + List runs = paragraph.getRuns(); + for (XWPFRun run : runs) { + String text = run.getText(0); + //System.out.println("text=="+text); + if (text != null) { + boolean isSetText = false; + for (Entry entry : param.entrySet()) { + String key = entry.getKey(); + if (text.indexOf(key) != -1) { + isSetText = true; + Object value = entry.getValue(); + if (value instanceof String) {//文本替换 + //System.out.println("key=="+key); + text = text.replace(key, value.toString()); + } else if (value instanceof Map) { //图片替换 + text = text.replace(text, ""); + Map pic = (Map) value; + int width = Integer.parseInt(pic.get("width").toString()); + int height = Integer.parseInt(pic.get("height").toString()); + int picType = getPictureType(pic.get("type").toString()); + String picPath = (String) pic.get("picPath"); + CTInline inline = run.getCTR().addNewDrawing().addNewInline(); + insertPicture(doc, picPath, inline, width, height); + CTDrawing drawing = run.getCTR().getDrawingArray(0); + CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); + //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 + CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", + Units.toEMU(width), Units.toEMU(height),//图片大小 + Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 + drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 + drawing.removeInline(0);//删除行内属性 + } + } + } + if (isSetText) { + run.setText(text, 0); + } + } + } + } + } + } + + /** + * 根据图片类型,取得对应的图片类型代码 + * + * @param picType + * @return int + */ + private static int getPictureType(String picType) { + int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; + if (picType != null) { + if (picType.equalsIgnoreCase("png")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; + } else if (picType.equalsIgnoreCase("dib")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; + } else if (picType.equalsIgnoreCase("emf")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; + } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; + } else if (picType.equalsIgnoreCase("wmf")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; + } + } + return res; + } + + /** + * insert Picture + * + * @param document + * @param filePath + * @param inline + * @param width + * @param height + * @throws InvalidFormatException + * @throws FileNotFoundException + */ + private static void insertPicture(XWPFDocument document, String filePath, + CTInline inline, int width, + int height) throws InvalidFormatException, + FileNotFoundException { + document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); + int id = document.getAllPictures().size() - 1; + final int EMU = 9525; + width *= EMU; + height *= EMU; + String blipId = + document.getAllPictures().get(id).getRelationId(document); + String picXml = getPicXml(blipId, width, height); + XmlToken xmlToken = null; + try { + xmlToken = XmlToken.Factory.parse(picXml); + } catch (XmlException xe) { + xe.printStackTrace(); + } + inline.set(xmlToken); + inline.setDistT(0); + inline.setDistB(0); + inline.setDistL(0); + inline.setDistR(0); + CTPositiveSize2D extent = inline.addNewExtent(); + extent.setCx(width); + extent.setCy(height); + CTNonVisualDrawingProps docPr = inline.addNewDocPr(); + docPr.setId(id); + docPr.setName("IMG_" + id); + docPr.setDescr("IMG_" + id); + } + + /** + * get the xml of the picture + * + * @param blipId + * @param width + * @param height + * @return + */ + private static String getPicXml(String blipId, int width, int height) { + String picXml = + "" + "" + + " " + + " " + + " " + " " + " " + + " " + " " + + " " + + " " + " " + + " " + " " + + " " + " " + + " " + + " " + " " + + " " + + " " + " " + + " " + " " + + " " + ""; + return picXml; + } + + /** + * @param ctGraphicalObject 图片数据 + * @param deskFileName 图片描述 + * @param width 宽 + * @param height 高 + * @param leftOffset 水平偏移:负数向左,正数向右 + * @param topOffset 垂直偏移:负数向上,正数向下 + * @return CTAnchor + * @throws Exception + */ + public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, + String deskFileName, int width, int height, + int leftOffset, int topOffset) { + //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 + if (StringUtils.isBlank(deskFileName)) { + deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 + } + String anchorXML = + "" + + "" + + "" + + "" + leftOffset + "" + + "" + + "" + + "" + topOffset + "" + + "" + + "" + + "" + + "" + + "" + + ""; + CTDrawing drawing = null; + try { + drawing = CTDrawing.Factory.parse(anchorXML); + } catch (XmlException e) { + e.printStackTrace(); + } + CTAnchor anchor = drawing.getAnchorArray(0); + anchor.setGraphic(ctGraphicalObject); + return anchor; + } + public static void main(String[] args) throws IOException{ + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl("C:\\upload\\word\\"); + image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); + param.put("image", image); + dataList.add(param); + } + Calendar now = Calendar.getInstance(); + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)+""); + params.put("m", (now.get(Calendar.MONTH) + 1)+""); + params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); + String template="C:\\upload\\word\\tem.docx"; + ByteArrayOutputStream baos = null; + try { + XWPFDocument document = generateWord(params, template); + baos = new ByteArrayOutputStream(); + document.write(baos);//临时存储流到内存 + baos.flush(); + } catch (Exception e) { + e.printStackTrace(); + }finally{ + if(baos != null){ + baos.close(); + } + } + + + } + +} diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java new file mode 100644 index 0000000..9c67a59 --- /dev/null +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -0,0 +1,116 @@ +package com.casic.missiles.controller.system; + + +import cn.afterturn.easypoi.entity.ImageEntity; +import com.casic.missiles.utils.PdfUtil; +import org.springframework.stereotype.Controller; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.*; + + +@Controller +@RequestMapping("/poi") +public class PoiController { + + private String filepath="C:\\upload"; + + @RequestMapping(value = "/convertWordToPdf") + public void convertWordToPdf(HttpServletResponse response) throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + String pdfDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + pdfDir = filepath + File.separator + "pdf"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = PdfUtil.exportWord(tf.getPath(), wordDir, fileName, params); + String pdfFileName = "convertDocx2Pdf.pdf"; + String downloadFile = "pdf导出.pdf"; + + if (word.equals("")) { + Assert.notNull(word, "word路径不能为空"); + } else { + PdfUtil.convertDocx2Pdf(word, pdfDir + File.separator + pdfFileName); + response.setContentType("application/force-download");// 设置强制下载不打开 + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8")); //中文名称下载 + byte[] buffer = new byte[1024]; + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream outputStream = null; + try { + fis = new FileInputStream(pdfDir + File.separator + pdfFileName); + bis = new BufferedInputStream(fis); + outputStream = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + outputStream.write(buffer, 0, i); + i = bis.read(buffer); + } + outputStream.flush(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fis != null) { + File file = new File(pdfDir); + if (file != null && file.isFile() && file.exists()) { + file.delete(); + } + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } +} diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index 7465202..b43f761 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -131,6 +131,46 @@ spring-test 5.3.15 + + + cn.afterturn + easypoi-base + 4.3.0 + + + cn.afterturn + easypoi-web + 4.3.0 + + + cn.afterturn + easypoi-annotation + 4.3.0 + + + + org.docx4j + docx4j-export-fo + 6.1.0 + + + + + org.apache.poi + poi + 4.1.2 + + + org.apache.poi + poi-ooxml + 4.1.2 + + + + + + + org.springframework.boot spring-boot-starter-data-redis diff --git a/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java b/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java index 938b88a..502ce1d 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java @@ -105,7 +105,7 @@ } } else if ("3".equals(jsonObject1.getString("type"))) { //按部门查询用户id - List> list = userMapper.selectUsers(null, null, null, targetId); + List> list = userMapper.selectUsers(null, null, null,null, targetId); if (!CollectionUtils.isEmpty(list)) { list.stream().forEach(m -> { String id = String.valueOf(m.get("id")); diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java new file mode 100644 index 0000000..9e7ed3f --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java @@ -0,0 +1,309 @@ +package com.casic.missiles.utils; + +import java.io.*; +import java.util.*; +import java.util.Map.Entry; + +import cn.afterturn.easypoi.entity.ImageEntity; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.ooxml.POIXMLDocument; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.util.Units; +import org.apache.poi.xwpf.usermodel.*; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlToken; +import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; +import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; +import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; + +public class CustomXWPFDocumentUtil extends XWPFDocument { + + public CustomXWPFDocumentUtil(InputStream in) throws IOException { + super(in); + } + + public CustomXWPFDocumentUtil() { + super(); + } + + public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { + super(pkg); + } + + /** + * 根据指定的参数值、模板,生成 word 文档 + * + * @param param 需要替换的变量 + * @param template 模板 + */ + public static XWPFDocument generateWord(Map param, String template) { + XWPFDocument doc = null; + try { + OPCPackage pack = POIXMLDocument.openPackage(template); + doc = new CustomXWPFDocumentUtil(pack); + if (param != null && param.size() > 0) { + + //处理段落 + List paragraphList = doc.getParagraphs(); + processParagraphs(paragraphList, param, doc); + + //处理表格 + Iterator it = doc.getTablesIterator(); + while (it.hasNext()) { + XWPFTable table = it.next(); + List rows = table.getRows(); + for (XWPFTableRow row : rows) { + List cells = row.getTableCells(); + for (XWPFTableCell cell : cells) { + List paragraphListTable = cell.getParagraphs(); + processParagraphs(paragraphListTable, param, doc); + } + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return doc; + } + + /** + * 处理段落 + * + * @param paragraphList + * @param + * @throws FileNotFoundException + * @throws InvalidFormatException + */ + public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { + if (paragraphList != null && paragraphList.size() > 0) { + for (XWPFParagraph paragraph : paragraphList) { + List runs = paragraph.getRuns(); + for (XWPFRun run : runs) { + String text = run.getText(0); + //System.out.println("text=="+text); + if (text != null) { + boolean isSetText = false; + for (Entry entry : param.entrySet()) { + String key = entry.getKey(); + if (text.indexOf(key) != -1) { + isSetText = true; + Object value = entry.getValue(); + if (value instanceof String) {//文本替换 + //System.out.println("key=="+key); + text = text.replace(key, value.toString()); + } else if (value instanceof Map) { //图片替换 + text = text.replace(text, ""); + Map pic = (Map) value; + int width = Integer.parseInt(pic.get("width").toString()); + int height = Integer.parseInt(pic.get("height").toString()); + int picType = getPictureType(pic.get("type").toString()); + String picPath = (String) pic.get("picPath"); + CTInline inline = run.getCTR().addNewDrawing().addNewInline(); + insertPicture(doc, picPath, inline, width, height); + CTDrawing drawing = run.getCTR().getDrawingArray(0); + CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); + //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 + CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", + Units.toEMU(width), Units.toEMU(height),//图片大小 + Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 + drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 + drawing.removeInline(0);//删除行内属性 + } + } + } + if (isSetText) { + run.setText(text, 0); + } + } + } + } + } + } + + /** + * 根据图片类型,取得对应的图片类型代码 + * + * @param picType + * @return int + */ + private static int getPictureType(String picType) { + int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; + if (picType != null) { + if (picType.equalsIgnoreCase("png")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; + } else if (picType.equalsIgnoreCase("dib")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; + } else if (picType.equalsIgnoreCase("emf")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; + } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; + } else if (picType.equalsIgnoreCase("wmf")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; + } + } + return res; + } + + /** + * insert Picture + * + * @param document + * @param filePath + * @param inline + * @param width + * @param height + * @throws InvalidFormatException + * @throws FileNotFoundException + */ + private static void insertPicture(XWPFDocument document, String filePath, + CTInline inline, int width, + int height) throws InvalidFormatException, + FileNotFoundException { + document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); + int id = document.getAllPictures().size() - 1; + final int EMU = 9525; + width *= EMU; + height *= EMU; + String blipId = + document.getAllPictures().get(id).getRelationId(document); + String picXml = getPicXml(blipId, width, height); + XmlToken xmlToken = null; + try { + xmlToken = XmlToken.Factory.parse(picXml); + } catch (XmlException xe) { + xe.printStackTrace(); + } + inline.set(xmlToken); + inline.setDistT(0); + inline.setDistB(0); + inline.setDistL(0); + inline.setDistR(0); + CTPositiveSize2D extent = inline.addNewExtent(); + extent.setCx(width); + extent.setCy(height); + CTNonVisualDrawingProps docPr = inline.addNewDocPr(); + docPr.setId(id); + docPr.setName("IMG_" + id); + docPr.setDescr("IMG_" + id); + } + + /** + * get the xml of the picture + * + * @param blipId + * @param width + * @param height + * @return + */ + private static String getPicXml(String blipId, int width, int height) { + String picXml = + "" + "" + + " " + + " " + + " " + " " + " " + + " " + " " + + " " + + " " + " " + + " " + " " + + " " + " " + + " " + + " " + " " + + " " + + " " + " " + + " " + " " + + " " + ""; + return picXml; + } + + /** + * @param ctGraphicalObject 图片数据 + * @param deskFileName 图片描述 + * @param width 宽 + * @param height 高 + * @param leftOffset 水平偏移:负数向左,正数向右 + * @param topOffset 垂直偏移:负数向上,正数向下 + * @return CTAnchor + * @throws Exception + */ + public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, + String deskFileName, int width, int height, + int leftOffset, int topOffset) { + //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 + if (StringUtils.isBlank(deskFileName)) { + deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 + } + String anchorXML = + "" + + "" + + "" + + "" + leftOffset + "" + + "" + + "" + + "" + topOffset + "" + + "" + + "" + + "" + + "" + + "" + + ""; + CTDrawing drawing = null; + try { + drawing = CTDrawing.Factory.parse(anchorXML); + } catch (XmlException e) { + e.printStackTrace(); + } + CTAnchor anchor = drawing.getAnchorArray(0); + anchor.setGraphic(ctGraphicalObject); + return anchor; + } + public static void main(String[] args) throws IOException{ + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl("C:\\upload\\word\\"); + image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); + param.put("image", image); + dataList.add(param); + } + Calendar now = Calendar.getInstance(); + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)+""); + params.put("m", (now.get(Calendar.MONTH) + 1)+""); + params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); + String template="C:\\upload\\word\\tem.docx"; + ByteArrayOutputStream baos = null; + try { + XWPFDocument document = generateWord(params, template); + baos = new ByteArrayOutputStream(); + document.write(baos);//临时存储流到内存 + baos.flush(); + } catch (Exception e) { + e.printStackTrace(); + }finally{ + if(baos != null){ + baos.close(); + } + } + + + } + +} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java new file mode 100644 index 0000000..3d80a8e --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -0,0 +1,175 @@ +package com.casic.missiles.utils; + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.docx4j.Docx4J; +import org.docx4j.convert.out.FOSettings; +import org.docx4j.fonts.IdentityPlusMapper; +import org.docx4j.fonts.Mapper; +import org.docx4j.fonts.PhysicalFonts; +import org.docx4j.openpackaging.packages.WordprocessingMLPackage; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.Map; + +/** + * @Description: 根据word模板导出文件 + * @Author: zt + * @Date: 2023/2/2 9:27 + */ +public class PdfUtil { + + /** + * 生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.exists()) { + dir.mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + //e.printStackTrace(); + } + return tmpPath; + } + + + public static String convertDocx2Pdf(String wordPath,String pdfPath) { + OutputStream os = null; + InputStream is = null; + try { + is = new FileInputStream(new File(wordPath)); + WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(is); + Mapper fontMapper = new IdentityPlusMapper(); + fontMapper.put("隶书", PhysicalFonts.get("LiSu")); + fontMapper.put("宋体", PhysicalFonts.get("SimSun")); + fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei")); + fontMapper.put("黑体", PhysicalFonts.get("SimHei")); + fontMapper.put("楷体", PhysicalFonts.get("KaiTi")); + fontMapper.put("新宋体", PhysicalFonts.get("NSimSun")); + fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai")); + fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong")); + fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB")); + fontMapper.put("仿宋", PhysicalFonts.get("FangSong")); + fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312")); + fontMapper.put("幼圆", PhysicalFonts.get("YouYuan")); + fontMapper.put("华文宋体", PhysicalFonts.get("STSong")); + fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong")); + mlPackage.setFontMapper(fontMapper); + os = new java.io.FileOutputStream(pdfPath); + //docx4j docx转pdf + FOSettings foSettings = Docx4J.createFOSettings(); + foSettings.setWmlPackage(mlPackage); + Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL); + is.close();//关闭输入流 + os.close();//关闭输出流 + return ""; + } catch (Exception e) { + //e.printStackTrace(); + try { + if (is != null) { + is.close(); + } + if (os != null) { + os.close(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } finally { + File file = new File(wordPath); + if (file != null && file.isFile() && file.exists()) { + file.delete(); + } + } + return ""; + } + + public static byte[] getImageBase64(String path) throws IOException { + InputStream input = new FileInputStream(path); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + int numBytesRead = 0; + while ((numBytesRead = input.read(buf)) != -1) { + output.write(buf, 0, numBytesRead); + } + byte[] data = output.toByteArray(); + output.close(); + input.close(); + return data; + } + + public static void downloadFile(HttpServletResponse response, String downloadFilePath, String fileName) throws UnsupportedEncodingException { + File file = new File(downloadFilePath); + if (file.exists()) { + response.setContentType("application/force-download");// 设置强制下载不打开 +// response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); + //中文名称下载 + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); + byte[] buffer = new byte[1024]; + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream outputStream = null; + try { + fis = new FileInputStream(file); + bis = new BufferedInputStream(fis); + outputStream = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + outputStream.write(buffer, 0, i); + i = bis.read(buffer); + } + outputStream.flush(); + } catch (Exception e) { + //e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + //e.printStackTrace(); + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + //e.printStackTrace(); + } + } + if (fis != null) { + try { + fis.close(); + } catch (IOException e) { + //e.printStackTrace(); + } + } + } + } + } + +} diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java new file mode 100644 index 0000000..9c67a59 --- /dev/null +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -0,0 +1,116 @@ +package com.casic.missiles.controller.system; + + +import cn.afterturn.easypoi.entity.ImageEntity; +import com.casic.missiles.utils.PdfUtil; +import org.springframework.stereotype.Controller; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.*; + + +@Controller +@RequestMapping("/poi") +public class PoiController { + + private String filepath="C:\\upload"; + + @RequestMapping(value = "/convertWordToPdf") + public void convertWordToPdf(HttpServletResponse response) throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + String pdfDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + pdfDir = filepath + File.separator + "pdf"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = PdfUtil.exportWord(tf.getPath(), wordDir, fileName, params); + String pdfFileName = "convertDocx2Pdf.pdf"; + String downloadFile = "pdf导出.pdf"; + + if (word.equals("")) { + Assert.notNull(word, "word路径不能为空"); + } else { + PdfUtil.convertDocx2Pdf(word, pdfDir + File.separator + pdfFileName); + response.setContentType("application/force-download");// 设置强制下载不打开 + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8")); //中文名称下载 + byte[] buffer = new byte[1024]; + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream outputStream = null; + try { + fis = new FileInputStream(pdfDir + File.separator + pdfFileName); + bis = new BufferedInputStream(fis); + outputStream = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + outputStream.write(buffer, 0, i); + i = bis.read(buffer); + } + outputStream.flush(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fis != null) { + File file = new File(pdfDir); + if (file != null && file.isFile() && file.exists()) { + file.delete(); + } + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + } +} diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index 7465202..b43f761 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -131,6 +131,46 @@ spring-test 5.3.15 + + + cn.afterturn + easypoi-base + 4.3.0 + + + cn.afterturn + easypoi-web + 4.3.0 + + + cn.afterturn + easypoi-annotation + 4.3.0 + + + + org.docx4j + docx4j-export-fo + 6.1.0 + + + + + org.apache.poi + poi + 4.1.2 + + + org.apache.poi + poi-ooxml + 4.1.2 + + + + + + + org.springframework.boot spring-boot-starter-data-redis diff --git a/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java b/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java index 938b88a..502ce1d 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/listeners/flowable/CounterSignListener.java @@ -105,7 +105,7 @@ } } else if ("3".equals(jsonObject1.getString("type"))) { //按部门查询用户id - List> list = userMapper.selectUsers(null, null, null, targetId); + List> list = userMapper.selectUsers(null, null, null,null, targetId); if (!CollectionUtils.isEmpty(list)) { list.stream().forEach(m -> { String id = String.valueOf(m.get("id")); diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java new file mode 100644 index 0000000..9e7ed3f --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java @@ -0,0 +1,309 @@ +package com.casic.missiles.utils; + +import java.io.*; +import java.util.*; +import java.util.Map.Entry; + +import cn.afterturn.easypoi.entity.ImageEntity; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.ooxml.POIXMLDocument; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.util.Units; +import org.apache.poi.xwpf.usermodel.*; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlToken; +import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; +import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; +import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; + +public class CustomXWPFDocumentUtil extends XWPFDocument { + + public CustomXWPFDocumentUtil(InputStream in) throws IOException { + super(in); + } + + public CustomXWPFDocumentUtil() { + super(); + } + + public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { + super(pkg); + } + + /** + * 根据指定的参数值、模板,生成 word 文档 + * + * @param param 需要替换的变量 + * @param template 模板 + */ + public static XWPFDocument generateWord(Map param, String template) { + XWPFDocument doc = null; + try { + OPCPackage pack = POIXMLDocument.openPackage(template); + doc = new CustomXWPFDocumentUtil(pack); + if (param != null && param.size() > 0) { + + //处理段落 + List paragraphList = doc.getParagraphs(); + processParagraphs(paragraphList, param, doc); + + //处理表格 + Iterator it = doc.getTablesIterator(); + while (it.hasNext()) { + XWPFTable table = it.next(); + List rows = table.getRows(); + for (XWPFTableRow row : rows) { + List cells = row.getTableCells(); + for (XWPFTableCell cell : cells) { + List paragraphListTable = cell.getParagraphs(); + processParagraphs(paragraphListTable, param, doc); + } + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return doc; + } + + /** + * 处理段落 + * + * @param paragraphList + * @param + * @throws FileNotFoundException + * @throws InvalidFormatException + */ + public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { + if (paragraphList != null && paragraphList.size() > 0) { + for (XWPFParagraph paragraph : paragraphList) { + List runs = paragraph.getRuns(); + for (XWPFRun run : runs) { + String text = run.getText(0); + //System.out.println("text=="+text); + if (text != null) { + boolean isSetText = false; + for (Entry entry : param.entrySet()) { + String key = entry.getKey(); + if (text.indexOf(key) != -1) { + isSetText = true; + Object value = entry.getValue(); + if (value instanceof String) {//文本替换 + //System.out.println("key=="+key); + text = text.replace(key, value.toString()); + } else if (value instanceof Map) { //图片替换 + text = text.replace(text, ""); + Map pic = (Map) value; + int width = Integer.parseInt(pic.get("width").toString()); + int height = Integer.parseInt(pic.get("height").toString()); + int picType = getPictureType(pic.get("type").toString()); + String picPath = (String) pic.get("picPath"); + CTInline inline = run.getCTR().addNewDrawing().addNewInline(); + insertPicture(doc, picPath, inline, width, height); + CTDrawing drawing = run.getCTR().getDrawingArray(0); + CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); + //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 + CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", + Units.toEMU(width), Units.toEMU(height),//图片大小 + Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 + drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 + drawing.removeInline(0);//删除行内属性 + } + } + } + if (isSetText) { + run.setText(text, 0); + } + } + } + } + } + } + + /** + * 根据图片类型,取得对应的图片类型代码 + * + * @param picType + * @return int + */ + private static int getPictureType(String picType) { + int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; + if (picType != null) { + if (picType.equalsIgnoreCase("png")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; + } else if (picType.equalsIgnoreCase("dib")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; + } else if (picType.equalsIgnoreCase("emf")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; + } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; + } else if (picType.equalsIgnoreCase("wmf")) { + res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; + } + } + return res; + } + + /** + * insert Picture + * + * @param document + * @param filePath + * @param inline + * @param width + * @param height + * @throws InvalidFormatException + * @throws FileNotFoundException + */ + private static void insertPicture(XWPFDocument document, String filePath, + CTInline inline, int width, + int height) throws InvalidFormatException, + FileNotFoundException { + document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); + int id = document.getAllPictures().size() - 1; + final int EMU = 9525; + width *= EMU; + height *= EMU; + String blipId = + document.getAllPictures().get(id).getRelationId(document); + String picXml = getPicXml(blipId, width, height); + XmlToken xmlToken = null; + try { + xmlToken = XmlToken.Factory.parse(picXml); + } catch (XmlException xe) { + xe.printStackTrace(); + } + inline.set(xmlToken); + inline.setDistT(0); + inline.setDistB(0); + inline.setDistL(0); + inline.setDistR(0); + CTPositiveSize2D extent = inline.addNewExtent(); + extent.setCx(width); + extent.setCy(height); + CTNonVisualDrawingProps docPr = inline.addNewDocPr(); + docPr.setId(id); + docPr.setName("IMG_" + id); + docPr.setDescr("IMG_" + id); + } + + /** + * get the xml of the picture + * + * @param blipId + * @param width + * @param height + * @return + */ + private static String getPicXml(String blipId, int width, int height) { + String picXml = + "" + "" + + " " + + " " + + " " + " " + " " + + " " + " " + + " " + + " " + " " + + " " + " " + + " " + " " + + " " + + " " + " " + + " " + + " " + " " + + " " + " " + + " " + ""; + return picXml; + } + + /** + * @param ctGraphicalObject 图片数据 + * @param deskFileName 图片描述 + * @param width 宽 + * @param height 高 + * @param leftOffset 水平偏移:负数向左,正数向右 + * @param topOffset 垂直偏移:负数向上,正数向下 + * @return CTAnchor + * @throws Exception + */ + public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, + String deskFileName, int width, int height, + int leftOffset, int topOffset) { + //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 + if (StringUtils.isBlank(deskFileName)) { + deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 + } + String anchorXML = + "" + + "" + + "" + + "" + leftOffset + "" + + "" + + "" + + "" + topOffset + "" + + "" + + "" + + "" + + "" + + "" + + ""; + CTDrawing drawing = null; + try { + drawing = CTDrawing.Factory.parse(anchorXML); + } catch (XmlException e) { + e.printStackTrace(); + } + CTAnchor anchor = drawing.getAnchorArray(0); + anchor.setGraphic(ctGraphicalObject); + return anchor; + } + public static void main(String[] args) throws IOException{ + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl("C:\\upload\\word\\"); + image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); + param.put("image", image); + dataList.add(param); + } + Calendar now = Calendar.getInstance(); + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)+""); + params.put("m", (now.get(Calendar.MONTH) + 1)+""); + params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); + String template="C:\\upload\\word\\tem.docx"; + ByteArrayOutputStream baos = null; + try { + XWPFDocument document = generateWord(params, template); + baos = new ByteArrayOutputStream(); + document.write(baos);//临时存储流到内存 + baos.flush(); + } catch (Exception e) { + e.printStackTrace(); + }finally{ + if(baos != null){ + baos.close(); + } + } + + + } + +} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java new file mode 100644 index 0000000..3d80a8e --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -0,0 +1,175 @@ +package com.casic.missiles.utils; + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.docx4j.Docx4J; +import org.docx4j.convert.out.FOSettings; +import org.docx4j.fonts.IdentityPlusMapper; +import org.docx4j.fonts.Mapper; +import org.docx4j.fonts.PhysicalFonts; +import org.docx4j.openpackaging.packages.WordprocessingMLPackage; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.util.Map; + +/** + * @Description: 根据word模板导出文件 + * @Author: zt + * @Date: 2023/2/2 9:27 + */ +public class PdfUtil { + + /** + * 生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.exists()) { + dir.mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + //e.printStackTrace(); + } + return tmpPath; + } + + + public static String convertDocx2Pdf(String wordPath,String pdfPath) { + OutputStream os = null; + InputStream is = null; + try { + is = new FileInputStream(new File(wordPath)); + WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(is); + Mapper fontMapper = new IdentityPlusMapper(); + fontMapper.put("隶书", PhysicalFonts.get("LiSu")); + fontMapper.put("宋体", PhysicalFonts.get("SimSun")); + fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei")); + fontMapper.put("黑体", PhysicalFonts.get("SimHei")); + fontMapper.put("楷体", PhysicalFonts.get("KaiTi")); + fontMapper.put("新宋体", PhysicalFonts.get("NSimSun")); + fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai")); + fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong")); + fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB")); + fontMapper.put("仿宋", PhysicalFonts.get("FangSong")); + fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312")); + fontMapper.put("幼圆", PhysicalFonts.get("YouYuan")); + fontMapper.put("华文宋体", PhysicalFonts.get("STSong")); + fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong")); + mlPackage.setFontMapper(fontMapper); + os = new java.io.FileOutputStream(pdfPath); + //docx4j docx转pdf + FOSettings foSettings = Docx4J.createFOSettings(); + foSettings.setWmlPackage(mlPackage); + Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL); + is.close();//关闭输入流 + os.close();//关闭输出流 + return ""; + } catch (Exception e) { + //e.printStackTrace(); + try { + if (is != null) { + is.close(); + } + if (os != null) { + os.close(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + } finally { + File file = new File(wordPath); + if (file != null && file.isFile() && file.exists()) { + file.delete(); + } + } + return ""; + } + + public static byte[] getImageBase64(String path) throws IOException { + InputStream input = new FileInputStream(path); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + int numBytesRead = 0; + while ((numBytesRead = input.read(buf)) != -1) { + output.write(buf, 0, numBytesRead); + } + byte[] data = output.toByteArray(); + output.close(); + input.close(); + return data; + } + + public static void downloadFile(HttpServletResponse response, String downloadFilePath, String fileName) throws UnsupportedEncodingException { + File file = new File(downloadFilePath); + if (file.exists()) { + response.setContentType("application/force-download");// 设置强制下载不打开 +// response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); + //中文名称下载 + response.setHeader("Content-Disposition", + "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); + byte[] buffer = new byte[1024]; + FileInputStream fis = null; + BufferedInputStream bis = null; + OutputStream outputStream = null; + try { + fis = new FileInputStream(file); + bis = new BufferedInputStream(fis); + outputStream = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + outputStream.write(buffer, 0, i); + i = bis.read(buffer); + } + outputStream.flush(); + } catch (Exception e) { + //e.printStackTrace(); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + //e.printStackTrace(); + } + } + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + //e.printStackTrace(); + } + } + if (fis != null) { + try { + fis.close(); + } catch (IOException e) { + //e.printStackTrace(); + } + } + } + } + } + +} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java new file mode 100644 index 0000000..4baa893 --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java @@ -0,0 +1,184 @@ +//package com.casic.missiles.utils; +// +//import cn.hutool.core.codec.Base64; +//import com.alibaba.fastjson.JSONObject; +//import com.google.common.collect.Lists; +//import org.apache.poi.xwpf.usermodel.*; +//import org.apache.xmlbeans.XmlException; +//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; +//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; +//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; +// +//import java.io.*; +//import java.util.List; +//import java.util.Map; +//import java.util.Set; +// +//public class PictureUtil { +// public void create(String filePath, JSONObject jsonObject) { +// try { +// FileInputStream template = new FileInputStream(new File(filePath)); +// //获取docx解析对象 +// XWPFDocument document = new XWPFDocument(template); +// List tableList = Lists.newArrayList(); +// +// //解析替换表格对象 +// List tables = document.getTables(); +// for (int i = 0; i < tables.size(); i++) { +// //只处理行数大于等于2的表格,且不循环表头 +// XWPFTable table = tables.get(i); +// if (table.getRows().size() > 1) { +// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 +// if (WordUtil.checkText(table.getText())) { +// List rows = table.getRows(); +// //遍历表格,并替换模板 +// eachTable(rows, jsonObject); +// } +// } +// } +// +// // workBook写入输出流 +// ByteArrayOutputStream baos = new ByteArrayOutputStream(); +// document.write(baos); +// baos.flush(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// /** +// * 遍历表格 +// * +// * @param rows 表格行对象 +// * @param textMap 需要替换的信息集合 +// */ +// public static void eachTable(List rows, JSONObject textMap) { +// for (XWPFTableRow row : rows) { +// List cells = row.getTableCells(); +// for (XWPFTableCell cell : cells) { +// //判断单元格是否需要替换 +// if (checkText(cell.getText())) { +// List paragraphs = cell.getParagraphs(); +// for (XWPFParagraph paragraph : paragraphs) { +// List runs = paragraph.getRuns(); +// for (XWPFRun run : runs) { +//// run.setText(changeValue(run.toString(), textMap), 0); +// //新增制证照片单独处理 +// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ +// addPic(run,textMap, 1188000, 1728000,0, 0); +// break; +// } +// String value = changeValue(run.toString(), textMap); +// setWrap(value, run); +// } +// } +// } +// } +// } +// } +// +// /** +// * 匹配传入信息集合与模板 +// * +// * @param value 模板需要替换的区域 +// * @param textMap 传入信息集合 +// * @return 模板需要替换区域信息集合对应值 +// */ +// public static String changeValue(String value, JSONObject textMap) { +// +// boolean flag = false; +// Set> textSets = textMap.entrySet(); +// for (Map.Entry textSet : textSets) { +// //匹配模板与替换值 格式${key} +// String key = "${" + textSet.getKey() + "}"; +// if (value.indexOf(key) != -1) { +// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); +// flag = true; +// break; +// } +// } +// //模板未匹配到区域替换为空 +// if (checkText(value)) { +// value = ""; +// } +// return value; +// } +// public static void setWrap(String value, XWPFRun run) { +// if ( value.indexOf("\n") > 0) { +// //设置换行 +// String[] text = value.split("\n"); +// for (int f = 0; f < text.length; f++) { +// if (f == 0) { +// run.setText(text[f].trim(),0); +// } else { +//// run.addCarriageReturn();//硬回车 +// // 换行 +// run.addBreak(); +// run.setText(text[f]); +// } +// } +// } else { +// run.setText((String) value,0); +// } +// } +// +// /** +// * @param ctGraphicalObject 图片数据 +// * @param deskFileName 图片描述 +// * @param width 宽 +// * @param height 高 +// * @param leftOffset 水平偏移 left +// * @param topOffset 垂直偏移 top +// * @param behind 文字上方,文字下方 +// * @return +// * @throws Exception +// */ +// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { +// String anchorXML ="" +// +"" +// +" " +// +" " +// +" "+ leftOffset + "" +// +" " +// +" " +// +" "+ topOffset +"" +// +" " +// +" " +// +" " +// +" " +// +" " +// +""; +// try { +// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); +// CTAnchor anchor = drawing.getAnchorArray(0); +// anchor.setGraphic(ctGraphicalObject); +// return anchor; +// } catch (XmlException e) { +// e.printStackTrace(); +// return null; +// } +// } +// +// /** +// * 新增制证照片单独处理 +// * @param run +// * @param textMap +// */ +// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ +// String runText = run.toString().trim(); +// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); +// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { +// //1、添加图片 +// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); +// //2、获取图片 +// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); +// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); +// //3、设置属性 +// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); +// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); +// cTDrawing.removeInline(0); +// run.setText(runText.replace("${jpeg}",""), 0); +// }catch (Exception e){ +// e.printStackTrace(); +// } +// } +//}