From bf033b57eaa739061cd3ede60f1fdc3c79b7c787 Mon Sep 17 00:00:00 2001
From: shichongfu <shi_chongfu@163.com>
Date: 星期五, 09 六月 2023 08:56:54 +0800
Subject: [PATCH] 打印转换

---
 src/main/java/com/product/print/service/PrintRealizeService.java |  226 +++++++++++++++++++++++++++++++++++++++++++++++++-------
 1 files changed, 197 insertions(+), 29 deletions(-)

diff --git a/src/main/java/com/product/print/service/PrintRealizeService.java b/src/main/java/com/product/print/service/PrintRealizeService.java
index 483cc58..3744f9f 100644
--- a/src/main/java/com/product/print/service/PrintRealizeService.java
+++ b/src/main/java/com/product/print/service/PrintRealizeService.java
@@ -2,7 +2,10 @@
 
 import com.deepoove.poi.XWPFTemplate;
 import com.deepoove.poi.config.Configure;
+import com.deepoove.poi.data.TextRenderData;
+import com.deepoove.poi.data.style.Style;
 import com.product.common.lang.StringUtils;
+import com.product.core.cache.DataPoolCacheImpl;
 import com.product.core.config.Global;
 import com.product.core.entity.DataTableEntity;
 import com.product.core.entity.FieldSetEntity;
@@ -13,11 +16,16 @@
 import com.product.print.config.CmnCode;
 import com.product.print.config.CmnConst;
 import com.product.print.service.ide.IPrintRealizeService;
+import com.product.util.BaseUtil;
+import com.product.util.SystemParamReplace;
+import com.product.util.config.SystemParamSet;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import javax.servlet.http.HttpServletResponse;
 import java.io.*;
+import java.net.URLEncoder;
 import java.util.*;
 import java.util.stream.Collectors;
 
@@ -34,7 +42,7 @@
 
     @Autowired
     FileManagerService fileManagerService;
