From 4dd940387c97429a29cb37fc4b177ed9806c7430 Mon Sep 17 00:00:00 2001 From: zhaolei <15900249928@163.com> Date: Mon, 1 Sep 2025 17:33:15 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=A1=E7=90=86=E5=8A=9E=E6=B3=95=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E8=AF=B4=E6=98=8E=E9=97=AE=E9=A2=98=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?|=E5=A2=9E=E5=8A=A0OA=E5=AE=A1=E6=89=B9=E6=B5=81=E7=A8=8B?= =?UTF-8?q?=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pal/pal/output/util/OutputWordUtil.java | 2699 +++++++---------- 1 file changed, 1026 insertions(+), 1673 deletions(-) mode change 100755 => 100644 com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java diff --git a/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java old mode 100755 new mode 100644 index 0a1e87a4..ba1012c3 --- a/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java +++ b/com.actionsoft.apps.coe.pal/src/com/actionsoft/apps/coe/pal/pal/output/util/OutputWordUtil.java @@ -1,6 +1,5 @@ package com.actionsoft.apps.coe.pal.pal.output.util; -import com.actionsoft.apps.coe.pal.constant.CoEConstant; import com.actionsoft.apps.coe.pal.constant.YiliWpsConst; import com.actionsoft.apps.coe.pal.pal.method.cache.PALMethodCache; import com.actionsoft.apps.coe.pal.pal.method.model.PALMethodAttributeModel; @@ -15,148 +14,205 @@ import com.actionsoft.apps.coe.pal.pal.repository.designer.relation.model.Design import com.actionsoft.apps.coe.pal.pal.repository.designer.util.CoeDesignerUtil; import com.actionsoft.apps.coe.pal.pal.repository.model.PALRepositoryModel; import com.actionsoft.apps.coe.pal.pal.repository.model.PALRepositoryPropertyModel; -import com.actionsoft.apps.coe.pal.pal.repository.upfile.constant.CoeFileConstant; import com.actionsoft.apps.coe.pal.pal.repository.upfile.dao.UpFileDao; import com.actionsoft.apps.coe.pal.pal.repository.upfile.model.UpfileModel; import com.actionsoft.apps.coe.pal.pal.ws.web.VersionUtil; import com.actionsoft.apps.coe.pal.util.HttpPostUtil; import com.actionsoft.apps.coe.pal.util.WPS4Util; import com.actionsoft.apps.resource.plugin.profile.DCPluginProfile; -import com.actionsoft.bpms.bo.engine.BO; -import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile; +import com.actionsoft.bpms.commons.database.RowMap; import com.actionsoft.bpms.commons.mvc.view.ResponseObject; import com.actionsoft.bpms.org.model.DepartmentModel; import com.actionsoft.bpms.org.model.RoleModel; import com.actionsoft.bpms.org.model.UserModel; -import com.actionsoft.bpms.server.AWSServer; import com.actionsoft.bpms.server.DispatcherRequest; import com.actionsoft.bpms.server.UserContext; -import com.actionsoft.bpms.server.conf.portal.AWSPortalConf; import com.actionsoft.bpms.server.fs.DCContext; import com.actionsoft.bpms.server.fs.dc.DCProfileManager; -import com.actionsoft.bpms.util.*; +import com.actionsoft.bpms.util.DBSql; +import com.actionsoft.bpms.util.UUIDGener; +import com.actionsoft.bpms.util.UtilDate; +import com.actionsoft.bpms.util.UtilFile; +import com.actionsoft.bpms.util.UtilNumber; +import com.actionsoft.bpms.util.UtilString; import com.actionsoft.sdk.local.SDK; import com.actionsoft.sdk.local.api.AppAPI; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -//import com.aspose.words.TableAlignment; +import com.google.gson.JsonObject; import com.sini.com.spire.doc.*; -import com.sini.com.spire.doc.collections.ParagraphCollection; import com.sini.com.spire.doc.collections.SectionCollection; import com.sini.com.spire.doc.documents.*; import com.sini.com.spire.doc.fields.DocPicture; +import com.sini.com.spire.doc.fields.ParagraphBase; import com.sini.com.spire.doc.fields.TextRange; import com.sini.com.spire.doc.formatting.CharacterFormat; import com.sini.com.spire.doc.formatting.ParagraphFormat; -import com.sini.com.spire.doc.formatting.RowFormat; +import com.sini.com.spire.doc.interfaces.IDocument; +import com.sini.com.spire.doc.interfaces.IDocumentObject; import com.sini.com.spire.doc.interfaces.IParagraph; import com.sini.com.spire.doc.interfaces.ITextRange; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; -import org.apache.commons.lang.StringUtils; - -import java.awt.*; -import java.io.*; +import java.awt.Color; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; -import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; import java.util.List; -import java.util.*; +import java.util.Map; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.sini.com.spire.doc.documents.HorizontalAlignment.*; - public class OutputWordUtil { + public static final String DEPARTMENT = "department"; - public static final String DEPARTMENT = "department"; // 部门 - public static final String POSITION = "position"; // 岗位 - public static final String COMPANY = "company"; // 公司 - public static final String GENERATEDATE = "generate_date"; // 文档创建日期 - public static final String ORGDUTIE = "org_dutie"; // 岗位职责 + public static final String POSITION = "position"; - public static final String TABLE_REPOSITORY = "repository_table"; // 流程table - public static final String TABLE_REPOSITORY_SHAPE = "repository_shape_table"; // 流程步骤table - public static final String TABLE_INSTITUTION = "institution_table"; // 制度table - public static final String TABLE_FORM = "form_table"; // 表单table - public static final String TABLE_IT_SYSTEM = "itsystem_table"; // 信息系统table - public static final String TABLE_KPI = "KPI_table"; // 绩效table - public static final String TABLE_DANGER = "danger_table"; // 风控要求table - public static final String TABLE_REGULATE = "regulate_table"; // 风控(控制)要求table + public static final String COMPANY = "company"; + + public static final String GENERATEDATE = "generate_date"; + + public static final String ORGDUTIE = "org_dutie"; + + public static final String TABLE_REPOSITORY = "repository_table"; + + public static final String TABLE_REPOSITORY_SHAPE = "repository_shape_table"; + + public static final String TABLE_INSTITUTION = "institution_table"; + + public static final String TABLE_FORM = "form_table"; + + public static final String TABLE_IT_SYSTEM = "itsystem_table"; + + public static final String TABLE_KPI = "KPI_table"; + + public static final String TABLE_DANGER = "danger_table"; + + public static final String TABLE_REGULATE = "regulate_table"; + + public static final String REPOSITORY_NAME = "repository_name"; + + public static final String PL_NUMBER = "pl_number"; + + public static final String PL_RESPONSIBLE_PERSON = "pl_responsible_person"; + + public static final String PL_RESPONSIBLE_DEPARTMENT = "pl_responsible_department"; + + public static final String PL_EXECUTIVE_ARM = "pl_executive_arm"; + + public static final String PL_INPUT = "pl_input"; + + public static final String PL_OUTPUT = "pl_output"; + + public static final String PL_DESC = "pl_desc"; + + public static final String PL_CREATE_USER = "pl_create_user"; + + public static final String PL_VERSION = "pl_version"; + + public static final String PL_RESPONSIBILITY = "pl_responsibility"; + + public static final String PL_BUSINESS = "pl_business"; + + public static final String PL_LEAD_PROCESS = "pl_lead_process"; + + public static final String PL_REAR_PROCESS = "pl_rear_process"; + + public static final String PL_ITSYSTEM = "pl_itsystem"; + + public static final String PL_DIAGRAM = "pl_diagram"; + + public static final String PL_DIAGRAM_WIDTH = "pl_diagram_width"; + + public static final String PL_DIAGRAM_HEIGHT = "pl_diagram_height"; - public static final String REPOSITORY_NAME = "repository_name"; // 流程名 - public static final String PL_NUMBER = "pl_number"; // 流程编号 - public static final String PL_RESPONSIBLE_PERSON = "pl_responsible_person"; // 责任人 - public static final String PL_RESPONSIBLE_DEPARTMENT = "pl_responsible_department"; // 责任部门 - public static final String PL_EXECUTIVE_ARM = "pl_executive_arm"; // 流程执行部门 - public static final String PL_INPUT = "pl_input"; // 流程输入 - public static final String PL_OUTPUT = "pl_output"; // 流程输出 - public static final String PL_DESC = "pl_desc"; // 流程说明 - public static final String PL_CREATE_USER = "pl_create_user"; // 编制人 - public static final String PL_VERSION = "pl_version"; // 版本号 - public static final String PL_RESPONSIBILITY = "pl_responsibility"; // 主要人员职责描述 - public static final String PL_BUSINESS = "pl_business"; // 关键业务逻辑规则 - public static final String PL_LEAD_PROCESS = "pl_lead_process"; // 前置流程 - public static final String PL_REAR_PROCESS = "pl_rear_process"; // 后置流程 - public static final String PL_ITSYSTEM = "pl_itsystem"; // 相关IT系统 - public static final String PL_DIAGRAM = "pl_diagram"; // 流程图 - public static final String PL_DIAGRAM_WIDTH = "pl_diagram_width"; // 流程图宽度 - public static final String PL_DIAGRAM_HEIGHT = "pl_diagram_height"; // 流程图高度 public static final int PL_DIAGRAM_MAX_WIDTH = 480; + public static final int PL_DIAGRAM_MAX_HEIGHT = 676; - public static final String SERIAL_NUMBER = "serial_number"; // 序号 - public static final String SHAPE_ID = "shape_id"; // 流程图形元素id - public static final String SHAPE_NAME = "shape_name"; // 流程图形元素名称 - public static final String SHAPE_NUMBER = "shape_number"; // 步骤编号 - public static final String SHAPE_DESC = "shape_desc"; // 工作详细描述 - public static final String SHAPE_INSTITUTION = "shape_institution"; // 制度要求 - public static final String SHAPE_DANGER = "shape_danger"; // 风险点 - public static final String SHAPE_KPI = "shape_kpi"; // 指标 - public static final String SHAPE_FORM = "shape_form"; // 作业单据 - public static final String SHAPE_HANDLE_TIME = "shape_handle_time"; // 处理时间 - public static final String SHAPE_ITSYSTEM = "shape_itsystem"; // 信息系统 - public static final String SHAPE_VERSION = "shape_version"; // 版本号 - public static final String SHAPE_APPLICATION_SCOPE = "shape_application_scope"; // 适用范围 - public static final String SHAPE_TARGET_VALUE = "shape_target_value"; // 指标值 - public static final String SHAPE_DUTY_R = "shape_duty_r"; // 责任者 + public static final String SERIAL_NUMBER = "serial_number"; - public static final String SHAPE_BUSINESS = "shape_business";// 业务规则 - public static final String SHAPE_INPUT = "shape_input";// 输入 - public static final String SHAPE_OUT = "shape_out";// 输出 + public static final String SHAPE_ID = "shape_id"; - public static final String SHAPE_EFFECT = "shape_effect"; // 风险影响 - public static final String SHAPE_PROBABILITY = "shape_probability"; // 风险概率 - public static final String SHAPE_TARGET = "shape_target"; // 控制目标 - public static final String SHAPE_FREQUENCY = "shape_frequency"; // 控制频率 - public static final String SHAPE_MEASURE = "shape_measure"; // 控制措施 - public static final String SHAPE_CALCULATION_METHOD = "shape_calculation_method"; // 计算公式 - public static final String SHAPE_CALCULATION_PROPORTION = "shape_calculation_proportion"; // 计算比例 - public static final String SHAPE_CALCULATION_FREQUENCY = "shape_calculation_frequency"; // 计算频率 - public static final String SHAPE_RELATION_NAME = "shape_relation_name"; // 关联性质名 + public static final String SHAPE_NAME = "shape_name"; + + public static final String SHAPE_NUMBER = "shape_number"; + + public static final String SHAPE_DESC = "shape_desc"; + + public static final String SHAPE_INSTITUTION = "shape_institution"; + + public static final String SHAPE_DANGER = "shape_danger"; + + public static final String SHAPE_KPI = "shape_kpi"; + + public static final String SHAPE_FORM = "shape_form"; + + public static final String SHAPE_HANDLE_TIME = "shape_handle_time"; + + public static final String SHAPE_ITSYSTEM = "shape_itsystem"; + + public static final String SHAPE_VERSION = "shape_version"; + + public static final String SHAPE_APPLICATION_SCOPE = "shape_application_scope"; + + public static final String SHAPE_TARGET_VALUE = "shape_target_value"; + + public static final String SHAPE_DUTY_R = "shape_duty_r"; + + public static final String SHAPE_BUSINESS = "shape_business"; + + public static final String SHAPE_INPUT = "shape_input"; + + public static final String SHAPE_OUT = "shape_out"; + + public static final String SHAPE_EFFECT = "shape_effect"; + + public static final String SHAPE_PROBABILITY = "shape_probability"; + + public static final String SHAPE_TARGET = "shape_target"; + + public static final String SHAPE_FREQUENCY = "shape_frequency"; + + public static final String SHAPE_MEASURE = "shape_measure"; + + public static final String SHAPE_CALCULATION_METHOD = "shape_calculation_method"; + + public static final String SHAPE_CALCULATION_PROPORTION = "shape_calculation_proportion"; + + public static final String SHAPE_CALCULATION_FREQUENCY = "shape_calculation_frequency"; + + public static final String SHAPE_RELATION_NAME = "shape_relation_name"; - //word换行符 public static final String WRAPSTRING = ""; - /** - * 生成word文件 - * - * @param dataMap - * @param tempPath - * @param tempName - * @param docName - */ public static void createDoc(JSONObject dataMap, String tempPath, String tempName, String docName) { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); - - // 设置模本装置方法和路径 try { UtilFile temps = new UtilFile(tempPath); - configuration.setDirectoryForTemplateLoading(temps); + configuration.setDirectoryForTemplateLoading((File)temps); } catch (IOException e2) { e2.printStackTrace(); } @@ -166,7 +222,6 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } - // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -174,7 +229,6 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } - try { t.process(dataMap, out); out.flush(); @@ -186,22 +240,12 @@ public class OutputWordUtil { } } - /** - * 生成word文件 - * - * @param dataMap - * @param tempPath - * @param tempName - * @param docName - */ - public static void createDoc2(JSONObject dataMap, String tempPath, String tempName, String docName,String repositoryId) throws FileNotFoundException { + public static void createDoc2(JSONObject dataMap, String tempPath, String tempName, String docName, String repositoryId) throws FileNotFoundException { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); - - // 设置模本装置方法和路径 try { UtilFile temps = new UtilFile(tempPath); - configuration.setDirectoryForTemplateLoading(temps); + configuration.setDirectoryForTemplateLoading((File)temps); } catch (IOException e2) { e2.printStackTrace(); } @@ -211,9 +255,6 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } - - - // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -221,7 +262,6 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } - try { if (t != null && out != null) { t.process(dataMap, out); @@ -233,10 +273,6 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } - - //流程图新增逻辑,增加管理要求wps文件合并需求 - mergeMRWord(outFile.getPath(),repositoryId); - Document doc = new Document(outFile.getPath()); Section section = doc.getLastSection(); UpFileDao upFileDao = new UpFileDao(); @@ -244,103 +280,104 @@ public class OutputWordUtil { PALRepositoryModel repositoryModel = PALRepositoryQueryAPIManager.getInstance().queryPalRepositoryModelByPalId(repositoryId); DCContext dcContextModel = null; List search = upFileDao.searchByRepositoryId(repositoryModel.getId(), "f"); - //读取模型附件插入手册中文档对象 if (search != null && search.size() > 0) { - //插入前,附件名先排序先排序 sortFilesByNumber(search); - //附件如果为空,不插入附件标题 CharacterFormat format4 = new CharacterFormat(); - //创建字体格式 format4.setFontName("宋体"); - //添加段落 Paragraph paragraph4 = section.addParagraph(); - ParagraphFormat paragraphFormat4 = paragraph4.getFormat(); - paragraphFormat4.setHorizontalAlignment(Left); - + paragraphFormat4.setHorizontalAlignment(HorizontalAlignment.Left); TextRange tr4 = paragraph4.appendText("附件"); - - tr4.getCharacterFormat().setBold(true); tr4.getCharacterFormat().setFontName("宋体"); - tr4.getCharacterFormat().setFontSize(12); - paragraph4.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 - + tr4.getCharacterFormat().setFontSize(12.0F); + paragraph4.applyStyle(BuiltinStyle.Body_Text); long b1 = System.currentTimeMillis(); for (UpfileModel upfileModel : search) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); + DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); if (dcProfile != null) { - - // 处理DocCenter - dcContextModel = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, "file", upfileModel.getPl_uuid(), upfileModel.getFileName()); - //添加段落 + dcContextModel = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", "file", upfileModel.getPl_uuid(), upfileModel.getFileName()); Paragraph paragraph5 = section.addParagraph(); - //加载一个图片,它将作为外部文件的符号显示在Word文档中 - //获取最后一个.的位置 int lastIndexOf = dcContextModel.getFileName().lastIndexOf("."); - //获取文件的后缀名 .jpg String suffix = dcContextModel.getFileName().substring(lastIndexOf); - - DocPicture pdfIcon = new DocPicture(doc); - + DocPicture pdfIcon = new DocPicture((IDocument)doc); InputStream stream1 = new FileInputStream(dcContextModel.getFilePath()); - DocPicture pic1 = new DocPicture(doc); - + DocPicture pic1 = new DocPicture((IDocument)doc); if (suffix.equals(".doc") || suffix.equals(".docx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/word.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".doc")) { paragraph5.appendOleObject(stream1, pic1, "doc"); - } else if (suffix.equals(".docx")) { - paragraph5.appendOleObject(stream1, pic1, "docx"); + continue; } - } else if (suffix.equals(".pdf")) { + if (suffix.equals(".docx")) + paragraph5.appendOleObject(stream1, pic1, "docx"); + continue; + } + if (suffix.equals(".pdf")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/pdf.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); paragraph5.appendOleObject(stream1, pic1, "pdf"); - } else if (suffix.equals(".xls") || suffix.equals(".xlsx")) { + continue; + } + if (suffix.equals(".xls") || suffix.equals(".xlsx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/xls.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".xls")) { paragraph5.appendOleObject(stream1, pic1, "xls"); - } else if (suffix.equals(".xlsx")) { - paragraph5.appendOleObject(stream1, pic1, "xlsx"); + continue; } - } else if (suffix.equals(".png") || suffix.equals(".jgp")) { + if (suffix.equals(".xlsx")) + paragraph5.appendOleObject(stream1, pic1, "xlsx"); + continue; + } + if (suffix.equals(".png") || suffix.equals(".jgp")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/png.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".png")) { paragraph5.appendOleObject(stream1, pic1, "png"); - } else if (suffix.equals(".jpg")) { - paragraph5.appendOleObject(stream1, pic1, "jpg"); + continue; } - } else if (suffix.equals(".zip") || suffix.equals(".rar")) { + if (suffix.equals(".jpg")) + paragraph5.appendOleObject(stream1, pic1, "jpg"); + continue; + } + if (suffix.equals(".zip") || suffix.equals(".rar")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/zip.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".zip")) { paragraph5.appendOleObject(stream1, pic1, "zip"); - } else if (suffix.equals(".rar")) { - paragraph5.appendOleObject(stream1, pic1, "rar"); + continue; } - } else if (suffix.equals(".mp3") || suffix.equals(".mp4")) { + if (suffix.equals(".rar")) + paragraph5.appendOleObject(stream1, pic1, "rar"); + continue; + } + if (suffix.equals(".mp3") || suffix.equals(".mp4")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/mp3.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".mp3")) { paragraph5.appendOleObject(stream1, pic1, "mp3"); - } else if (suffix.equals(".mp4")) { - paragraph5.appendOleObject(stream1, pic1, "mp4"); + continue; } - } else if (suffix.equals(".ppt") || suffix.equals(".pptx")) { + if (suffix.equals(".mp4")) + paragraph5.appendOleObject(stream1, pic1, "mp4"); + continue; + } + if (suffix.equals(".ppt") || suffix.equals(".pptx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/ppt.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".ppt")) { paragraph5.appendOleObject(stream1, pic1, "ppt"); - } else if (suffix.equals(".pptx")) { - paragraph5.appendOleObject(stream1, pic1, "pptx"); + continue; } - } else if (suffix.equals(".txt")) { + if (suffix.equals(".pptx")) + paragraph5.appendOleObject(stream1, pic1, "pptx"); + continue; + } + if (suffix.equals(".txt")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/txt.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); paragraph5.appendOleObject(stream1, pic1, "txt"); } } @@ -350,32 +387,17 @@ public class OutputWordUtil { } catch (Exception e) { e.printStackTrace(); } finally { - // 关闭文档对象 doc.close(); } } - - } - - /** - * 生成word文件 - * - * @param dataMap - * @param tempPath - * @param tempName - * @param docName - */ public static void createZdDoc2(JSONObject dataMap, String tempPath, String tempName, String docName, JSONObject wizardJsonData, String repositoryId, String docPath) throws FileNotFoundException { - Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); - - // 设置模本装置方法和路径 try { UtilFile temps = new UtilFile(tempPath); - configuration.setDirectoryForTemplateLoading(temps); + configuration.setDirectoryForTemplateLoading((File)temps); } catch (IOException e2) { e2.printStackTrace(); } @@ -385,102 +407,69 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } - -//***********************************************************使用spire 生成模板后复制文件****************************************************/ - List> repositoryFileElements = CoeDesignerUtil.getShapeMessageJson4(repositoryId); //流程文件内容 - if (wizardJsonData.getBoolean("orderNuberFirst")) { // 根据页面选择进行排序 - OutputWordUtil.orderByNumber(repositoryFileElements); - } - + List> repositoryFileElements = CoeDesignerUtil.getShapeMessageJson4(repositoryId); + if (wizardJsonData.getBoolean("orderNuberFirst").booleanValue()) + orderByNumber(repositoryFileElements); String controlShapeId = ""; if (repositoryFileElements != null) { - int index = 1;// 流程步骤序号 - int dangerIndex = 1;// 风险序号 - int regulateIndex = 1;// 控制序号 + int index = 1; + int dangerIndex = 1; + int regulateIndex = 1; for (Map shape : repositoryFileElements) { String type = shape.get("type").toString(); if ("regulation".equals(type)) { controlShapeId = shape.get("id").toString(); - } else if ("I/O_L4".equals(type)) { - controlShapeId = shape.get("id").toString(); - } else if("card".equals(type)){ - controlShapeId = shape.get("id").toString(); + continue; } + if ("I/O_L4".equals(type)) { + controlShapeId = shape.get("id").toString(); + continue; + } + if ("card".equals(type)) + controlShapeId = shape.get("id").toString(); } } - - UserContext userContext = DispatcherRequest.getUserContext(); - Map result = new HashMap<>(); result.put("listDef", ""); result.put("content", ""); - PALRepositoryModel repositoryModel = PALRepositoryQueryAPIManager.getInstance().queryPalRepositoryModelByPalId(repositoryId); - String content = ""; StringBuilder listStr = new StringBuilder(); - // 读取附件 - // 流程附件列表 UpFileDao upFileDao = new UpFileDao(); List search = upFileDao.search(repositoryModel.getId(), controlShapeId, null); - DCContext dcContextpdf = null; File file = null; - boolean isPPT = false; - //如果为PPT,则生成PPT手册 if (search != null && search.size() > 0) { - //插入前,附件名先排序先排序 sortFilesByNumber(search); long b1 = System.currentTimeMillis(); - // 复制附件 for (UpfileModel upfileModel : search) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); - + DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); if (dcProfile != null) { - dcContextpdf = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); + dcContextpdf = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); String path = dcContextpdf.getPath(); String fileName = dcContextpdf.getFileName(); - String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); if (suffix.equals("pptx")) { isPPT = true; String pptUrl = docName.substring(0, docName.lastIndexOf("/") + 1); - // 调用App String sourceAppId = "com.actionsoft.apps.coe.pal"; - // aslp服务地址 String aslp = "aslp://com.awspaas.user.apps.new_performance_indicator_library/UpdatePptxAndExcelAslp"; - // 参数定义列表 Map params = new HashMap(); - //文件id,必填 params.put("pl_uuid", repositoryId); - //文件内容id,必填 params.put("shape_uuid", search.get(0).getShape_uuid()); - - //文件保存地址,必填 params.put("fil_path", pptUrl + search.get(0).getFileName()); - - //文件路径(不包含文件名称),必填 params.put("file_url", pptUrl); - - //文件名称,必填 params.put("file_data", search.get(0).getFileName()); - //sid,必填 params.put("sid", userContext.getSessionId()); AppAPI appAPI = SDK.getAppAPI(); - //根据上传的文件进行更新相关的excel或者ppt - ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params); - + ResponseObject responseObject = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params); } - - } } } - - if (isPPT == false) { - // 输出文档路径及名称 + if (!isPPT) { File outFile = new File(docName); Writer out = null; try { @@ -488,8 +477,6 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } - - try { if (t != null && out != null) { t.process(dataMap, out); @@ -501,89 +488,59 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } - - if (search != null && search.size() > 0) { - //插入前,附件名先排序先排序 sortFilesByNumber(search); long b1 = System.currentTimeMillis(); - // 复制附件 for (UpfileModel upfileModel : search) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); - + DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); if (dcProfile != null) { - dcContextpdf = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); + dcContextpdf = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); String path = dcContextpdf.getPath(); String fileName = dcContextpdf.getFileName(); - - - //创建 Document 类的对象并从磁盘加载 Word 文档 Document document = new Document(outFile.getPath()); - // 获取第一个节的第一个表格 Section firstsection = document.getSections().get(1); Table table1 = firstsection.getTables().get(0); - - - table1.setPreferredWidth(new PreferredWidth(WidthType.Twip, (short) 8335f)); - - //遍历表格单元格 - for (int i = 0;i< table1.getRows().getCount();i++) { + table1.setPreferredWidth(new PreferredWidth(WidthType.Twip, (short)8335)); + for (int i = 0; i < table1.getRows().getCount(); i++) { TableRow rows = table1.getRows().get(i); - - - for (int j = 0; j< rows.getCells().getCount(); j++){ - for (int z= 0; z < rows.getCells().get(j).getParagraphs().getCount();z++){ - Paragraph p = rows.getCells().get(j).getParagraphs().get(z); - p.getFormat().setLineSpacing(12f);//设置边距为1.0 - for (int k = 0; k < p.getItems().getCount(); k++) { - DocumentObject item = p.getItems().get(k); - if (item instanceof TextRange) { - TextRange textRange = (TextRange) item; + for (int k = 0; k < rows.getCells().getCount(); k++) { + for (int z = 0; z < rows.getCells().get(k).getParagraphs().getCount(); z++) { + Paragraph p = rows.getCells().get(k).getParagraphs().get(z); + p.getFormat().setLineSpacing(12.0F); + for (int m = 0; m < p.getItems().getCount(); m++) { + ParagraphBase paragraphBase = p.getItems().get(m); + if (paragraphBase instanceof TextRange) { + TextRange textRange = (TextRange)paragraphBase; textRange.getCharacterFormat().setFontName("宋体"); - textRange.getCharacterFormat().setFontSize(10.5f); + textRange.getCharacterFormat().setFontSize(10.5F); } } - } } - } - - JSONArray versionHistoryTable = getVersionHistoryTable(repositoryModel); - int index = 0; + int j = 0; if (versionHistoryTable.getJSONObject(0).size() > 0) { - - //获取最后一节 - Section section = document.getLastSection(); - - + Section section1 = document.getLastSection(); CharacterFormat format2 = new CharacterFormat(); - //创建字体格式 format2.setFontName("宋体"); - //添加段落,设置一级序列 - Paragraph paragraph2 = section.addParagraph(); + Paragraph paragraph2 = section1.addParagraph(); ParagraphFormat paragraphFormat2 = paragraph2.getFormat(); - paragraphFormat2.setHorizontalAlignment(Left); + paragraphFormat2.setHorizontalAlignment(HorizontalAlignment.Left); TextRange tr2 = paragraph2.appendText("修订记录"); tr2.getCharacterFormat().setBold(true); tr2.getCharacterFormat().setFontName("宋体"); - tr2.getCharacterFormat().setFontSize(12f); - paragraph2.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 - - - - //定义表格数据 - String[] header = {"版本", "发布部门","拟制人","拟制日期","审核人","复核人","审批人","修订内容及理由"}; + tr2.getCharacterFormat().setFontSize(12.0F); + paragraph2.applyStyle(BuiltinStyle.Body_Text); + String[] header = { "版本", "发布部门", "拟制人", "拟制日期", "审核人", "复核人", "审批人", "修订内容及理由" }; String[][] strArray2 = new String[versionHistoryTable.size()][]; - List list = new LinkedList<>(); - for (int i = 0; i < versionHistoryTable.size(); i++) { - JSONObject jsonObject = versionHistoryTable.getJSONObject(i); + List list = (List)new LinkedList<>(); + for (int k = 0; k < versionHistoryTable.size(); k++) { + JSONObject jsonObject = versionHistoryTable.getJSONObject(k); String[] strArray = new String[8]; - - if(repositoryModel.getMethodId().equals("process.scheme")){ + if (repositoryModel.getMethodId().equals("process.scheme")) { strArray[0] = jsonObject.getString("P_versions").toString(); - }else{ + } else { strArray[0] = jsonObject.getString("versions").toString(); } strArray[1] = jsonObject.getString("Issuing_department").toString(); @@ -594,426 +551,314 @@ public class OutputWordUtil { strArray[6] = jsonObject.getString("approver").toString(); strArray[7] = jsonObject.getString("Contents_and_reasons_for_revision").toString(); list.add(strArray); - strArray2[i] = strArray; + strArray2[k] = strArray; } - String[][] data = strArray2; - - //添加表格 - Table table = section.addTable(true); - + Table table = section1.addTable(true); table.getTableFormat().setHorizontalAlignment(RowAlignment.Center); - table.resetCells(data.length + 1, header.length); table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); TableRow row = table.getRows().get(0); row.isHeader(true); row.setHeightType(TableRowHeightType.Exactly); - row.setHeight(20); - table.setPreferredWidth(new PreferredWidth(WidthType.Twip, (short) 8335f)); - - float[] columnWidths = {10f,17f,13f,17f,13f,13f,13f,25f}; - - // 设置列宽 - for (int i = 0; i < columnWidths.length; i++) { - row.getCells().get(i).setWidth(columnWidths[i]); - } - - - for (int i = 0; i < header.length; i++) { - row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - Paragraph p = row.getCells().get(i).addParagraph(); - - TextRange txtRange = p.appendText(header[i]); - + row.setHeight(20.0F); + table.setPreferredWidth(new PreferredWidth(WidthType.Twip, (short)8335)); + float[] columnWidths = { 10.0F, 17.0F, 13.0F, 17.0F, 13.0F, 13.0F, 13.0F, 25.0F }; + int n; + for (n = 0; n < columnWidths.length; n++) + row.getCells().get(n).setWidth(columnWidths[n]); + for (n = 0; n < header.length; n++) { + row.getCells().get(n).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + Paragraph p = row.getCells().get(n).addParagraph(); + TextRange txtRange = p.appendText(header[n]); txtRange.getCharacterFormat().setBold(true); txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5f); - + txtRange.getCharacterFormat().setFontSize(10.5F); p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); - } - - - //将数据添加到其余行 for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); - - dataRow.setHeight(20); + dataRow.setHeight(20.0F); dataRow.setHeightType(TableRowHeightType.Auto); dataRow.getRowFormat().setBackColor(Color.white); - - for (int c = 0; c < data[r].length; c++) { + for (int c = 0; c < (data[r]).length; c++) { dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - //设置固定列宽 - //dataRow.getCells().get(c).addParagraph().appendText(data[r][c]); - TextRange text =dataRow.getCells().get(c).addParagraph().appendText(data[r][c]); + TextRange text = dataRow.getCells().get(c).addParagraph().appendText(data[r][c]); text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5f); - - - // 设置列宽 - for (int i = 0; i < columnWidths.length; i++) { - row.getCells().get(i).setWidth(columnWidths[i]); - row.getCells().get(i).setCellWidthType(CellWidthType.Percentage); + text.getCharacterFormat().setFontSize(10.5F); + for (int i1 = 0; i1 < columnWidths.length; i1++) { + row.getCells().get(i1).setWidth(columnWidths[i1]); + row.getCells().get(i1).setCellWidthType(CellWidthType.Percentage); } - - } } - - - //遍历表格单元格 - for (int i = 0;i< table.getRows().getCount();i++) { - TableRow rows = table.getRows().get(i); - for (int j = 0; j< rows.getCells().getCount(); j++){ - for (int z= 0; z < rows.getCells().get(j).getParagraphs().getCount();z++){ - Paragraph p = rows.getCells().get(j).getParagraphs().get(z); - p.getFormat().setLineSpacing(12f);//设置边距为1.0 - if(j==7 && i !=0){ - p.getFormat().setHorizontalAlignment(Left); - }else{ - p.getFormat().setHorizontalAlignment(Center); + for (int m = 0; m < table.getRows().getCount(); m++) { + TableRow rows = table.getRows().get(m); + for (int i1 = 0; i1 < rows.getCells().getCount(); i1++) { + for (int z = 0; z < rows.getCells().get(i1).getParagraphs().getCount(); z++) { + Paragraph p = rows.getCells().get(i1).getParagraphs().get(z); + p.getFormat().setLineSpacing(12.0F); + if (i1 == 7 && m != 0) { + p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + } else { + p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); } } } } - document.saveToFile(outFile.getPath(), FileFormat.Docx_2013); } - - - String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); - if (suffix.equals("xml")) { - // 输出文档路径及名称 - File sourceFile = new UtilFile(path + fileName); - File targetFile = new UtilFile(docPath+ fileName); + UtilFile utilFile1 = new UtilFile(path + fileName); + UtilFile utilFile2 = new UtilFile(docPath + fileName); try { - UtilFile.copyFile(sourceFile, targetFile); + UtilFile.copyFile((File)utilFile1, (File)utilFile2); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } - - //创建实例,加载xml测试文档 - Document doc = new Document(); - doc.loadFromFile(docPath+ fileName); - - //保存为xml格式 + Document document1 = new Document(); + document1.loadFromFile(docPath + fileName); String substring = fileName.substring(0, fileName.lastIndexOf(".xml")); - //保存为Word - doc.saveToFile(docPath +"/xmltodoc/"+ substring + ".doc", FileFormat.Doc);//支持.doc - - + document1.saveToFile(docPath + "/xmltodoc/" + substring + ".doc", FileFormat.Doc); } - - if (suffix.equals("xml")) { - //保存为xml格式 String substring = fileName.substring(0, fileName.lastIndexOf(".xml")); - //保存为Word - document.insertTextFromFile(docPath+"/xmltodoc/" + substring + ".doc", FileFormat.Doc); - //保存结果文档 + document.insertTextFromFile(docPath + "/xmltodoc/" + substring + ".doc", FileFormat.Doc); document.saveToFile(outFile.getPath(), FileFormat.Docx_2013); } else if (suffix.equals("doc") || suffix.equals("docx")) { - /*document.insertTextFromFile(path + fileName, FileFormat.Docx_2013); - //保存结果文档 - document.saveToFile(outFile.getPath(), FileFormat.Docx_2013);*/ - //此处在合并文档,着重处理此处 逻辑:大于50M走wps合并,小于50M的走jar合并 - //判断用户上传的文件的大小有多大 String fileLength = String.valueOf(dcContextpdf.length()); - String maxFileLength = SDK.getAppAPI().getProperty(CoEConstant.APP_ID, "wps_export_file_size"); - String maxFileLength_B = UtilNumber.mul(UtilNumber.mul(maxFileLength, "1024.0"),"1024"); + String maxFileLength = SDK.getAppAPI().getProperty("com.actionsoft.apps.coe.pal", "wps_export_file_size"); + String maxFileLength_B = UtilNumber.mul(UtilNumber.mul(maxFileLength, "1024.0"), "1024"); System.out.println(">>fileLength = " + fileLength); System.out.println(">>maxFileLength_B = " + maxFileLength_B); - if(Double.parseDouble(UtilNumber.sub(fileLength,maxFileLength_B))>0){//大于设置的值,则走wps逻辑 - //先获取第一个文件的下载地址 - String fileURL = outFile.getPath(); // 下载文件的URL - //..\doccenter\com.awspaas.user.apps.coe.pal.output.zd\output\11dd43d0-a3c7-4ba7-860f-6eac3383e0b0\0f4c6420-cd5d-41b6-a5b3-9c4cd5464c64\测试超级大文件_1.0.doc - //构建dc对象 + if (Double.parseDouble(UtilNumber.sub(fileLength, maxFileLength_B)) > 0.0D) { + String appId, groupValue, fileValue, dcFileName, fileURL = outFile.getPath(); System.out.println(">>>>>>>>fileURL = " + fileURL); - //生产环境和测试环境文件路径深度不同,分别处理 - String appId;String groupValue;String fileValue;String dcFileName; - boolean isPrd = SDK.getAppAPI().getPropertyBooleanValue(CoEConstant.APP_ID, "isPrd",true); - if(isPrd){ - //生产环境和测试环境文件路径深度不同,分别处理 - appId =fileURL.split("/")[4]; - groupValue =fileURL.split("/")[6]; - fileValue =fileURL.split("/")[7]; + boolean isPrd = SDK.getAppAPI().getPropertyBooleanValue("com.actionsoft.apps.coe.pal", "isPrd", true); + if (isPrd) { + appId = fileURL.split("/")[4]; + groupValue = fileURL.split("/")[6]; + fileValue = fileURL.split("/")[7]; dcFileName = fileURL.split("/")[8]; - }else{ - appId =fileURL.split("/")[2]; - groupValue =fileURL.split("/")[4]; - fileValue =fileURL.split("/")[5]; + } else { + appId = fileURL.split("/")[2]; + groupValue = fileURL.split("/")[4]; + fileValue = fileURL.split("/")[5]; dcFileName = fileURL.split("/")[6]; } String dcReposirotyName = "output"; - System.out.println("dc = " + appId + "|"+groupValue+"|"+fileValue+"|"+dcFileName); - DCPluginProfile dcPluginProfile =SDK.getDCAPI().getDCProfile(appId,dcReposirotyName); - DCContext dc =new DCContext(userContext,dcPluginProfile,"com.awspaas.user.apps.coe.pal.output.zd",groupValue,fileValue,dcFileName); + System.out.println("dc = " + appId + "|" + groupValue + "|" + fileValue + "|" + dcFileName); + DCPluginProfile dcPluginProfile = SDK.getDCAPI().getDCProfile(appId, dcReposirotyName); + DCContext dc = new DCContext(userContext, dcPluginProfile, "com.awspaas.user.apps.coe.pal.output.zd", groupValue, fileValue, dcFileName); System.out.println("dc.getDownloadURL() = " + dc.getDownloadURL()); - //修改成调用wps文件发送 - mergeFileForWPS(dc,dc.getDownloadURL(), dcFileName,dcContextpdf.getDownloadURL(),fileName); - }else{//小于设定的值,则走第三方类库逻辑 + mergeFileForWPS(dc, dc.getDownloadURL(), dcFileName, dcContextpdf.getDownloadURL(), fileName); + } else { Document docs1 = new Document(); docs1.loadFromFile(outFile.getPath()); - // 加载文档2 Document docs2 = new Document(); docs2.loadFromFile(path + fileName); SectionCollection sections2 = docs2.getSections(); - sections2.insert(0, docs1.getSections().get(1).deepClone()); - sections2.insert(0, docs1.getSections().get(0).deepClone()); - // 保存文档2 + sections2.insert(0, (IDocumentObject)docs1.getSections().get(1).deepClone()); + sections2.insert(0, (IDocumentObject)docs1.getSections().get(0).deepClone()); docs2.saveToFile(outFile.getPath(), FileFormat.Docx_2013); docs2.dispose(); } } else if (suffix.equals("pptx")) { isPPT = true; } - if (isPPT == false) { - - //复制页眉页脚操作 + if (!isPPT) try { - //加载纵向模板文档用于复制 Document doc1 = new Document(); doc1.loadFromFile(tempPath + "制度-手册5.doc"); - - //获取section Section section1 = doc1.getSections().get(0); - - //加载文档2 Document doc2 = new Document(); doc2.loadFromFile(outFile.getPath()); SectionCollection sections = doc2.getSections(); - - - //加载文档1 Document doc3 = new Document(); doc3.loadFromFile(tempPath + "横板页眉页脚模板.doc"); - // 将页眉复制到目标文档的第三节以及后续节 - for (int i = 2; i < doc2.getSections().getCount(); i++) { - Section targetSection = doc2.getSections().get(i); - - PageSetup pageSetup = targetSection.getPageSetup(); - PageOrientation orientation = pageSetup.getOrientation(); - // 根据合并文档节的页面方向选择模板 - PageOrientation mergeOrientation = pageSetup.getOrientation(); - Document templateDoc = (mergeOrientation == PageOrientation.Landscape) ? doc3 : doc1; + for (int k = 2; k < doc2.getSections().getCount(); k++) { + Section targetSection = doc2.getSections().get(k); - // 复制模板文档的页眉和页脚到新文档 - HeaderFooter sourceHeader = templateDoc.getSections().get(0).getHeadersFooters().getHeader(); - HeaderFooter targetHeader = targetSection.getHeadersFooters().getHeader(); - targetHeader.getChildObjects().clear(); + double width = targetSection.getPageSetup().getPageSize().getWidth(); + double height = targetSection.getPageSetup().getPageSize().getHeight(); + + // 实际方向(根据尺寸) + boolean actualLandscape = isLandscapeBySize(width, height); + + Document templateDoc = actualLandscape ? doc3 : doc1; + + HeaderFooter sourceHeader = templateDoc.getSections().get(0).getHeadersFooters().getHeader(); + + HeaderFooter targetHeader = targetSection.getHeadersFooters().getHeader(); + targetHeader.getChildObjects().clear(); + + + + HeaderFooter header = targetSection.getHeadersFooters().getHeader(); + Paragraph hpara= header.addParagraph(); + + // 先添加文字到页眉左侧 + TextRange txt = hpara.appendText(dataMap.getString("HEADERFONT")); + txt.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None); + txt.getCharacterFormat().setFontSize(10f); + txt.getCharacterFormat().setFontName("黑体"); + + + + // 添加制表符以实现右侧定位 + hpara.appendText("\t"); + + // 添加图片到页眉右侧 + DocPicture pic = hpara.appendPicture(dataMap.getString("LOGOURL")); + pic.setHorizontalAlignment(ShapeHorizontalAlignment.Right); + pic.setVerticalOrigin(VerticalOrigin.Top_Margin_Area); + pic.setVerticalAlignment(ShapeVerticalAlignment.Center); + pic.setWidth(44.0F); + pic.setHeight(35.0F); + // 设置段落格式:左侧文字左对齐,右侧图片右对齐 + hpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + hpara.getFormat().setLeftIndent(0f); + hpara.getFormat().setFirstLineIndent(0f); + + hpara.getFormat().setAfterSpacing(25f); // 增加段后间距,可以根据需要调整数值 + hpara.getFormat().setBeforeSpacing(25f); // 也可以调整段前间距 + + + // 设置制表位以实现右侧定位 + Tab tab = hpara.getFormat().getTabs().addTab(500f, TabJustification.Right, TabLeader.No_Leader); + + + // 设置图片的文本环绕方式 + pic.setTextWrappingStyle(TextWrappingStyle.Behind); + + // 设置页眉底部边线(粗细、间距)- 文字和图片都在横线上面 + hpara.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single); + hpara.getFormat().getBorders().getBottom().setLineWidth(0.5f); + hpara.getFormat().getBorders().setSpace(1f); + + + + + /*for(int c = 0; c < targetHeader.getChildObjects().getCount(); ++c) { + DocumentObject childObj = targetHeader.getChildObjects().get(c); + + if (childObj instanceof Table) { + Table table = (Table) childObj; + + if (table.getRows().getCount() > 0 && table.getRows().get(0).getCells().getCount() > 0) { + // 处理左侧单元格的文字 + TableCell cell = table.getRows().get(0).getCells().get(0); + if (cell.getParagraphs().getCount() > 0) { + String originalText = cell.getParagraphs().get(0).getText(); + System.out.println("HEADERFONT = " + originalText); + cell.getParagraphs().get(0).setText(dataMap.getString("HEADERFONT")); + } + + // 处理右侧单元格的图片 + if (table.getRows().get(0).getCells().getCount() > 1) { + TableCell cellImg = table.getRows().get(0).getCells().get(1); + processImageCell(cellImg, dataMap.getString("LOGOURL")); + } + } + }else if(childObj instanceof Paragraph){ + processParagraph((Paragraph)childObj, dataMap); - for (int j = 0; j < sourceHeader.getChildObjects().getCount(); j++) { - //定制页眉 - Table table = (Table)sourceHeader.getChildObjects().get(0); - if (table.getRows().getCount() > 0 && table.getRows().get(0).getCells().getCount() > 0) { - //页眉文字 - TableCell cell = table.getRows().get(0).getCells().get(0); - String text = cell.getParagraphs().get(0).getText();// 假设单元格中只有一个TextRange - System.out.println("HEADERFONT = " + text); - cell.getParagraphs().get(0).setText(dataMap.getString("HEADERFONT")); - //页眉logo - String logoUrl = dataMap.getString("LOGOURL"); - TableCell cellImg = table.getRows().get(0).getCells().get(1); - IParagraph firstParagraph = cellImg.getFirstParagraph(); - //进行替换 - firstParagraph.getChildObjects().removeAt(0); - DocPicture picture = firstParagraph.appendPicture(logoUrl); - picture.setWidth(44); - picture.setHeight(35); } - DocumentObject obj = sourceHeader.getChildObjects().get(j).deepClone(); - targetHeader.getChildObjects().add(obj); - } + }*/ + + } - // 将页脚复制到目标文档的第三节以及后续节 - for (int i = 2; i < doc2.getSections().getCount(); i++) { - Section targetSection = doc2.getSections().get(i); + + + + + + + + + + for (int k = 2; k < doc2.getSections().getCount(); k++) { + Section targetSection = doc2.getSections().get(k); HeaderFooter targetFooter = targetSection.getHeadersFooters().getFooter(); - PageSetup pageSetup = targetSection.getPageSetup(); - PageOrientation mergeOrientation = pageSetup.getOrientation(); - Document templateDoc = (mergeOrientation == PageOrientation.Landscape) ? doc3 : doc1; - HeaderFooter sourceFooter = templateDoc.getSections().get(0).getHeadersFooters().getFooter(); + double width = targetSection.getPageSetup().getPageSize().getWidth(); + double height = targetSection.getPageSetup().getPageSize().getHeight(); + + // 实际方向(根据尺寸) + boolean actualLandscape = isLandscapeBySize(width, height); + + Document templateDoc = actualLandscape ? doc3 : doc1; + + HeaderFooter sourceFooter = templateDoc.getSections().get(0).getHeadersFooters().getFooter(); targetFooter.getChildObjects().clear(); - for (int j = 0; j < sourceFooter.getChildObjects().getCount(); j++) { - //定制页脚 + + /* for (int m = 0; m < sourceFooter.getChildObjects().getCount(); m++) { Table table = (Table)sourceFooter.getChildObjects().get(1); if (table.getRows().getCount() > 0 && table.getRows().get(0).getCells().getCount() > 0) { - // 定位到第一行第一列的单元格 TableCell cell = table.getRows().get(0).getCells().get(0); - // 修改单元格中的文本 - String text = cell.getParagraphs().get(0).getText();// 假设单元格中只有一个TextRange - System.out.println("FOOTERFONT = " + text); + String text = cell.getParagraphs().get(0).getText(); + cell.getParagraphs().get(0).setText(dataMap.getString("FOOTERFONT")); } - DocumentObject obj = sourceFooter.getChildObjects().get(j).deepClone(); - targetFooter.getChildObjects().add(obj); - } + DocumentObject obj = sourceFooter.getChildObjects().get(m).deepClone(); + targetFooter.getChildObjects().add((IDocumentObject)obj); + }*/ + + HeaderFooter header = targetSection.getHeadersFooters().getFooter(); + Paragraph fpara= header.addParagraph(); + // 先添加文字到页脚左侧 + TextRange txt = fpara.appendText(dataMap.getString("FOOTERFONT")); + txt.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None); + txt.getCharacterFormat().setFontSize(10f); + txt.getCharacterFormat().setFontName("黑体"); + + + fpara.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single); + fpara.getFormat().getBorders().getTop().setLineWidth(1f); + + + // 设置页脚文字左对齐 + fpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); + + // 调整页脚段落的间距,确保横线在文字上方有适当距离 + fpara.getFormat().setBeforeSpacing(15f); // 增加段前间距,让横线与文字之间有足够空间 + fpara.getFormat().setAfterSpacing(5f); // 段后间距 + + + } - - - - - doc2.saveToFile(outFile.getPath(), FileFormat.Docx_2013); - } catch (Exception e) { e.printStackTrace(); } finally { - // 关闭文档对象 - if (document != null) { + if (document != null) document.close(); - } } - } - } } - - - long b2 = System.currentTimeMillis(); - - System.err.println("复制附件用时:" - + (b2 - b1) / 1000 + "秒"); + System.err.println("复制附件用时:" + ((b2 - b1) / 1000L) + "秒"); } - - - /****************************插入支持文件、相关文件、附则等信息********************************************************/ - - Document doc = new Document(outFile.getPath()); - //获取最后一节 Section section = doc.getLastSection(); - - //添加段落,设置一级序列 - //Paragraph paragraph = section.addParagraph(); - - //paragraph.appendBreak(BreakType.Page_Break); - - // 开始 - /*********************************************************关键控制点风险矩阵 begin**********************************************************************************/ - /* PALRepositoryPropertyModel riskMatrixInfo = PALRepositoryPropertyCache.getPropertyByPropertyId(repositoryModel.getId(), "riskMatrixInfo"); - if(null!=riskMatrixInfo){ - JSONObject jsonObject = JSONObject.parseObject(riskMatrixInfo.getPropertyValue()); - if(null != jsonObject){ - JSONArray tableInfo = jsonObject.getJSONArray("table"); - //看看tableInfo是什么内容,如果没有内容,也不用生成表格 - System.out.println(">>>>>>>>>tableInfo.toString() = " + tableInfo.toString()); - if(tableInfo.size()>1){ - - CharacterFormat format2 = new CharacterFormat(); - //创建字体格式 - format2.setFontName("宋体"); - //添加段落,设置一级序列 - Paragraph paragraph2 = section.addParagraph(); - ParagraphFormat paragraphFormat2 = paragraph2.getFormat(); - paragraphFormat2.setHorizontalAlignment(Left); - TextRange tr2 = paragraph2.appendText("关键控制点风险矩阵"); - tr2.getCharacterFormat().setBold(true); - tr2.getCharacterFormat().setFontName("宋体"); - tr2.getCharacterFormat().setFontSize(12f); - paragraph2.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 - - - - //定义表格数据 - String[] header = {"关键控制点", "控制描述","对应风险描述","角色/岗位"}; - //添加表格的表头 - Table table = section.addTable(true); - table.resetCells(tableInfo.size(),header.length); - //table.getTableFormat().isAutoResized(true); - table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); - TableRow row = table.getRows().get(0); - row.isHeader(true); - row.setHeightType(TableRowHeightType.Auto); - for (int i = 0; i < header.length; i++) { - row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - Paragraph p = row.getCells().get(i).addParagraph(); - p.getFormat().setHorizontalAlignment(Center); - TextRange txtRange = p.appendText(header[i]); - txtRange.getCharacterFormat().setBold(true); - txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5f); - } - - - //添加数据到表中 - for (int i = 1; i < tableInfo.size(); i++) { - JSONObject cellInfo = tableInfo.getJSONObject(i); - TableRow dataRow = table.getRows().get(i); - dataRow.setHeight(25); - dataRow.setHeightType(TableRowHeightType.Exactly); - int flagNum = 0; - for (String cellKey : cellInfo.keySet()) { - if(cellKey.equals("id")){ - continue; - } - dataRow.getCells().get(flagNum).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - - TableCell cell = dataRow.getCells().get(flagNum); - - - // 清除单元格原有段落(重要!) - cell.getParagraphs().clear(); - - Paragraph p = cell.addParagraph(); - - - // 第一列居中,第二列居左 - if (flagNum == 0) { - p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); - } else { - p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); - - } - - TextRange text =dataRow.getCells().get(flagNum).addParagraph().appendText(cellInfo.getString(cellKey)); - text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5f); - flagNum++; - - } - - } - - - Paragraph paragraph_blank = section.addParagraph(); - } - } - }*/ - - - - - - JSONArray riskMatrix = new JSONArray(); //组织职责Table + JSONArray riskMatrix = new JSONArray(); PALRepositoryPropertyModel riskMatrixInfoData = PALRepositoryPropertyCache.getPropertyByPropertyId(repositoryModel.getId(), "riskMatrixInfo"); - - - if(null!=riskMatrixInfoData) { + if (null != riskMatrixInfoData) { JSONObject jsonObject = JSONObject.parseObject(riskMatrixInfoData.getPropertyValue()); if (null != jsonObject) { JSONArray tableInfo = jsonObject.getJSONArray("table"); - //看看tableInfo是什么内容,如果没有内容,也不用生成表格 System.out.println(">>>>>>>>>tableInfo.toString() = " + tableInfo.toString()); if (tableInfo.size() > 1) { - - int index = 0; - - //添加数据到表中 + int j = 0; for (int i = 1; i < tableInfo.size(); i++) { JSONObject cellInfo = tableInfo.getJSONObject(i); JSONObject tmp = new JSONObject(); @@ -1024,163 +869,108 @@ public class OutputWordUtil { riskMatrix.add(tmp); } CharacterFormat format2 = new CharacterFormat(); - //创建字体格式 format2.setFontName("宋体"); - //添加段落,设置一级序列 Paragraph paragraph2 = section.addParagraph(); ParagraphFormat paragraphFormat2 = paragraph2.getFormat(); - paragraphFormat2.setHorizontalAlignment(Left); + paragraphFormat2.setHorizontalAlignment(HorizontalAlignment.Left); TextRange tr2 = paragraph2.appendText("关键控制点风险矩阵"); tr2.getCharacterFormat().setBold(true); tr2.getCharacterFormat().setFontName("宋体"); - tr2.getCharacterFormat().setFontSize(12f); - paragraph2.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 - - - //定义表格数据 - String[] header = {"关键控制点", "控制描述","对应风险描述","角色/岗位"}; + tr2.getCharacterFormat().setFontSize(12.0F); + paragraph2.applyStyle(BuiltinStyle.Body_Text); + String[] header = { "关键控制点", "控制描述", "对应风险描述", "角色/岗位" }; String[][] strArray2 = new String[riskMatrix.size()][]; - List list = new LinkedList<>(); - for (int i = 0; i < riskMatrix.size(); i++) { - JSONObject jsonObject1 = riskMatrix.getJSONObject(i); + List list = (List)new LinkedList<>(); + for (int k = 0; k < riskMatrix.size(); k++) { + JSONObject jsonObject1 = riskMatrix.getJSONObject(k); String[] strArray = new String[4]; strArray[0] = jsonObject1.getString("firstColumn").toString(); strArray[1] = jsonObject1.getString("secondColumn").toString(); strArray[2] = jsonObject1.getString("threeColumn").toString(); strArray[3] = jsonObject1.getString("fourColumn").toString(); list.add(strArray); - strArray2[i] = strArray; + strArray2[k] = strArray; } - String[][] data = strArray2; - - //添加表格 Table table = section.addTable(true); table.resetCells(data.length + 1, header.length); - table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); - - TableRow row = table.getRows().get(0); row.isHeader(true); - row.setHeight(20); + row.setHeight(20.0F); row.setHeightType(TableRowHeightType.Exactly); - for (int i = 0; i < header.length; i++) { - row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - Paragraph p = row.getCells().get(i).addParagraph(); - p.getFormat().setHorizontalAlignment(Center); - TextRange txtRange = p.appendText(header[i]); + for (int m = 0; m < header.length; m++) { + row.getCells().get(m).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + Paragraph p = row.getCells().get(m).addParagraph(); + p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + TextRange txtRange = p.appendText(header[m]); txtRange.getCharacterFormat().setBold(true); txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5f); + txtRange.getCharacterFormat().setFontSize(10.5F); } - - - float[] columnWidths = {20f, 30f,30f,20f}; // 比例总和为100% - - // 设置列宽 - for (int i = 0; i < columnWidths.length; i++) { - row.getCells().get(i).setWidth(columnWidths[i]); - } - - //将数据添加到其余行 + float[] columnWidths = { 20.0F, 30.0F, 30.0F, 20.0F }; + for (int n = 0; n < columnWidths.length; n++) + row.getCells().get(n).setWidth(columnWidths[n]); for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); - dataRow.setHeight(20); - //dataRow.setHeightType(TableRowHeightType.Auto); + dataRow.setHeight(20.0F); dataRow.getRowFormat().setBackColor(Color.white); - for (int c = 0; c < data[r].length; c++) { - + for (int c = 0; c < (data[r]).length; c++) { TableCell cell = dataRow.getCells().get(c); - dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - - // 清除单元格原有段落(重要!) cell.getParagraphs().clear(); - Paragraph p = cell.addParagraph(); - - - // 第一列居中,第二列居左 if (c == 0) { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); } else { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); - } TextRange text = p.appendText(data[r][c]); text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5f); - - // 设置列宽 - for (int i = 0; i < columnWidths.length; i++) { - dataRow.getCells().get(i).setWidth(columnWidths[i]); - dataRow.getCells().get(i).setCellWidthType(CellWidthType.Percentage); - + text.getCharacterFormat().setFontSize(10.5F); + for (int i1 = 0; i1 < columnWidths.length; i1++) { + dataRow.getCells().get(i1).setWidth(columnWidths[i1]); + dataRow.getCells().get(i1).setCellWidthType(CellWidthType.Percentage); } } } - - - Paragraph paragraph_blank = section.addParagraph(); - - } - - - + Paragraph paragraph1 = section.addParagraph(); } } - - - - - /*********************************************************关键控制点风险矩阵 end******************************************************************/ - - - - /**********************************************相关/支持文件表格绘制 begin**********************************************************************/ - JSONArray related_support_files = new JSONArray(); //组织职责Table + } + JSONArray related_support_files = new JSONArray(); List relationList = DesignerShapeRelationCache.getListByAttrId(repositoryModel.getId(), "", "related_support_files"); - relationList.sort(Comparator.comparing(DesignerShapeRelationModel::getShapeText)); - int index = 0; if (relationList.size() > 0) { for (DesignerShapeRelationModel relation : relationList) { - String relationFileId = relation.getRelationFileId();// 支持或相关文件的ID + String relationFileId = relation.getRelationFileId(); List models = PALRepositoryCache.getByVersionId(relationFileId); if (models != null && models.size() > 0) { index++; - for(PALRepositoryModel oneModel:models){ - if(oneModel.isUse()==true){ + for (PALRepositoryModel oneModel : models) { + if (oneModel.isUse() == true) { JSONObject tmp = new JSONObject(); tmp.put("name", oneModel.getName()); - tmp.put("desc", index); + tmp.put("desc", Integer.valueOf(index)); related_support_files.add(tmp); } } } } - - CharacterFormat format2 = new CharacterFormat(); - //创建字体格式 format2.setFontName("宋体"); - //添加段落,设置一级序列 Paragraph paragraph2 = section.addParagraph(); ParagraphFormat paragraphFormat2 = paragraph2.getFormat(); - paragraphFormat2.setHorizontalAlignment(Left); + paragraphFormat2.setHorizontalAlignment(HorizontalAlignment.Left); TextRange tr2 = paragraph2.appendText("相关/支持文件"); tr2.getCharacterFormat().setBold(true); tr2.getCharacterFormat().setFontName("宋体"); - tr2.getCharacterFormat().setFontSize(12f); - paragraph2.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 - - - //定义表格数据 - String[] header = {"序号", "文件名称"}; + tr2.getCharacterFormat().setFontSize(12.0F); + paragraph2.applyStyle(BuiltinStyle.Body_Text); + String[] header = { "序号", "文件名称" }; String[][] strArray2 = new String[related_support_files.size()][]; - List list = new LinkedList<>(); + List list = (List)new LinkedList<>(); for (int i = 0; i < related_support_files.size(); i++) { JSONObject jsonObject = related_support_files.getJSONObject(i); String[] strArray = new String[2]; @@ -1189,149 +979,96 @@ public class OutputWordUtil { list.add(strArray); strArray2[i] = strArray; } - String[][] data = strArray2; - - //添加表格 Table table = section.addTable(true); table.resetCells(data.length + 1, header.length); - table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); - - TableRow row = table.getRows().get(0); row.isHeader(true); - row.setHeight(20); + row.setHeight(20.0F); row.setHeightType(TableRowHeightType.Exactly); - for (int i = 0; i < header.length; i++) { - row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - Paragraph p = row.getCells().get(i).addParagraph(); - p.getFormat().setHorizontalAlignment(Center); - TextRange txtRange = p.appendText(header[i]); + for (int j = 0; j < header.length; j++) { + row.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + Paragraph p = row.getCells().get(j).addParagraph(); + p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + TextRange txtRange = p.appendText(header[j]); txtRange.getCharacterFormat().setBold(true); txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5f); + txtRange.getCharacterFormat().setFontSize(10.5F); } - - float[] columnWidths = {10f, 90f}; // 比例总和为100% - - // 设置列宽 - for (int i = 0; i < columnWidths.length; i++) { - row.getCells().get(i).setWidth(columnWidths[i]); - row.getCells().get(i).setCellWidthType(CellWidthType.Percentage); - + float[] columnWidths = { 10.0F, 90.0F }; + for (int k = 0; k < columnWidths.length; k++) { + row.getCells().get(k).setWidth(columnWidths[k]); + row.getCells().get(k).setCellWidthType(CellWidthType.Percentage); } - - - //将数据添加到其余行 for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); - dataRow.setHeight(20); - //dataRow.setHeightType(TableRowHeightType.Auto); + dataRow.setHeight(20.0F); dataRow.getRowFormat().setBackColor(Color.white); - for (int c = 0; c < data[r].length; c++) { - + for (int c = 0; c < (data[r]).length; c++) { TableCell cell = dataRow.getCells().get(c); - dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - - // 清除单元格原有段落(重要!) cell.getParagraphs().clear(); - Paragraph p = cell.addParagraph(); - - - // 第一列居中,第二列居左 if (c == 0) { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); } else { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); - } TextRange text = p.appendText(data[r][c]); text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5f); - - // 设置列宽 - for (int i = 0; i < columnWidths.length; i++) { - dataRow.getCells().get(i).setWidth(columnWidths[i]); - dataRow.getCells().get(i).setCellWidthType(CellWidthType.Percentage); - + text.getCharacterFormat().setFontSize(10.5F); + for (int m = 0; m < columnWidths.length; m++) { + dataRow.getCells().get(m).setWidth(columnWidths[m]); + dataRow.getCells().get(m).setCellWidthType(CellWidthType.Percentage); } } } - - - - Paragraph paragraph_blank = section.addParagraph(); + Paragraph paragraph1 = section.addParagraph(); } - - /**********************************************相关/支持文件表格绘制 end*********************************************************************/ - - - - - /**********************************************外部相关文件表格绘制 begin*********************************************************************/ - int extercount = 0; - //外部相关文件 - JSONArray ExternalCorrelationFileArray = new JSONArray(); //外部相关文件Table - String sqlOut = "select PROPERTYVALUE from APP_ACT_COE_PAL_PROP where PLID = '"+repositoryModel.getId()+"' and PROPERTYID = 'Out_related_files'"; + JSONArray ExternalCorrelationFileArray = new JSONArray(); + String sqlOut = "select PROPERTYVALUE from APP_ACT_COE_PAL_PROP where PLID = '" + repositoryModel.getId() + "' and PROPERTYID = 'Out_related_files'"; String outRelatFileJson = DBSql.getString(sqlOut); - if(UtilString.isNotEmpty(outRelatFileJson)) { - if(outRelatFileJson.contains(",")) { + if (UtilString.isNotEmpty(outRelatFileJson)) { + if (outRelatFileJson.contains(",")) { String[] split = outRelatFileJson.split(","); for (String str : split) { extercount++; JSONObject tmp = new JSONObject(); - tmp.put("name", str+"【外部】"); - tmp.put("desc", extercount); + tmp.put("name", str + "【外部】"); + tmp.put("desc", Integer.valueOf(extercount)); ExternalCorrelationFileArray.add(tmp); } - }else if(outRelatFileJson.contains(",")) { + } else if (outRelatFileJson.contains(",")) { String[] split = outRelatFileJson.split(","); for (String str : split) { extercount++; JSONObject tmp = new JSONObject(); - tmp.put("name", str+"【外部】"); - tmp.put("desc", extercount); + tmp.put("name", str + "【外部】"); + tmp.put("desc", Integer.valueOf(extercount)); ExternalCorrelationFileArray.add(tmp); } - }else { + } else { extercount++; JSONObject tmp = new JSONObject(); - tmp.put("name", outRelatFileJson+"【外部】"); - tmp.put("desc", extercount); + tmp.put("name", outRelatFileJson + "【外部】"); + tmp.put("desc", Integer.valueOf(extercount)); ExternalCorrelationFileArray.add(tmp); } - - - CharacterFormat format = new CharacterFormat(); - //创建字体格式 format.setFontName("宋体"); - //添加段落,设置一级序列 Paragraph paragraph1 = section.addParagraph(); - ParagraphFormat paragraphFormat1 = paragraph1.getFormat(); - paragraphFormat1.setHorizontalAlignment(Left); - + paragraphFormat1.setHorizontalAlignment(HorizontalAlignment.Left); TextRange tr = paragraph1.appendText("外部相关文件"); tr.getCharacterFormat().setBold(true); tr.getCharacterFormat().setFontName("宋体"); - tr.getCharacterFormat().setFontSize(12f); - //tr.applyCharacterFormat(format); //应用字体格式 - paragraph1.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 - - - - - - //定义表格数据 - String[] header = {"序号", "文件名称"}; - + tr.getCharacterFormat().setFontSize(12.0F); + paragraph1.applyStyle(BuiltinStyle.Body_Text); + String[] header = { "序号", "文件名称" }; String[][] strArray2 = new String[ExternalCorrelationFileArray.size()][]; - List list = new LinkedList<>(); + List list = (List)new LinkedList<>(); for (int i = 0; i < ExternalCorrelationFileArray.size(); i++) { JSONObject jsonObject = ExternalCorrelationFileArray.getJSONObject(i); String[] strArray = new String[2]; @@ -1340,248 +1077,333 @@ public class OutputWordUtil { list.add(strArray); strArray2[i] = strArray; } - String[][] data = strArray2; - - //添加表格 Table table = section.addTable(true); table.resetCells(data.length + 1, header.length); table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window); TableRow row = table.getRows().get(0); row.isHeader(true); - row.setHeight(20); + row.setHeight(20.0F); row.setHeightType(TableRowHeightType.Exactly); - - - - for (int i = 0; i < header.length; i++) { - - TableCell cell = row.getCells().get(i); - - row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - - // 清除单元格原有段落(重要!) + for (int j = 0; j < header.length; j++) { + TableCell cell = row.getCells().get(j); + row.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); cell.getParagraphs().clear(); - - Paragraph p = row.getCells().get(i).addParagraph(); + Paragraph p = row.getCells().get(j).addParagraph(); p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); - - TextRange txtRange = p.appendText(header[i]); + TextRange txtRange = p.appendText(header[j]); txtRange.getCharacterFormat().setBold(true); txtRange.getCharacterFormat().setFontName("宋体"); - txtRange.getCharacterFormat().setFontSize(10.5f); - + txtRange.getCharacterFormat().setFontSize(10.5F); } - - - float[] columnWidths = {10f, 90f}; // 比例总和为100% - - - //将数据添加到其余行 + float[] columnWidths = { 10.0F, 90.0F }; for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); - dataRow.setHeight(20); - //dataRow.setHeightType(TableRowHeightType.Exactly); - for (int c = 0; c < data[r].length; c++) { + dataRow.setHeight(20.0F); + for (int c = 0; c < (data[r]).length; c++) { TableCell cell = dataRow.getCells().get(c); - dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); - - // 清除单元格原有段落(重要!) cell.getParagraphs().clear(); - Paragraph p = cell.addParagraph(); - - - // 第一列居中,第二列居左 if (c == 0) { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); } else { p.getFormat().setHorizontalAlignment(HorizontalAlignment.Left); - } TextRange text = p.appendText(data[r][c]); text.getCharacterFormat().setFontName("宋体"); - text.getCharacterFormat().setFontSize(10.5f); - - // 设置列宽 - for (int i = 0; i < columnWidths.length; i++) { - row.getCells().get(i).setWidth(columnWidths[i]); - row.getCells().get(i).setCellWidthType(CellWidthType.Percentage); - + text.getCharacterFormat().setFontSize(10.5F); + for (int k = 0; k < columnWidths.length; k++) { + row.getCells().get(k).setWidth(columnWidths[k]); + row.getCells().get(k).setCellWidthType(CellWidthType.Percentage); } } } - - - - - - - - Paragraph paragraph_blank = section.addParagraph(); + Paragraph paragraph2 = section.addParagraph(); } - - /**********************************************外部相关文件表格绘制 end*********************************************************************/ - - - - - //查询模型文件属性上传附件信息 List search2 = upFileDao.searchByRepositoryId(repositoryModel.getId(), "f"); - DCContext dcContextModel = null; - //读取模型附件插入手册中文档对象 if (search2 != null && search2.size() > 0) { - //插入前,附件名先排序先排序 sortFilesByNumber(search2); - //附件如果为空,不插入附件标题 CharacterFormat format4 = new CharacterFormat(); - //创建字体格式 format4.setFontName("宋体"); - //添加段落 Paragraph paragraph4 = section.addParagraph(); - ParagraphFormat paragraphFormat4 = paragraph4.getFormat(); - paragraphFormat4.setHorizontalAlignment(Left); - + paragraphFormat4.setHorizontalAlignment(HorizontalAlignment.Left); TextRange tr4 = paragraph4.appendText("附件"); - - tr4.getCharacterFormat().setBold(true); tr4.getCharacterFormat().setFontName("宋体"); - tr4.getCharacterFormat().setFontSize(12); - paragraph4.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 - - + tr4.getCharacterFormat().setFontSize(12.0F); + paragraph4.applyStyle(BuiltinStyle.Body_Text); long b1 = System.currentTimeMillis(); - for (UpfileModel upfileModel : search2) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); + DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); if (dcProfile != null) { - - // 处理DocCenter - dcContextModel = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, "file", upfileModel.getPl_uuid(), upfileModel.getFileName()); - //添加段落 + dcContextModel = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", "file", upfileModel.getPl_uuid(), upfileModel.getFileName()); Paragraph paragraph5 = section.addParagraph(); - //加载一个图片,它将作为外部文件的符号显示在Word文档中 - //获取最后一个.的位置 int lastIndexOf = dcContextModel.getFileName().lastIndexOf("."); - //获取文件的后缀名 .jpg String suffix = dcContextModel.getFileName().substring(lastIndexOf); - - DocPicture pdfIcon = new DocPicture(doc); - + DocPicture pdfIcon = new DocPicture((IDocument)doc); InputStream stream1 = new FileInputStream(dcContextModel.getFilePath()); - DocPicture pic1 = new DocPicture(doc); - + DocPicture pic1 = new DocPicture((IDocument)doc); if (suffix.equals(".doc") || suffix.equals(".docx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/word.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); if (suffix.equals(".doc")) { paragraph5.appendOleObject(stream1, pic1, "doc"); - } else if (suffix.equals(".docx")) { - paragraph5.appendOleObject(stream1, pic1, "docx"); + continue; } - } else if (suffix.equals(".pdf")) { + if (suffix.equals(".docx")) + paragraph5.appendOleObject(stream1, pic1, "docx"); + continue; + } + if (suffix.equals(".pdf")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/pdf.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); paragraph5.appendOleObject(stream1, pic1, "pdf"); - } else if (suffix.equals(".xls") || suffix.equals(".xlsx")) { + continue; + } + if (suffix.equals(".xls") || suffix.equals(".xlsx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/xls.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); if (suffix.equals(".xls")) { paragraph5.appendOleObject(stream1, pic1, "xls"); - } else if (suffix.equals(".xlsx")) { - paragraph5.appendOleObject(stream1, pic1, "xlsx"); + continue; } - } else if (suffix.equals(".png") || suffix.equals(".jgp")) { + if (suffix.equals(".xlsx")) + paragraph5.appendOleObject(stream1, pic1, "xlsx"); + continue; + } + if (suffix.equals(".png") || suffix.equals(".jgp")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/png.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); if (suffix.equals(".png")) { paragraph5.appendOleObject(stream1, pic1, "png"); - } else if (suffix.equals(".jpg")) { - paragraph5.appendOleObject(stream1, pic1, "jpg"); + continue; } - } else if (suffix.equals(".zip") || suffix.equals(".rar")) { + if (suffix.equals(".jpg")) + paragraph5.appendOleObject(stream1, pic1, "jpg"); + continue; + } + if (suffix.equals(".zip") || suffix.equals(".rar")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/zip.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); if (suffix.equals(".zip")) { paragraph5.appendOleObject(stream1, pic1, "zip"); - } else if (suffix.equals(".rar")) { - paragraph5.appendOleObject(stream1, pic1, "rar"); + continue; } - } else if (suffix.equals(".mp3") || suffix.equals(".mp4")) { + if (suffix.equals(".rar")) + paragraph5.appendOleObject(stream1, pic1, "rar"); + continue; + } + if (suffix.equals(".mp3") || suffix.equals(".mp4")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/mp3.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); if (suffix.equals(".mp3")) { paragraph5.appendOleObject(stream1, pic1, "mp3"); - } else if (suffix.equals(".mp4")) { - paragraph5.appendOleObject(stream1, pic1, "mp4"); + continue; } - } else if (suffix.equals(".ppt") || suffix.equals(".pptx")) { + if (suffix.equals(".mp4")) + paragraph5.appendOleObject(stream1, pic1, "mp4"); + continue; + } + if (suffix.equals(".ppt") || suffix.equals(".pptx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/ppt.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); if (suffix.equals(".ppt")) { paragraph5.appendOleObject(stream1, pic1, "ppt"); - } else if (suffix.equals(".pptx")) { - paragraph5.appendOleObject(stream1, pic1, "pptx"); + continue; } - } else if (suffix.equals(".txt")) { + if (suffix.equals(".pptx")) + paragraph5.appendOleObject(stream1, pic1, "pptx"); + continue; + } + if (suffix.equals(".txt")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/txt.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); - paragraph5.applyStyle(BuiltinStyle.Body_Text); //应用标题1样式 + paragraph5.appendText(dcContextModel.getFileName() + " "); + paragraph5.applyStyle(BuiltinStyle.Body_Text); paragraph5.appendOleObject(stream1, pic1, "txt"); } - - } - } long b2 = System.currentTimeMillis(); - System.err.println("插入附件用时:" - + (b2 - b1) / 1000 + "秒"); + System.err.println("插入附件用时:" + ((b2 - b1) / 1000L) + "秒"); } - try { - System.out.println("Filed=================="+repositoryModel.getId()); + System.out.println("Filed==================" + repositoryModel.getId()); doc.saveToFile(outFile.getPath(), FileFormat.Docx_2013); } catch (Exception e) { e.printStackTrace(); } finally { - // 关闭文档对象 doc.close(); } + } + } + + // 针对横版页眉的特殊处理 + private static void processLandscapeHeader(HeaderFooter header, JSONObject dataMap) { + for (int c = 0; c < header.getChildObjects().getCount(); c++) { + DocumentObject childObj = header.getChildObjects().get(c); + + if (childObj instanceof Table) { + Table table = (Table) childObj; + // 横版可能需要对表格布局做特殊调整 + adjustTableForLandscape(table, dataMap); + } + // 其他横版特有的处理逻辑 + } + } + + + // 调整表格适应横版 + private static void adjustTableForLandscape(Table table, JSONObject dataMap) { + // 调整列宽比例 + if (table.getRows().getCount() > 0) { + TableRow row = table.getRows().get(0); + if (row.getCells().getCount() >= 2) { + row.getCells().get(0).setWidth(70f); + row.getCells().get(1).setWidth(70f); + + + } } + // 处理内容 + processTable(table, dataMap); + } + + // 处理表格中的占位符 + private static void processTable(Table table, JSONObject dataMap) { + for (int i = 0; i < table.getRows().getCount(); i++) { + TableRow row = table.getRows().get(i); + for (int j = 0; j < row.getCells().getCount(); j++) { + TableCell cell = row.getCells().get(j); + for (int k = 0; k < cell.getParagraphs().getCount(); k++) { + Paragraph paragraph = cell.getParagraphs().get(k); + processParagraph(paragraph, dataMap); + } + } + } } /** - * 生成word文件 - * - * @param dataMap - * @param tempPath - * @param tempName - * @param docName + * 判断是否为横向 */ + public static boolean isLandscapeBySize(double width, double height) { + return width > height; + } + + + // 处理段落中的占位符 + private static void processParagraph(Paragraph paragraph, JSONObject dataMap) { + for (int i = 0; i < paragraph.getChildObjects().getCount(); i++) { + DocumentObject paraChild = paragraph.getChildObjects().get(i); + + if (paraChild instanceof TextRange) { + // 处理文本占位符 + TextRange textRange = (TextRange) paraChild; + textRange.setText(dataMap.getString("HEADERFONT")); + } else if (paraChild instanceof DocPicture) { + // 处理图片占位符 + DocPicture picture = (DocPicture) paraChild; + processPicture(picture, dataMap); + } + // 可以添加其他类型的处理 + } + } + + + + // 替换占位符的具体实现 + private static String replacePlaceholders(String text, JSONObject dataMap) { + // 使用正则表达式匹配 ${...} 格式的占位符 + Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}"); + Matcher matcher = pattern.matcher(text); + StringBuffer result = new StringBuffer(); + + while (matcher.find()) { + String placeholder = matcher.group(1); // 获取占位符名称 + String replacement = dataMap.getString(placeholder); // 从数据映射中获取值 + + // 特殊处理LOGOURL,可能需要替换为图片 + if ("LOGOURL".equals(placeholder) && !replacement.isEmpty()) { + // 这里可以设置标志,后续处理图片 + replacement = "[LOGO_PLACEHOLDER]"; // 临时占位符 + } + + matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); + } + matcher.appendTail(result); + + return result.toString(); + } + + + // 处理图片 + private static void processPicture(DocPicture picture, JSONObject dataMap) { + // 检查图片是否有特殊标记或需要替换 + String altText = picture.getAlternativeText(); + if (altText != null && altText.contains("${LOGOURL}")) { + String logoUrl = dataMap.getString("LOGOURL"); + if (logoUrl != null && !logoUrl.isEmpty()) { + try { + // 重新设置图片 + picture.loadImage(logoUrl); + picture.setWidth(44.0F); + picture.setHeight(35.0F); + } catch (Exception e) { + System.out.println("图片加载失败: " + logoUrl); + } + } + } + } + + + + + private static void processImageCell(TableCell cell, String logoUrl) { + if (cell.getParagraphs().getCount() > 0) { + IParagraph firstParagraph = cell.getFirstParagraph(); + + // 清除段落中的所有现有内容 + firstParagraph.getChildObjects().clear(); + + try { + // 添加新图片 + DocPicture picture = firstParagraph.appendPicture(logoUrl); + picture.setWidth(44.0F); + picture.setHeight(35.0F); + + // 设置图片对齐方式 + firstParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right); + + } catch (Exception e) { + // 图片加载失败时添加文本占位符 + ITextRange textRange = firstParagraph.appendText("[图片加载失败]"); + textRange.getCharacterFormat().setTextColor(Color.RED); + textRange.getCharacterFormat().setItalic(true); + } + } + } + + + public static void createBdDoc2(JSONObject dataMap, String tempPath, String tempName, String docName, String repositoryId) throws FileNotFoundException { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); - - // 设置模本装置方法和路径 try { UtilFile temps = new UtilFile(tempPath); - configuration.setDirectoryForTemplateLoading(temps); + configuration.setDirectoryForTemplateLoading((File)temps); } catch (IOException e2) { e2.printStackTrace(); } @@ -1591,60 +1413,31 @@ public class OutputWordUtil { } catch (IOException e) { e.printStackTrace(); } - - //判断表单图是否为单一模型并且只上传excel一种附件,导出手册直接导出excel手册 PALRepositoryModel repositoryModel = PALRepositoryQueryAPIManager.getInstance().queryPalRepositoryModelByPalId(repositoryId); - UpFileDao upFileDao = new UpFileDao(); - //查询模型文件属性上传附件信息 List search = upFileDao.searchByRepositoryId(repositoryModel.getId(), "s"); - - if (search.size() > 0) { + if (search.size() > 0) if (search.size() == 1) { DCContext dcContextModel = null; - //获取 - String getExcelFileName = search.get(0).getFileName(); - - //获取文件的后缀名 + String getExcelFileName = ((UpfileModel)search.get(0)).getFileName(); int lastIndexOf = getExcelFileName.lastIndexOf("."); String suffix = getExcelFileName.substring(lastIndexOf); if (suffix.equals(".xls") || suffix.equals(".xlsx")) { - - DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); - + DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); UserContext userContext = DispatcherRequest.getUserContext(); - - String excelUrl = docName.substring(0, docName.lastIndexOf("/") + 1); - - // 调用App String sourceAppId = "com.actionsoft.apps.coe.pal"; - // aslp服务地址 String aslp = "aslp://com.awspaas.user.apps.new_performance_indicator_library/UpdatePptxAndExcelAslp"; - // 参数定义列表 Map params = new HashMap(); - //文件id,必填 params.put("pl_uuid", repositoryId); - //文件内容id,必填 - params.put("shape_uuid", search.get(0).getShape_uuid()); - - //文件保存地址,必填 + params.put("shape_uuid",search.get(0).getShape_uuid()); params.put("fil_path", excelUrl + search.get(0).getFileName()); - - //文件路径(不包含文件名称),必填 params.put("file_url", excelUrl); - - //文件名称,必填 params.put("file_data", search.get(0).getFileName()); - //sid,必填 params.put("sid", userContext.getSessionId()); AppAPI appAPI = SDK.getAppAPI(); - //根据上传的文件进行更新相关的excel或者ppt - ResponseObject ro = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params); - - + ResponseObject responseObject = appAPI.callASLP(appAPI.getAppContext(sourceAppId), aslp, params); } else { - // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -1652,7 +1445,6 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } - try { if (t != null && out != null) { t.process(dataMap, out); @@ -1666,10 +1458,7 @@ public class OutputWordUtil { } ConcatenationformBySpire(outFile.getPath(), search); } - - } else { - // 输出文档路径及名称 File outFile = new File(docName); Writer out = null; try { @@ -1677,7 +1466,6 @@ public class OutputWordUtil { } catch (Exception e1) { e1.printStackTrace(); } - try { if (t != null && out != null) { t.process(dataMap, out); @@ -1691,188 +1479,143 @@ public class OutputWordUtil { } ConcatenationformBySpire(outFile.getPath(), search); } - } - - } - public static void ConcatenationformBySpire(String filePath, List search) throws FileNotFoundException { - /**************************************************插入文件对象**********************************************************************/ Document doc = new Document(filePath); - //获取最后一节 Section section = doc.getLastSection(); - - CharacterFormat format4 = new CharacterFormat(); - //创建字体格式 format4.setFontName("宋体"); - //添加段落 Paragraph paragraph = section.addParagraph(); - - ParagraphFormat paragraphFormat4 = paragraph.getFormat(); - paragraphFormat4.setHorizontalAlignment(Left); - + paragraphFormat4.setHorizontalAlignment(HorizontalAlignment.Left); TextRange tr4 = paragraph.appendText("表单/模板"); - tr4.getCharacterFormat().setBold(true); tr4.getCharacterFormat().setFontName("宋体"); - paragraph.applyStyle(BuiltinStyle.Heading_2); //应用标题1样式 - - //doc.saveToFile(outFile.getPath(), FileFormat.Docx_2013); - - + paragraph.applyStyle(BuiltinStyle.Heading_2); DCContext dcContextModel = null; UserContext userContext = DispatcherRequest.getUserContext(); if (search != null && search.size() > 0) { - //插入前,附件名先排序先排序 sortFilesByNumber(search); - // 复制附件 for (UpfileModel upfileModel : search) { - DCPluginProfile dcProfile = DCProfileManager.getDCProfile(CoEConstant.APP_ID, CoeFileConstant.COE_UPFILE); - + DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.actionsoft.apps.coe.pal", "COE_Upfile"); if (dcProfile != null) { - dcContextModel = new DCContext(userContext, dcProfile, CoEConstant.APP_ID, upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); + dcContextModel = new DCContext(userContext, dcProfile, "com.actionsoft.apps.coe.pal", upfileModel.getPl_uuid(), upfileModel.getShape_uuid(), upfileModel.getFileName()); String path = dcContextModel.getPath(); String fileName = dcContextModel.getFileName(); - - - //添加段落 Paragraph paragraph5 = section.addParagraph(); - - //加载一个图片,它将作为外部文件的符号显示在Word文档中 - //获取最后一个.的位置 int lastIndexOf = dcContextModel.getFileName().lastIndexOf("."); - //获取文件的后缀名 .jpg String suffix = dcContextModel.getFileName().substring(lastIndexOf); - - DocPicture pdfIcon = new DocPicture(doc); - + DocPicture pdfIcon = new DocPicture((IDocument)doc); InputStream stream1 = new FileInputStream(dcContextModel.getFilePath()); - DocPicture pic1 = new DocPicture(doc); - + DocPicture pic1 = new DocPicture((IDocument)doc); if (suffix.equals(".doc") || suffix.equals(".docx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/word.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".doc")) { paragraph5.appendOleObject(stream1, pic1, "doc"); - } else if (suffix.equals(".docx")) { - paragraph5.appendOleObject(stream1, pic1, "docx"); + continue; } - } else if (suffix.equals(".pdf")) { + if (suffix.equals(".docx")) + paragraph5.appendOleObject(stream1, pic1, "docx"); + continue; + } + if (suffix.equals(".pdf")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/pdf.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); paragraph5.appendOleObject(stream1, pic1, "pdf"); - } else if (suffix.equals(".xls") || suffix.equals(".xlsx")) { + continue; + } + if (suffix.equals(".xls") || suffix.equals(".xlsx")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/xls.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".xls")) { paragraph5.appendOleObject(stream1, pic1, "xls"); - } else if (suffix.equals(".xlsx")) { - paragraph5.appendOleObject(stream1, pic1, "xlsx"); + continue; } - } else if (suffix.equals(".png") || suffix.equals(".jgp")) { + if (suffix.equals(".xlsx")) + paragraph5.appendOleObject(stream1, pic1, "xlsx"); + continue; + } + if (suffix.equals(".png") || suffix.equals(".jgp")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/png.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".png")) { paragraph5.appendOleObject(stream1, pic1, "png"); - } else if (suffix.equals(".jpg")) { - paragraph5.appendOleObject(stream1, pic1, "jpg"); + continue; } - } else if (suffix.equals(".zip") || suffix.equals(".rar")) { + if (suffix.equals(".jpg")) + paragraph5.appendOleObject(stream1, pic1, "jpg"); + continue; + } + if (suffix.equals(".zip") || suffix.equals(".rar")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/zip.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".zip")) { paragraph5.appendOleObject(stream1, pic1, "zip"); - } else if (suffix.equals(".rar")) { - paragraph5.appendOleObject(stream1, pic1, "rar"); + continue; } - } else if (suffix.equals(".mp3") || suffix.equals(".mp4")) { + if (suffix.equals(".rar")) + paragraph5.appendOleObject(stream1, pic1, "rar"); + continue; + } + if (suffix.equals(".mp3") || suffix.equals(".mp4")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/mp3.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); if (suffix.equals(".mp3")) { paragraph5.appendOleObject(stream1, pic1, "mp3"); - } else if (suffix.equals(".mp4")) { - paragraph5.appendOleObject(stream1, pic1, "mp4"); + continue; } - } else if (suffix.equals(".txt")) { + if (suffix.equals(".mp4")) + paragraph5.appendOleObject(stream1, pic1, "mp4"); + continue; + } + if (suffix.equals(".txt")) { pic1.loadImage("../doccenter/com.awspaas.user.apps.coe.pal.output.zd/filepic/txt.png"); - paragraph5.appendText(dcContextModel.getFileName()+" "); + paragraph5.appendText(dcContextModel.getFileName() + " "); paragraph5.appendOleObject(stream1, pic1, "txt"); } - - } } - } - doc.saveToFile(filePath, FileFormat.Docx_2013); } - /** - * 将文件的扩展属性设置默认值为空字符串(防止没有设置扩展属性而使得导出文件出错) - * - * @param methodScope - * @param dataMap - */ public static void setRepositoryDefaultValue(String methodScope, JSONObject dataMap) { - List attributes = new ArrayList(); + List attributes = new ArrayList<>(); String[] methodIds = methodScope.split(","); for (String methodId : methodIds) { PALMethodModel palMethodModel = PALMethodCache.getPALMethodModelById(methodId); - if (palMethodModel != null) { + if (palMethodModel != null) attributes.addAll(palMethodModel.getAttributes()); - } } - - if (attributes != null) { + if (attributes != null) for (PALMethodAttributeModel attribute : attributes) { String scope = attribute.getScope(); - if (scope.indexOf("%") > -1) { + if (scope.indexOf("%") > -1) dataMap.put("pl_" + attribute.getKey(), ""); - } } - } } - /** - * 将文件的扩展属性设置默认值为空字符串(防止没有设置扩展属性而使得导出文件出错) - * com.alibaba.fastjson - * - * @param methodScope - * @param dataMap - */ public static void setRepositoryDefaultValue2(String methodScope, JSONObject dataMap) { - List attributes = new ArrayList(); + List attributes = new ArrayList<>(); String[] methodIds = methodScope.split(","); for (String methodId : methodIds) { PALMethodModel palMethodModel = PALMethodCache.getPALMethodModelById(methodId); - if (palMethodModel != null) { + if (palMethodModel != null) attributes.addAll(palMethodModel.getAttributes()); - } } - - if (attributes != null) { + if (attributes != null) for (PALMethodAttributeModel attribute : attributes) { String scope = attribute.getScope(); - if (scope.indexOf("%") > -1) { + if (scope.indexOf("%") > -1) dataMap.put("pl_" + attribute.getKey(), ""); - } } - } } - /** - * 将文件中图形元素的扩展属性默认值设为空字符串(防止没有设置扩展属性而使得导出文件出错) - * - * @param repositoryId - * @param _tr - */ public static void setShapeDefaultValue(String repositoryId, JSONObject _tr) { - List attributes = new ArrayList(); - PALRepositoryModel repositoryModel = PALRepositoryCache.getCache().get(repositoryId); + List attributes = new ArrayList<>(); + PALRepositoryModel repositoryModel = (PALRepositoryModel)PALRepositoryCache.getCache().get(repositoryId); String methodId = repositoryModel.getMethodId(); if ("control".equals(methodId.substring(0, methodId.indexOf(".")))) { PALMethodModel palMethodModel_kpi = PALMethodCache.getPALMethodModelById("control.kpi"); @@ -1885,32 +1628,23 @@ public class OutputWordUtil { PALMethodModel palMethodModel = PALMethodCache.getPALMethodModelById(repositoryModel.getMethodId()); attributes.addAll(palMethodModel.getAttributes()); } - - _tr.put(OutputWordUtil.SHAPE_NUMBER, ""); - _tr.put(OutputWordUtil.SHAPE_NAME, ""); - if (attributes != null) { + _tr.put("shape_number", ""); + _tr.put("shape_name", ""); + if (attributes != null) for (PALMethodAttributeModel attribute : attributes) { String scope = attribute.getScope(); - if (!"%".equals(scope)) { + if (!"%".equals(scope)) _tr.put("shape_" + attribute.getKey(), ""); - } if ("organization".equals(attribute.getGroupPath())) { _tr.put("shape_" + attribute.getKey() + "_org", ""); _tr.put("shape_" + attribute.getKey() + "_role", ""); } } - } } - /** - * 将文件中图形元素的扩展属性默认值设为空字符串(防止没有设置扩展属性而使得导出文件出错) - * - * @param repositoryId - * @param _tr - */ public static void setShapeDefaultValue2(String repositoryId, JSONObject _tr) { - List attributes = new ArrayList(); - PALRepositoryModel repositoryModel = PALRepositoryCache.getCache().get(repositoryId); + List attributes = new ArrayList<>(); + PALRepositoryModel repositoryModel = (PALRepositoryModel)PALRepositoryCache.getCache().get(repositoryId); String methodId = repositoryModel.getMethodId(); if ("control".equals(methodId.substring(0, methodId.indexOf(".")))) { PALMethodModel palMethodModel_kpi = PALMethodCache.getPALMethodModelById("control.kpi"); @@ -1923,326 +1657,239 @@ public class OutputWordUtil { PALMethodModel palMethodModel = PALMethodCache.getPALMethodModelById(repositoryModel.getMethodId()); attributes.addAll(palMethodModel.getAttributes()); } - - _tr.put(OutputWordUtil.SHAPE_NUMBER, ""); - _tr.put(OutputWordUtil.SHAPE_NAME, ""); - if (attributes != null) { + _tr.put("shape_number", ""); + _tr.put("shape_name", ""); + if (attributes != null) for (PALMethodAttributeModel attribute : attributes) { String scope = attribute.getScope(); - if (!"%".equals(scope)) { + if (!"%".equals(scope)) _tr.put("shape_" + attribute.getKey(), ""); - } if ("organization".equals(attribute.getGroupPath())) { _tr.put("shape_" + attribute.getKey() + "_org", ""); _tr.put("shape_" + attribute.getKey() + "_role", ""); } } - } } - /** - * 字符串去重(Set本身有去重功能) - * - * @param str 要去重的字符串 - * @param separator 分隔符 - * @return - */ public static String removeRepeat(String str, String separator) { Set set = string2set(str, separator); return set2string(set); } public static Set string2set(String str, String separator) { - Set set = new LinkedHashSet(); + Set set = new LinkedHashSet<>(); if (str != null && !"".equals(str)) { String[] array = str.split(separator); - for (String string : array) { + for (String string : array) set.add(string); - } } return set; } public static String set2string(Set set) { StringBuilder result = new StringBuilder(); - if (set.size() > 0) { + if (set.size() > 0) for (Iterator it = set.iterator(); it.hasNext(); ) { result.append(it.next()); result.append(","); } - } - - if (result.indexOf(",") != -1) { + if (result.indexOf(",") != -1) return result.substring(0, result.length() - 1); - } else { - return result.toString(); - } + return result.toString(); } - /** - * 如果图形元素属性中有关联的图形,获取关联的流程文件的数据Table - * - * @param table - * @param relationShapeIds - */ @Deprecated public static void setTableValue(JSONArray table, String relationShapeIds) { relationShapeIds = relationShapeIds.replace("[", "").replace("]", "").replace("\"", ""); String[] relationShapeIdArray = relationShapeIds.split(","); - List relationModelList = new ArrayList(); + List relationModelList = new ArrayList<>(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); for (String relationShapeId : relationShapeIdArray) { - if (UtilString.isEmpty(relationShapeId)) { - continue; - } - List relationModels = dao.query(null, null, null, null, relationShapeId); - if (relationModels != null && relationModels.size() > 0) { - relationModelList.addAll(relationModels); + if (!UtilString.isEmpty(relationShapeId)) { + List relationModels = dao.query(null, null, null, null, relationShapeId); + if (relationModels != null && relationModels.size() > 0) + relationModelList.addAll(relationModels); } } - if (relationModelList != null && relationModelList.size() > 0) { int index = 1; for (DesignerShapeRelationModel repositoryShape : relationModelList) { String relationFileId = repositoryShape.getRelationFileId(); - if (relationFileId == null || "".equals(relationFileId)) { + if (relationFileId == null || "".equals(relationFileId)) continue; - } - List> relationFileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); // 关联流程文件内容 - if (relationFileElements == null || relationFileElements.size() == 0) { + List> relationFileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); + if (relationFileElements == null || relationFileElements.size() == 0) continue; - } - for (Map element : relationFileElements) { - String id = (String) element.get("id"); + String id = (String)element.get("id"); if (relationShapeIds.indexOf(id) != -1) { JSONObject _tr = new JSONObject(); - OutputWordUtil.setShapeDefaultValue(repositoryShape.getRelationFileId(), _tr); + setShapeDefaultValue(repositoryShape.getRelationFileId(), _tr); String name = element.get("text").toString(); - _tr.put(OutputWordUtil.SHAPE_NAME, name.replace("\n", OutputWordUtil.WRAPSTRING)); - _tr.put(OutputWordUtil.SERIAL_NUMBER, index); - - JSONObject dataAttributes = (JSONObject) element.get("attributes"); + _tr.put("shape_name", name.replace("\n", "")); + _tr.put("serial_number", Integer.valueOf(index)); + JSONObject dataAttributes = (JSONObject)element.get("attributes"); if (dataAttributes != null) { JSONArray dataAttributesJsonArray = dataAttributes.getJSONArray("attributesJsonArray"); for (int i = 0; i < dataAttributesJsonArray.size(); i++) { JSONObject dataAttribute = dataAttributesJsonArray.getJSONObject(i); - if (dataAttribute == null || "null".equals(dataAttribute.toString())) { - continue; //跳过dataAttributesJsonArray中的空 - } - if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) { - _tr.put("shape_" + dataAttribute.getString("key"), dataAttribute.getString("value")); - } + if (dataAttribute != null && !"null".equals(dataAttribute.toString())) + if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) + _tr.put("shape_" + dataAttribute.getString("key"), dataAttribute.getString("value")); } if (dataAttributes.containsKey("privateAttributeContent")) { String privateAttributeContentStr = dataAttributes.get("privateAttributeContent").toString(); - //basic类型的privateAttributeContent属性为“[]”,其他类型模型的该属性为JSONObject格式 if (!"".equals(privateAttributeContentStr) && !"[]".equals(privateAttributeContentStr)) { String firstChart = privateAttributeContentStr.substring(0, 1); if ("{".equals(firstChart)) { JSONObject privateAttributeContent = dataAttributes.getJSONObject("privateAttributeContent"); - for (String key : privateAttributeContent.keySet()) { + for (String key : privateAttributeContent.keySet()) _tr.put("shape_" + key, privateAttributeContent.getString(key)); - } - // Iterator it = privateAttributeContent.keys(); - // while (it.hasNext()) { - // String key = (String) it.next(); - // _tr.put("shape_" + key, privateAttributeContent.getString(key)); - // } } } } } - table.add(_tr); index++; relationShapeIds = relationShapeIds.replace(id, ""); } } } - } } - /** - * 如果图形元素属性中有关联的图形,获取关联的流程文件的数据Table - * com.alibaba.fastjson - * - * @param repositoryId - * @param table - * @param relationShapeIds - */ @Deprecated public static void setTableValue2(String repositoryId, JSONArray table, String relationShapeIds) { - // 记录关联属性的流程节点,防止多次查询重复文件信息耗费时间 Set relationFileIds = new HashSet<>(); - List> relationFileElements2 = new ArrayList>(); - + List> relationFileElements2 = new ArrayList<>(); relationShapeIds = relationShapeIds.replace("[", "").replace("]", "").replace("\"", ""); if (!"".equals(relationShapeIds)) { String[] relationShapeIdArray = relationShapeIds.split(","); - Set relationShapeIdSet = new HashSet<>(Arrays.asList(relationShapeIdArray)); // 去重 + Set relationShapeIdSet = new HashSet<>(Arrays.asList(relationShapeIdArray)); Set fileIdSet = new HashSet<>(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); for (String relationShapeId : relationShapeIdSet) { List relationModels = dao.query(repositoryId, null, null, null, relationShapeId); - if (relationModels != null && relationModels.size() > 0) { + if (relationModels != null && relationModels.size() > 0) for (int i = 0; i < relationModels.size(); i++) { - String relationFileId = relationModels.get(i).getRelationFileId(); - if (relationFileId == null || "".equals(relationFileId)) { - continue; - } - if (!fileIdSet.contains(relationFileId)) { - fileIdSet.add(relationFileId); - } + String relationFileId = ((DesignerShapeRelationModel)relationModels.get(i)).getRelationFileId(); + if (relationFileId != null && !"".equals(relationFileId)) + if (!fileIdSet.contains(relationFileId)) + fileIdSet.add(relationFileId); } - } } - - if (fileIdSet.size() > 0) { + if (fileIdSet.size() > 0) for (String fileId : fileIdSet) { - if (relationFileIds.contains(fileId)) {// 该文件已查询过,不再重复查询 - - } else { - List> fileElements = CoeDesignerUtil.getShapeMessageJson2(fileId); // 关联流程文件内容 - if (fileElements != null && fileElements.size() > 0) { - relationFileIds.add(fileId); - relationFileElements2.addAll(fileElements); - } + if (relationFileIds.contains(fileId)) + continue; + List> fileElements = CoeDesignerUtil.getShapeMessageJson2(fileId); + if (fileElements != null && fileElements.size() > 0) { + relationFileIds.add(fileId); + relationFileElements2.addAll(fileElements); } } - } int index = 1; - for (String relationShapeId : relationShapeIdSet) { + label75: for (String relationShapeId : relationShapeIdSet) { for (Map element : relationFileElements2) { - String id = (String) element.get("id"); + String id = (String)element.get("id"); if (relationShapeId.equals(id)) { JSONObject _tr = new JSONObject(); - OutputWordUtil.setShapeDefaultValue2((String) element.get("pid"), _tr); + setShapeDefaultValue2((String)element.get("pid"), _tr); String name = specialCharTransfer(element.get("text").toString()); - _tr.put(OutputWordUtil.SHAPE_NAME, name.replace("\n", OutputWordUtil.WRAPSTRING)); - _tr.put(OutputWordUtil.SERIAL_NUMBER, index); - - JSONObject dataAttributes = (JSONObject) element.get("attributes"); + _tr.put("shape_name", name.replace("\n", "")); + _tr.put("serial_number", Integer.valueOf(index)); + JSONObject dataAttributes = (JSONObject)element.get("attributes"); if (dataAttributes != null) { JSONArray dataAttributesJsonArray = dataAttributes.getJSONArray("attributesJsonArray"); for (int i = 0; i < dataAttributesJsonArray.size(); i++) { JSONObject dataAttribute = dataAttributesJsonArray.getJSONObject(i); - if (dataAttribute == null || "null".equals(dataAttribute.toString())) { - continue; - } - if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) { - _tr.put("shape_" + dataAttribute.getString("key"), specialCharTransfer(dataAttribute.getString("value"))); - } + if (dataAttribute != null && !"null".equals(dataAttribute.toString())) + if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) + _tr.put("shape_" + dataAttribute.getString("key"), specialCharTransfer(dataAttribute.getString("value"))); } if (dataAttributes.containsKey("privateAttributeContent")) { String privateAttributeContentStr = dataAttributes.get("privateAttributeContent").toString(); - if (!"".equals(privateAttributeContentStr) && !"[]".equals(privateAttributeContentStr)) { - String firstChart = privateAttributeContentStr.substring(0, 1); - if ("{".equals(firstChart)) { - JSONObject privateAttributeContent = dataAttributes.getJSONObject("privateAttributeContent"); - for (String key : privateAttributeContent.keySet()) { - _tr.put("shape_" + key, specialCharTransfer(privateAttributeContent.getString(key))); + if (!"".equals(privateAttributeContentStr)) { + if (!"[]".equals(privateAttributeContentStr)) { + String firstChart = privateAttributeContentStr.substring(0, 1); + if ("{".equals(firstChart)) { + JSONObject privateAttributeContent = dataAttributes.getJSONObject("privateAttributeContent"); + for (String key : privateAttributeContent.keySet()) + _tr.put("shape_" + key, specialCharTransfer(privateAttributeContent.getString(key))); + continue label75; } + continue label75; } + continue label75; } + continue label75; } + continue label75; } - table.add(_tr); index++; - break; } } } } - } - /** - * 获取一行数据信息(包括扩展属性) - * - * @param _tr - * @param shapeIds - * @param key - */ @Deprecated public static void setTrValue(JSONObject _tr, String shapeIds, String key, Map shapeModelMap) { shapeIds = shapeIds.replace("[", "").replace("]", "").replace("\"", ""); shapeIds = removeRepeat(shapeIds, ","); String[] shapeIdArray = shapeIds.split(","); - List relationModelList = new ArrayList(); + List relationModelList = new ArrayList<>(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); for (String shapeId : shapeIdArray) { List relationModels = dao.query(null, null, null, null, shapeId); - if (relationModels != null && relationModels.size() > 0) { + if (relationModels != null && relationModels.size() > 0) relationModelList.addAll(relationModels); - } } - StringBuffer sbOrg = new StringBuffer(""); StringBuffer sbRole = new StringBuffer(""); - - if (relationModelList != null && relationModelList.size() > 0) { + if (relationModelList != null && relationModelList.size() > 0) for (DesignerShapeRelationModel repositoryShape : relationModelList) { - if (!shapeModelMap.containsKey(repositoryShape.getRelationShapeId())) { + if (!shapeModelMap.containsKey(repositoryShape.getRelationShapeId())) continue; - } - String relationFileId = repositoryShape.getRelationFileId(); - List> relationFileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); // 关联流程文件内容 - if (relationFileElements != null) { + List> relationFileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); + if (relationFileElements != null) for (Map element : relationFileElements) { - String id = (String) element.get("id"); + String id = (String)element.get("id"); if (shapeIds.indexOf(id) != -1) { String type = element.get("type").toString(); if ("organization".equals(type)) { - sbOrg.append(element.get("text").toString().replace("\n", OutputWordUtil.WRAPSTRING)); + sbOrg.append(element.get("text").toString().replace("\n", "")); sbOrg.append(","); } else if ("position".equals(type) || "role".equals(type)) { - sbRole.append(element.get("text").toString().replace("\n", OutputWordUtil.WRAPSTRING)); + sbRole.append(element.get("text").toString().replace("\n", "")); sbRole.append(","); } - - JSONObject dataAttributes = (JSONObject) element.get("attributes"); + JSONObject dataAttributes = (JSONObject)element.get("attributes"); if (dataAttributes != null) { JSONArray dataAttributesJsonArray = dataAttributes.getJSONArray("attributesJsonArray"); for (int i = 0; i < dataAttributesJsonArray.size(); i++) { JSONObject dataAttribute = dataAttributesJsonArray.getJSONObject(i); - if (dataAttribute == null || "null".equals(dataAttribute.toString())) { - continue; - } - if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) { - _tr.put("shape_" + dataAttribute.getString("key"), dataAttribute.getString("value")); - } + if (dataAttribute != null && !"null".equals(dataAttribute.toString())) + if (dataAttribute.containsKey("key") && dataAttribute.containsKey("value")) + _tr.put("shape_" + dataAttribute.getString("key"), dataAttribute.getString("value")); } } shapeIds = shapeIds.replace(id, ""); } } - } } - - } String sbOrgString = sbOrg.toString(); - if (sbOrgString.lastIndexOf(",") > 0) { + if (sbOrgString.lastIndexOf(",") > 0) sbOrgString = sbOrgString.substring(0, sbOrgString.length() - 1); - } String sbRoleString = sbRole.toString(); - if (sbRoleString.lastIndexOf(",") > 0) { + if (sbRoleString.lastIndexOf(",") > 0) sbRoleString = sbRoleString.substring(0, sbRoleString.length() - 1); - } _tr.put(key + "_org", sbOrgString); _tr.put(key + "_role", sbRoleString); } - /** - * 获取一行地址簿相关的数据信息 - * - * @param _tr - * @param shapeIds - * @param key - */ @Deprecated public static void setTrAwsOrgValue(JSONObject _tr, String shapeIds, String key, Map shapeModelMap) { shapeIds = shapeIds.replace("[", "").replace("]", "").replace("\"", ""); @@ -2255,108 +1902,72 @@ public class OutputWordUtil { String text = shapeModelMap.get(keyId); JSONObject object = JSONObject.parseObject(text); String type = object.getString("type"); - if ("department".equals(type)) {// 部门 + if ("department".equals(type)) { DepartmentModel deptModel = SDK.getORGAPI().getDepartmentById(keyId); - if (deptModel != null) { + if (deptModel != null) sbOrg.append(specialCharTransfer(deptModel.getName())).append(","); - } } - if ("user".equals(type)) {// 人员 + if ("user".equals(type)) { UserModel userModel = SDK.getORGAPI().getUser(keyId); - if (userModel != null) { + if (userModel != null) sbOrg.append(specialCharTransfer(userModel.getUserName())).append(","); - } } - if ("role".equals(type)) {// 角色 + if ("role".equals(type)) { RoleModel roleModel = SDK.getORGAPI().getRoleById(keyId); - if (roleModel != null) { + if (roleModel != null) sbRole.append(specialCharTransfer(roleModel.getName())).append(","); - } } } } String sbOrgString = sbOrg.toString(); - if (sbOrgString.lastIndexOf(",") > 0) { + if (sbOrgString.lastIndexOf(",") > 0) sbOrgString = sbOrgString.substring(0, sbOrgString.length() - 1); - } String sbRoleString = sbRole.toString(); - if (sbRoleString.lastIndexOf(",") > 0) { + if (sbRoleString.lastIndexOf(",") > 0) sbRoleString = sbRoleString.substring(0, sbRoleString.length() - 1); - } _tr.put(key + "_org", sbOrgString); _tr.put(key + "_role", sbRoleString); } - /** - * 获取图形实例的关联Model Map - * - * @param shapeId - * @return - */ @Deprecated public static Map getShapeRelationMap(String shapeId) { - Map relationMap = new HashMap(); + Map relationMap = new HashMap<>(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); List relationModels = dao.query(null, shapeId, null, null, null); - if (relationModels != null && relationModels.size() > 0) { - for (DesignerShapeRelationModel model : relationModels) { + if (relationModels != null && relationModels.size() > 0) + for (DesignerShapeRelationModel model : relationModels) relationMap.put(model.getRelationShapeId(), model.getRelationShapeText()); - } - } return relationMap; } - /** - * 获取图形实例的关联Model Map - * - * @param shapeId - * @return - */ @Deprecated public static Map getShapeRelationMap(String fileId, String shapeId) { - Map relationMap = new HashMap(); + Map relationMap = new HashMap<>(); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); List relationModels = dao.query(fileId, shapeId, null, null, null); - if (relationModels != null && relationModels.size() > 0) { + if (relationModels != null && relationModels.size() > 0) for (DesignerShapeRelationModel model : relationModels) { if ("00000000-0000-0000-0000-000000000000".equals(model.getRelationFileId()) && "00000000-0000-0000-0000-000000000000".equals(model.getRelationShapeId())) { String text = model.getRelationShapeText(); relationMap.put(JSONObject.parseObject(text).getString("id"), text); - } else { - relationMap.put(model.getRelationShapeId(), model.getRelationShapeText()); + continue; } + relationMap.put(model.getRelationShapeId(), model.getRelationShapeText()); } - } return relationMap; } - /** - * 获取图形实例的关联Model Map - * - * @param fileId - * @param shapeId - * @return - */ public static Map> getShapeRelationAttrMap(String fileId, String shapeId) { - List list = new DesignerShapeRelationDao().query(fileId, shapeId, null, null, null); + List list = (new DesignerShapeRelationDao()).query(fileId, shapeId, null, null, null); Map> map = new HashMap<>(); for (DesignerShapeRelationModel model : list) { - if (!map.containsKey(model.getAttrId())) { - map.put(model.getAttrId(), new ArrayList()); - } - map.get(model.getAttrId()).add(model); + if (!map.containsKey(model.getAttrId())) + map.put(model.getAttrId(), new ArrayList<>()); + ((List)map.get(model.getAttrId())).add(model); } return map; } - /** - * 将图形元素关联属性的id替换为name - * - * @param key - * @param dataAttribute 图形元素所有关联属性 - * @param shapeRelationModelMap - * @return - */ @Deprecated public static void setShapeValue(JSONObject _tr, JSONObject dataAttribute, Map shapeRelationModelMap) { String result = ""; @@ -2365,46 +1976,28 @@ public class OutputWordUtil { result = dataAttribute.getString("value"); } else { StringBuilder keyValue = new StringBuilder(); - List keyValueList = new ArrayList(); + List keyValueList = new ArrayList<>(); if (key != null) { String attributeValue = dataAttribute.getString("value"); if (attributeValue != null && attributeValue.length() != 0) { attributeValue = attributeValue.replace("[", "").replace("]", "").replace("\"", ""); String[] keyValues = removeRepeat(attributeValue, ",").split(","); for (String keyId : keyValues) { - if (!"".equals(keyId) && shapeRelationModelMap.containsKey(keyId)) { + if (!"".equals(keyId) && shapeRelationModelMap.containsKey(keyId)) keyValueList.add(shapeRelationModelMap.get(keyId)); - } } - for (String value : keyValueList) { + for (String value : keyValueList) keyValue.append(value + ","); - } - - if (keyValue.length() > 0) { + if (keyValue.length() > 0) result = keyValue.toString().substring(0, keyValue.length() - 1); - } } } } - - _tr.put("shape_" + key, result.replace("\n", OutputWordUtil.WRAPSTRING)); + _tr.put("shape_" + key, result.replace("\n", "")); } - /** - * 查询横版特殊信息 - *