-
+/*
     public static void main(String[] args) {
         Map<String, Object> t = new HashMap<>();
         Integer a = 1;
@@ -44,35 +52,195 @@
         Map<String, String> cc = (Map<String, String>) (Map) t;
         System.out.println(cc);
     }
+*/    
+/*
+    public static void main(String[] args) throws Exception {
+        Map<String, Object> map = new HashMap<>();
+        List<Map<String, String>> subMapList = new ArrayList<>();
+        for (int i = 0; i < 5; i++) {
+            Map<String, String> subMap = new HashMap<>();
+            subMap.put("a1", "鍝佸悕鈥斺��" + (i + 1));
+            subMap.put("a2", "鍗曚綅鈥斺��" + (i + 1));
+            subMap.put("a3", "鏁伴噺鈥斺��" + (i + 1));
+            subMap.put("a4", "鐢ㄩ�斺�斺��" + (i + 1));
+            subMapList.add(subMap);
+        }
+        map.put("BGYPLYB_SUB", subMapList);
+        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();//鍒涘缓涓�涓垪琛ㄧ殑瑙勫垯
+        Configure config = Configure.newBuilder().customPolicy("BGYPLYB_SUB", policy).customPolicy("test_table", policy).build();
+        File targetFile = new File("C:\\Users\\cheng\\Desktop\\replaceWord.docx");
+        File file = new File("C:\\Users\\cheng\\Desktop\\鍔炲叕鐢ㄥ搧棰嗙敤琛�.docx");
+        if (targetFile.exists()) {
+            targetFile.delete();
+        }
+        targetFile.createNewFile();
+        try (FileOutputStream is = new FileOutputStream(targetFile);
+        ) {
+            XWPFTemplate render = XWPFTemplate.compile(file, config).render(map);
+            render.write(is);
+            render.close();
+        }
+    }
+*/
+    
+    /**
+     * 	word鎵撳嵃澶嶉�夋澶勭悊
+     * @param fs
+     */
+    public static void dataConvertCheckedData(FieldSetEntity fse) {
+    	
+    	TextRenderData selSymbol = new TextRenderData(CmnConst.PRINT_CHECKED_CHAR, new Style(CmnConst.PRINT_FONT,14));
+		TextRenderData unselSymbol = new TextRenderData(CmnConst.PRINT_UNCHECKED_CHAR, new Style(CmnConst.PRINT_FONT,14));
+    	
+    	//鑾峰彇琛ㄥ崟瀛楁
+    	Object[] fields = fse.getMeta().getFields();
+        if (fields != null) {
+            for(int i = 0; i < fields.length; ++i) {
+            	
+            	//鑾峰彇淇濆瓨鐨勬暟鎹��
+            	String dataSaveValue = fse.getString(fields[i] + CmnConst._SAVE_VALUE);
+            	if (!BaseUtil.strIsNull(dataSaveValue)) {
+            		
+            		//鑾峰彇姣忎釜瀛楁鐨刴eta淇℃伅
+                    FieldSetEntity meta = fse.getMeta().getFieldMeta(fields[i].toString());
+                    if (meta != null && meta.getString(CmnConst.FIELD_REFERECE) != null && meta.getString(CmnConst.FIELD_REFERECE).indexOf("銆�")>-1) {
+                    	
+                    	//鏁版嵁瀵瑰簲鍙傜収淇℃伅
+                    	DataTableEntity dictInfos = getMetaAndCacheDictInfo(meta);
+                    	if (!BaseUtil.dataTableIsEmpty(dictInfos)) {
+                    		for (int j = 0; j < dictInfos.getRows(); j++) {
+                    			
+                    			//鑾峰彇姣忎釜鍙傜収瀵瑰簲鍊�
+                    			String dict_value = dictInfos.getFieldSetEntity(j).getString(CmnConst.DICT_VALUE);
+                    			
+                    			if (dataSaveValue.indexOf(dict_value)>-1) {
+									fse.setValue(fields[i]+"_" + dict_value, selSymbol);
+								}else {
+									fse.setValue(fields[i]+"_" + dict_value, unselSymbol);
+								}
+                    		}
+						}
+                    }
+				}
+            }
+        }
+    }
+    
+    /**
+     * 	鑾峰彇瀛楁瀵瑰簲鏁版嵁瀛楀吀淇℃伅
+     * @param fieldMate
+     * @return
+     */
+    public static DataTableEntity getMetaAndCacheDictInfo(FieldSetEntity fieldMate) {
+    	if (fieldMate != null && fieldMate.getString(CmnConst.FIELD_REFERECE) != null) {
+            int a = fieldMate.getString(CmnConst.FIELD_REFERECE).indexOf("銆�");
+            int b = fieldMate.getString(CmnConst.FIELD_REFERECE).indexOf("銆�");
+            if (b > 1 && a == 0) {
+            	return DataPoolCacheImpl.getInstance().getCacheData("鏁版嵁瀛楀吀閰嶇疆淇℃伅", new String[]{fieldMate.getString(CmnConst.FIELD_REFERECE).substring(a + 1, b)});
+            }
+    	}
+    	return null;
+    }
+    
+    
+    @Override
+    public void printWord(FieldSetEntity fse, HttpServletResponse response) throws BaseException {
+        // 鎵撳嵃閰嶇疆uuid
+        String print_uuid = fse.getString("~" + CmnConst.PRINT_TEMP + "~");
+        //鏌ヨ鎵撳嵃閰嶇疆
+        FieldSetEntity fieldSetEntity = getBaseDao().getFieldSetEntity(CmnConst.TABLE_PRINT_CONFIG, print_uuid, false);
+        if (fieldSetEntity == null || StringUtils.isEmpty(fieldSetEntity.getString(CmnConst.PRINT_TEMPLATE))) {
+            throw new BaseException(CmnCode.PRINT_CONFIG_NOT_EXIST.getValue(), CmnCode.PRINT_CONFIG_NOT_EXIST.getText());
+        }
+        // 鎵撳嵃妯℃澘闄勪欢uuid
+        String template_uuid = fieldSetEntity.getString(CmnConst.PRINT_TEMPLATE);
+        // 鑾峰彇鎵撳嵃妯℃澘
+        File file = getFile(template_uuid);
+        // 鍔犺浇鍙傜収 鎵撳嵃鏃朵娇鐢ㄦ樉绀哄�� 鑰屼笉鏄疄闄呭��
+        getBaseDao().loadPromptData(fse);
+        // 鏂囦欢鍚嶅墠缂�閮ㄥ垎
+        Object tempKey = UUID.randomUUID();
+        // 鏇挎崲鍚庣殑word涓存椂璺緞
+        String localTempPathWord = Global.getSystemConfig("temp.dir", "") + File.separator + "temp_print_" + tempKey + ".docx";
+        File wordTemp = new File(localTempPathWord);
+        try {
+            new File(Global.getSystemConfig("temp.dir", "")).mkdirs();
+            wordTemp.createNewFile();
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new BaseException(CmnCode.PRINT_CONTENT_FAIL.getValue(), CmnCode.PRINT_CONTENT_FAIL.getText() + (e.getMessage() != null ? e.getMessage() : ""));
+        }
+        //灏嗘ā鍜屽綋鍓峟se鐨剉alues鏀惧叆杩涜鏇挎崲
+        try (FileOutputStream is = new FileOutputStream(wordTemp);
+             OutputStream out = response.getOutputStream()) {
+            Map<String, DataTableEntity> subData = fse.getSubData();
 
-//    public static void main(String[] args) throws Exception {
-//        Map<String, Object> map = new HashMap<>();
-//        List<Map<String, String>> subMapList = new ArrayList<>();
-//        for (int i = 0; i < 5; i++) {
-//            Map<String, String> subMap = new HashMap<>();
-//            subMap.put("a1", "鍝佸悕鈥斺��" + (i + 1));
-//            subMap.put("a2", "鍗曚綅鈥斺��" + (i + 1));
-//            subMap.put("a3", "鏁伴噺鈥斺��" + (i + 1));
-//            subMap.put("a4", "鐢ㄩ�斺�斺��" + (i + 1));
-//            subMapList.add(subMap);
-//        }
-//        map.put("BGYPLYB_SUB", subMapList);
-//        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();//鍒涘缓涓�涓垪琛ㄧ殑瑙勫垯
-//        Configure config = Configure.newBuilder().customPolicy("BGYPLYB_SUB", policy).customPolicy("test_table", policy).build();
-//        File targetFile = new File("C:\\Users\\cheng\\Desktop\\replaceWord.docx");
-//        File file = new File("C:\\Users\\cheng\\Desktop\\鍔炲叕鐢ㄥ搧棰嗙敤琛�.docx");
-//        if (targetFile.exists()) {
-//            targetFile.delete();
-//        }
-//        targetFile.createNewFile();
-//        try (FileOutputStream is = new FileOutputStream(targetFile);
-//        ) {
-//            XWPFTemplate render = XWPFTemplate.compile(file, config).render(map);
-//            render.write(is);
-//            render.close();
-//        }
-//    }
+            Configure.ConfigureBuilder configureBuilder = null;
+            if (subData != null && subData.size() > 0) {
+                for (Map.Entry<String, DataTableEntity> vv :
+                        subData.entrySet()) {
+                    getBaseDao().loadPromptData(vv.getValue());
+                    if (!DataTableEntity.isEmpty(vv.getValue())) {
+                        List<Map> collect = vv.getValue().getData().stream().map(item -> (Map<String, String>) ((Map) item.getValues())).collect(Collectors.toList());
+                        fse.setValue(vv.getKey(), collect);
+                    } else {
+                        fse.setValue(vv.getKey(), new ArrayList<>());
+                    }
+                    if (configureBuilder == null) {
+                        configureBuilder = Configure.newBuilder();
+                    }
+                    configureBuilder.customPolicy(vv.getKey(), new HackLoopTableRenderPolicy());
+                }
+            }
+            
+            //澶嶉�夋澶勭悊
+            dataConvertCheckedData(fse);
+            
+            XWPFTemplate render = XWPFTemplate.compile(file, configureBuilder == null ? Configure.createDefault() : configureBuilder.build()).render(fse.getValues());
+            render.write(is);
+            render.close();
+            response.setContentType("multipart/form-data");
+            response.setHeader("Access-Control-Allow-Origin", "*"); // 鍏佽鎵�鏈�
+            //璁剧疆鍝嶅簲
+            response.setContentType("application/octet-stream;charset=UTF-8");
+            // 灏嗗搷搴斿ご涓殑Content-Disposition鏆撮湶鍑烘潵锛屼笉鐒跺墠绔幏鍙栦笉鍒�
+            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
+            
+            String fileName = null;
+            if(!BaseUtil.strIsNull(fieldSetEntity.getString(CmnConst.PRINT_FILE_NAME))) {
+            	fileName = SystemParamReplace.replaceParams(fieldSetEntity.getString(CmnConst.PRINT_FILE_NAME), fse);
+            }else {
+            	fileName = fieldSetEntity.getString(CmnConst.PRINT_NAME);
+			}
+            fileName+=".docx";
+            
+            // 鍦ㄥ搷搴斿ご涓殑Content-Disposition閲岃缃枃浠跺悕绉�
+            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
+            InputStream isPdf = new FileInputStream(wordTemp);
+            int len;
+            byte[] b = new byte[1024];
+            // 杈撳嚭
+            while ((len = isPdf.read(b)) > 0) {
+                out.write(b, 0, len);
+            }
+            isPdf.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new BaseException(CmnCode.PRINT_CONTENT_FAIL.getValue(), CmnCode.PRINT_CONTENT_FAIL.getText() + (e.getMessage() != null ? e.getMessage() : ""));
+        } finally {
+        	//鍒犻櫎word涓存椂鏂囦欢
+            if (wordTemp.exists()) {
+            	System.out.println(wordTemp.getPath());
+//                wordTemp.delete();
+            }
+            if (file != null) {
+                file.delete();
+            }
+        }
 
+    }
+    
+    
     @Override
     public void print(FieldSetEntity fse, HttpServletResponse response) throws BaseException {
         // 鎵撳嵃閰嶇疆uuid
@@ -132,7 +300,7 @@
             response.setContentType("multipart/form-data");
             response.setHeader("Content-Disposition", "attachment;");
             // 浣跨敤openOffice 杞崲涓簆df
-            pdfTemp = PdfConcurrenceUtil.convertToPdf(wordTemp.getPath(), localTempPathPdf);
+            pdfTemp = PdfConcurrenceUtil.convertToPdf(wordTemp.getPath(), localTempPathPdf,"docx");
             InputStream isPdf = new FileInputStream(pdfTemp);
             int len;
             byte[] b = new byte[1024];

--
Gitblit v1.9.2