- * 查询部门、岗位、角色 - *

- * 部门、岗位、角色的区分依据在相应的流程源文件,需要查找源文件 - * - * @param _tr - * @param dataAttribute - * @param shapeModelMap - * @param relationFileElements - */ @Deprecated - public static void setRelationShapeValueByOrgAndRole(JSONObject _tr, JSONObject dataAttribute, - Map shapeModelMap, List> relationFileElements, String shapeId, Set relationFileIds) { + public static void setRelationShapeValueByOrgAndRole(JSONObject _tr, JSONObject dataAttribute, Map shapeModelMap, List> relationFileElements, String shapeId, Set relationFileIds) { String key = dataAttribute.getString("key"); if ("organization".equals(dataAttribute.getString("groupPath")) && "relation".equals(dataAttribute.getString("type"))) { String relationShapeIds = dataAttribute.getString("value"); @@ -2413,73 +2006,61 @@ public class OutputWordUtil { String[] relationShapeIdArr = relationShapeIds.split(","); DesignerShapeRelationDao dao = new DesignerShapeRelationDao(); for (String str : relationShapeIdArr) { - if (!shapeModelMap.containsKey(str)) { - continue; - } - List relationModels = dao.query(null, shapeId, key, null, str); - if (relationModels != null && relationModels.size() > 0) { - for (DesignerShapeRelationModel model : relationModels) { - String relationFileId = model.getRelationFileId(); - boolean flag = false; - if (relationFileIds.contains(relationFileId)) {// 包含该关联文件内容,不再查询 - flag = true; - } else {// 不包含该文件,查询 - List> FileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); // 关联流程文件内容 - if (FileElements != null) { - relationFileIds.add(relationFileId); - relationFileElements.addAll(FileElements); + if (shapeModelMap.containsKey(str)) { + List relationModels = dao.query(null, shapeId, key, null, str); + if (relationModels != null && relationModels.size() > 0) + for (DesignerShapeRelationModel model : relationModels) { + String relationFileId = model.getRelationFileId(); + boolean flag = false; + if (relationFileIds.contains(relationFileId)) { flag = true; - } - } - if (flag) { - StringBuilder sbOrg = new StringBuilder(_tr.getString("shape_" + key + "_org")); - StringBuilder sbRole = new StringBuilder(_tr.getString("shape_" + key + "_role")); - - for (Map element : relationFileElements) { - String id = (String) element.get("id"); - if (relationShapeIds.indexOf(id) != -1 && id.equals(str)) { - String type = element.get("type").toString(); - if ("organization".equals(type)) { - sbOrg.append(","); - sbOrg.append(element.get("text").toString().replace("\n", "")); - } else if ("position".equals(type) || "role".equals(type)) { - sbRole.append(","); - sbRole.append(element.get("text").toString().replace("\n", "")); - } + } else { + List> FileElements = CoeDesignerUtil.getShapeMessageJson2(relationFileId); + if (FileElements != null) { + relationFileIds.add(relationFileId); + relationFileElements.addAll(FileElements); + flag = true; } } - String sbOrgString = specialCharTransfer(sbOrg.toString()); - if (sbOrgString.indexOf(",") == 0) { - sbOrgString = sbOrgString.substring(1, sbOrgString.length()); + if (flag) { + StringBuilder sbOrg = new StringBuilder(_tr.getString("shape_" + key + "_org")); + StringBuilder sbRole = new StringBuilder(_tr.getString("shape_" + key + "_role")); + for (Map element : relationFileElements) { + String id = (String)element.get("id"); + if (relationShapeIds.indexOf(id) != -1 && id.equals(str)) { + String type = element.get("type").toString(); + if ("organization".equals(type)) { + sbOrg.append(","); + sbOrg.append(element.get("text").toString().replace("\n", "")); + continue; + } + if ("position".equals(type) || "role".equals(type)) { + sbRole.append(","); + sbRole.append(element.get("text").toString().replace("\n", "")); + } + } + } + String sbOrgString = specialCharTransfer(sbOrg.toString()); + if (sbOrgString.indexOf(",") == 0) + sbOrgString = sbOrgString.substring(1, sbOrgString.length()); + String sbRoleString = specialCharTransfer(sbRole.toString()); + if (sbRoleString.indexOf(",") == 0) + sbRoleString = sbRoleString.substring(1, sbRoleString.length()); + _tr.put("shape_" + key + "_org", sbOrgString); + _tr.put("shape_" + key + "_role", sbRoleString); } - String sbRoleString = specialCharTransfer(sbRole.toString()); - if (sbRoleString.indexOf(",") == 0) { - sbRoleString = sbRoleString.substring(1, sbRoleString.length()); - } - _tr.put("shape_" + key + "_org", sbOrgString); - _tr.put("shape_" + key + "_role", sbRoleString); } - } } } } } - /** - * 将图形元素关联属性的id替换为name - * com.alibaba.fastjson - * - * @param key - * @param dataAttribute 图形元素所有关联属性 - * @param shapeRelationModelMap - * @return - */ @Deprecated public static void setShapeValue2(JSONObject _tr, JSONObject dataAttribute, Map shapeRelationModelMap) { String result = ""; String key = dataAttribute.getString("key"); if ("string".equals(dataAttribute.getString("type")) || "textarea".equals(dataAttribute.getString("type"))) { - result = specialCharTransfer(dataAttribute.getString("value")).replace("\n", OutputWordUtil.WRAPSTRING); + result = specialCharTransfer(dataAttribute.getString("value")).replace("\n", ""); } else if ("awsorg".equals(dataAttribute.getString("type"))) { StringBuilder keyValue = new StringBuilder(); if (key != null) { @@ -2492,121 +2073,97 @@ public class OutputWordUtil { String text = shapeRelationModelMap.get(keyId); JSONObject object = JSONObject.parseObject(text); String type = object.getString("type"); - if ("department".equals(type)) {// 部门 + if ("department".equals(type)) { DepartmentModel deptModel = SDK.getORGAPI().getDepartmentById(keyId); - if (deptModel != null) { + if (deptModel != null) keyValue.append(specialCharTransfer(deptModel.getName())).append(","); - } } - if ("user".equals(type)) {// 人员 + if ("user".equals(type)) { UserModel userModel = SDK.getORGAPI().getUser(keyId); - if (userModel != null) { + if (userModel != null) keyValue.append(specialCharTransfer(userModel.getUserName())).append(","); - } } - if ("role".equals(type)) {// 角色 + if ("role".equals(type)) { RoleModel roleModel = SDK.getORGAPI().getRoleById(keyId); - if (roleModel != null) { + if (roleModel != null) keyValue.append(specialCharTransfer(roleModel.getName())).append(","); - } } } } } } - if (keyValue.length() > 0) { + if (keyValue.length() > 0) result = keyValue.toString().substring(0, keyValue.length() - 1); - } } else if ("select".equals(dataAttribute.getString("type"))) { result = specialCharTransfer(dataAttribute.getString("value")); } else { StringBuilder keyValue = new StringBuilder(); - List keyValueList = new ArrayList(); + List keyValueList = new ArrayList<>(); if (key != null) { String attributeValue = dataAttribute.getString("value"); if (attributeValue != null && attributeValue.length() != 0) { attributeValue = attributeValue.replace("[", "").replace("]", "").replace("\"", ""); String[] keyValues = removeRepeat(attributeValue, ",").split(","); for (String keyId : keyValues) { - if (!"".equals(keyId) && shapeRelationModelMap.containsKey(keyId)) { + if (!"".equals(keyId) && shapeRelationModelMap.containsKey(keyId)) keyValueList.add(shapeRelationModelMap.get(keyId)); - } } for (String value : keyValueList) { value = specialCharTransfer(value); keyValue.append(value + ","); } - - if (keyValue.length() > 0) { + if (keyValue.length() > 0) result = keyValue.toString().substring(0, keyValue.length() - 1); - } } } } - - _tr.put("shape_" + key, result.replace("\n", OutputWordUtil.WRAPSTRING)); + _tr.put("shape_" + key, result.replace("\n", "")); } - /** - * 导出word时对特殊字符转义,防止office解析特殊字符打不开 - * 特殊字符"&" "<" ">" - * - * @param str - */ public static String specialCharTransfer(String str) { - if (str == null || "".equals(str.trim())) { + if (str == null || "".equals(str.trim())) return str; - } return str.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); } - //排序 private static class ComparatorMap implements Comparator> { - @Override - public int compare(Map json1, Map json2) { - String number1 = getNum(json1); - String number2 = getNum(json2); - if (!OutputUtil.isPositiveInteger(number1) || !OutputUtil.isPositiveInteger(number2)) { - return number1.compareTo(number2); - } else { - Integer n1 = 0; - Integer n2 = 0; - n1 = Integer.parseInt(number1); - n2 = Integer.parseInt(number2); - return n1.compareTo(n2); - } - } + private ComparatorMap() {} + public int compare(Map json1, Map json2) { + String number1 = OutputWordUtil.getNum(json1); + String number2 = OutputWordUtil.getNum(json2); + if (!OutputUtil.isPositiveInteger(number1) || !OutputUtil.isPositiveInteger(number2)) + return number1.compareTo(number2); + Integer n1 = Integer.valueOf(0); + Integer n2 = Integer.valueOf(0); + n1 = Integer.valueOf(Integer.parseInt(number1)); + n2 = Integer.valueOf(Integer.parseInt(number2)); + return n1.compareTo(n2); + } } private static String getNum(Map json) { - if (json.containsKey("number")) { + if (json.containsKey("number")) return json.get("number").toString(); - } if (json.containsKey("attributes")) { - if (json.get("attributes") instanceof JSONObject) {// netJson - JSONObject dataJson = (JSONObject) json.get("attributes"); - if (dataJson.containsKey("privateAttributeContent") && dataJson.get("privateAttributeContent").getClass().getName().contains("JSONObject")) { + if (json.get("attributes") instanceof JSONObject) { + JSONObject dataJson = (JSONObject)json.get("attributes"); + if (dataJson.containsKey("privateAttributeContent") && dataJson.get("privateAttributeContent").getClass().getName().contains("JSONObject")) return dataJson.getJSONObject("privateAttributeContent").getString("number"); - } } - if (json.get("attributes") instanceof JSONObject) {// fastJson - JSONObject dataJson = (JSONObject) json.get("attributes"); - if (dataJson.containsKey("privateAttributeContent") && dataJson.get("privateAttributeContent").getClass().getName().contains("JSONObject")) { + if (json.get("attributes") instanceof JSONObject) { + JSONObject dataJson = (JSONObject)json.get("attributes"); + if (dataJson.containsKey("privateAttributeContent") && dataJson.get("privateAttributeContent").getClass().getName().contains("JSONObject")) return dataJson.getJSONObject("privateAttributeContent").getString("number"); - } } if (json.get("attributes") instanceof JSONArray) { - JSONArray dataJson = (JSONArray) json.get("attributes"); + JSONArray dataJson = (JSONArray)json.get("attributes"); for (int i = 0; i < dataJson.size(); i++) { - JSONObject obj = (JSONObject) dataJson.get(i); - if ("number".equals(obj.getString("key"))) { + JSONObject obj = (JSONObject)dataJson.get(i); + if ("number".equals(obj.getString("key"))) return obj.getString("value"); - } - //加入活动序号排序处理 - if (obj.getString("key") != null && obj.getString("key").contains("number")) { + if (obj.getString("key") != null && obj.getString("key").contains("number")) return obj.getString("value"); - } } } } @@ -2615,17 +2172,11 @@ public class OutputWordUtil { public static void orderByNumber(List> list) { ComparatorMap comparator = new ComparatorMap(); - - if (list != null && list.size() > 0) { + if (list != null && list.size() > 0) Collections.sort(list, comparator); - } } - - - - public static JSONArray getVersionHistoryTable(PALRepositoryModel repositoryModel) { JSONArray versionHistoryTable = new JSONArray();// 修订记录 List list = PALRepositoryCache.getByVersionId(repositoryModel.getVersionId()); @@ -2692,153 +2243,111 @@ public class OutputWordUtil { return versionHistoryTable; } - /** - * xml转换成word(找doc文件,执行转换) - * @param log - * @param fileDirPath - */ + public static void xml2Word(GenerLogExd log, String fileDirPath) { File dir = new File(fileDirPath); if (dir.exists() && dir.isDirectory()) { - File [] files = dir.listFiles(); + File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; - if (file.isFile() && file.getName().toLowerCase().endsWith(".doc")) { + if (file.isFile() && file.getName().toLowerCase().endsWith(".doc")) xml2Word(log, fileDirPath, file.getName()); - } } } } - /** - * xml转换成word - * @param filePath - * @param fileName - */ public static void xml2Word(GenerLogExd log, String filePath, String fileName) { - boolean record = log != null; + boolean record = (log != null); File file = new File(filePath, fileName); if (file.exists() && isXML(file.getPath())) { Document document = new Document(); document.loadFromFile(file.getPath()); document.saveToFile(file.getPath(), FileFormat.Doc); - if (record) { + if (record) log.info("文件从XML格式转换成Doc格式"); - } - } else { - if (record) { - log.info("文件不存在或者文件不是XML格式,无需转换成Doc格式"); - } + } else if (record) { + log.info("文件不存在或者文件不是XML格式,无需转换成Doc格式"); } } public static boolean isXML(String filePath) { try (FileInputStream fis = new FileInputStream(filePath)) { - byte[] buffer = new byte[50]; // 假设我们读取前50个字节进行检测 + byte[] buffer = new byte[50]; int bytesRead = fis.read(buffer); String startOfFile = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8); - - // 使用正则表达式来处理可能出现的前导空白字符 return startOfFile.trim().startsWith(" headers = WPS4Util.getSignatureHeaders(url, "POST",result.toString(), YiliWpsConst.CONTENT_TYPE); - JSONObject json = HttpPostUtil.sendPostRequest(YiliWpsConst.HOST + "/open" + url, result.toString(), headers, JSONObject.class); + Map headers = WPS4Util.getSignatureHeaders(url, "POST", result.toString(), "application/json"); + JSONObject json = (JSONObject)HttpPostUtil.sendPostRequest(YiliWpsConst.HOST + "/open" + url, result.toString(), headers, JSONObject.class); System.out.println("jsonObject = " + json.toString()); - if(json.getString("code").equals("200")){ + if (json.getString("code").equals("200")) { System.out.println(">>>>>>>已合并成功"); String download_id = json.getJSONObject("data").getString("download_id"); String route_key = json.getJSONObject("data").getString("route_key"); - //String savePath = AWSPortalConf.getUrl() +"/test/123.doc"; - //patc和name中间不需要加"/"杠,兼容有斜杠的场景 - //String savePath = dc.getPath()+"/"+dc.getFileName(); String savePath = ""; - if(dc.getPath().endsWith("/")){ - savePath = dc.getPath()+dc.getFileName(); - }else{ - savePath = dc.getPath()+"/"+dc.getFileName(); + if (dc.getPath().endsWith("/")) { + savePath = dc.getPath() + dc.getFileName(); + } else { + savePath = dc.getPath() + "/" + dc.getFileName(); } System.out.println("savePath = " + savePath); - operateDocumentResultDownload(YiliWpsConst.HOST,download_id,route_key,savePath); + operateDocumentResultDownload(YiliWpsConst.HOST, download_id, route_key, savePath); return savePath; } return ""; - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); + return ""; } - return ""; } - /** - * 根据wps的下载id下载替换文件 - * @param host - * @param downloadId - * @param routeKey - * @param savePath - * @throws Exception - */ - public static void operateDocumentResultDownload(String host,String downloadId,String routeKey,String savePath) throws Exception { + public static void operateDocumentResultDownload(String host, String downloadId, String routeKey, String savePath) throws Exception { String url = "/api/cps/v1/download/{download_id}"; - url = url.replace("{download_id}",downloadId); - Map headers = WPS4Util.getSignatureHeaders(url, "GET",null,YiliWpsConst.CONTENT_TYPE); - headers.put("Route-Key",routeKey); - HttpPostUtil.sendGetDownloadRequest(host + "/open" + url, headers,savePath); + url = url.replace("{download_id}", downloadId); + Map headers = WPS4Util.getSignatureHeaders(url, "GET", null, "application/json"); + headers.put("Route-Key", routeKey); + HttpPostUtil.sendGetDownloadRequest(host + "/open" + url, headers, savePath); } - public static void downloadFile(String fileURL, String saveDir,String fileName) { + public static void downloadFile(String fileURL, String saveDir, String fileName) { try { File file = new File(saveDir); - - // 确保文件目录存在 - if (!file.exists()) { + if (!file.exists()) file.mkdirs(); - } - // 创建输出流到文件 File outputFile = new File(file, fileName); FileOutputStream fos = new FileOutputStream(outputFile); URL url = new URL(fileURL); - HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); + HttpURLConnection httpConn = (HttpURLConnection)url.openConnection(); int responseCode = httpConn.getResponseCode(); - // 检查响应码是否为HTTP_OK - if (responseCode == HttpURLConnection.HTTP_OK) { - // 通过输入流读取数据 + if (responseCode == 200) { InputStream inputStream = httpConn.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; - - while ((bytesRead = inputStream.read(buffer)) != -1) { + while ((bytesRead = inputStream.read(buffer)) != -1) fos.write(buffer, 0, bytesRead); - } - fos.close(); inputStream.close(); - System.out.println("File downloaded"); } else { System.out.println("No file to download. Server replied HTTP code: " + responseCode); @@ -2851,180 +2360,24 @@ public class OutputWordUtil { public static void sortFilesByNumber(List fileList) { fileList.sort( - Comparator.comparing( - OutputWordUtil::extractLeadingNumber, - Comparator.nullsLast(Comparator.naturalOrder()) - ) - ); + Comparator.comparing(OutputWordUtil::extractLeadingNumber, + + Comparator.nullsLast(Comparator.naturalOrder()))); } - // 提取附件后的第一个连续数字(支持小数) + private static Double extractLeadingNumber(UpfileModel file) { - Pattern FILE_NUMBER_PATTERN = - Pattern.compile("^附件[^\\d]*(\\d+(?:\\.\\d+)?|\\.\\d+)"); // 增强正则 + Pattern FILE_NUMBER_PATTERN = Pattern.compile("^附件[^\\d]*(\\d+(?:\\.\\d+)?|\\.\\d+)"); try { Matcher matcher = FILE_NUMBER_PATTERN.matcher(file.getFileName()); if (matcher.find()) { String numberStr = matcher.group(1); - // 处理结尾单独的小数点(如"123."的情况) - if (numberStr.endsWith(".")) { + if (numberStr.endsWith(".")) numberStr = numberStr.substring(0, numberStr.length() - 1); - } - return Double.parseDouble(numberStr); + return Double.valueOf(Double.parseDouble(numberStr)); } return null; } catch (Exception e) { return null; } } - - /** - * 判断是否需求合并管理要求 - * @param uuid - */ - public static void mergeMRWord(String filePath, String uuid) { - Map stringJSONObjectMap = PALRepositoryQueryAPIManager.queryRepositoryAttributeById(uuid); - JSONObject attrJson = stringJSONObjectMap.get("management_requirements_Location"); - String text = attrJson.getString("text"); - if ("不显示管理要求".equals(text)) { - return; - } - BO mrBO = SDK.getBOAPI().getByKeyField("BO_EU_PROCESS_MR", "FILEUUID", uuid); - if (null == mrBO || !"1".equals(mrBO.getString("STATUS"))) { - return; - } - - List systemfile = SDK.getBOAPI().getFiles(mrBO.getId(), "SYSTEMFILE"); - if (systemfile.isEmpty()) { - return; - } - FormFile formFile = systemfile.get(0); - DCContext fileDCContext = SDK.getBOAPI().getFileDCContext(formFile); - - // 加载目标文件和待合并文档2 - Document docs1 = new Document(); - docs1.loadFromFile(filePath); - Document docs2 = new Document(); - docs2.loadFromFile(fileDCContext.getFilePath()); - - // 定位插入位置:根据text判断是“流程图前”还是“活动说明后(表格后)” - Paragraph targetPara = null; - Section targetSection = null; - int targetParaIndex = -1; - if ("流程图前".equals(text)) { - // 保持原有“流程图前”逻辑(适配文件中“# 2. 流程图”) - for (Object obj : docs1.getSections()) { - Section sec = (Section) obj; - int i = 0; - for (Object parObj : sec.getParagraphs()) { - Paragraph para = (Paragraph) parObj; - if (para.getText().trim().contains("2. 流程图") || para.getText().trim().equals("流程图")) { - targetPara = para; - targetSection = sec; - targetParaIndex = i; - break; - } - i++; - } - if (targetPara != null) { - break; - } - } - } else if ("活动说明后".equals(text)) { - boolean foundProcessDesc = false; // 标记已找到“3. 流程说明”标题 - int lastTableParaIndex = -1; // 记录流程说明表格最后一行的索引 - for (Object obj : docs1.getSections()) { - Section sec = (Section) obj; - int i = 0; - for (Object paragraph : sec.getParagraphs()) { - Paragraph para = (Paragraph) paragraph; - String paraText = para.getText().trim(); - - // 修正1:匹配文件中实际的“3. 流程说明”标题(含#和数字) - if (paraText.contains("3. 流程说明") || paraText.contains("流程说明")) { - foundProcessDesc = true; - continue; - } - // 修正2:在“流程说明”后,持续追踪表格最后一行(含|符号) - if (foundProcessDesc) { - // 表格行含|(如“|01|线上审批55555|...”) - if (paraText.contains("|")) { - lastTableParaIndex = i; // 持续更新表格最后一行索引 - } else { - // 遇到非表格内容时,插入位置为表格最后一行的下一行 - if (lastTableParaIndex != -1) { - targetParaIndex = i; // 插入到当前非表格段落前(即表格下方) - targetPara = para; - targetSection = sec; - break; - } - } - } - i++; - } - - - if (targetPara != null) { - break; - } - } - } - - // 未找到目标位置则退出 - if (targetPara == null || targetSection == null) { - return; - } - - // 插入文档2内容(保持格式与文件协调) - Section doc2Sec = docs2.getSections().get(0); - boolean isFirstPara = true; - for (Object obj : doc2Sec.getParagraphs()) { - Paragraph doc2Para = (Paragraph) obj; - Paragraph clonedPara = (Paragraph) doc2Para.deepClone(); - ParagraphFormat format = clonedPara.getFormat(); - - // 核心格式:确保同页且不挤压 - format.setPageBreakBefore(false); - format.setPageBreakAfter(false); - format.setKeepLines(true); - format.setKeepFollow(true); - format.setLineSpacingRule(LineSpacingRule.At_Least); - format.setLineSpacing(12f); // 适配文件中行高 - - // 第一段与表格保持6磅间距(避免贴紧表格底部) - if (isFirstPara) { - float beforeSpacing = format.getBeforeSpacing(); - format.setBeforeSpacing(beforeSpacing > 0 ? beforeSpacing : 6f); - isFirstPara = false; - } - - // 插入到目标位置(表格下方) - targetSection.getParagraphs().insert(targetParaIndex, clonedPara); - } - - // 调整后续段落(如矩阵标题)与插入内容的间距 - ParagraphFormat targetFormat = targetPara.getFormat(); - targetFormat.setBeforeSpacing(6f); // 与插入内容保持6磅间距 - targetFormat.setPageBreakBefore(false); - - // 保存文档 - docs1.saveToFile(filePath, FileFormat.Docx_2013); - docs1.dispose(); - docs2.dispose(); - } - - // 新增:清除文档中的分页符(针对文档2) - private static void clearPageBreaks(Document doc) { - for (Object obj : doc.getSections()) { - Section section= (Section) obj; - // 遍历段落,移除手动分页符(假设分页符以特殊字符或元素存在) - for (Object obj1 : section.getParagraphs()) { - Paragraph para = (Paragraph) obj1; - String paraText = para.getText(); - if (paraText.contains("\f")) { - para.setText(paraText.replace("\f", "")); // 清除分页符字符 - } - } - - } - } }