当前位置:   article > 正文

(Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出

(Java)word转pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)导出

目录

1、引入jar包

2、pdf处理工具类

3、poi模板导出工具类

4、测试类

5、模板

6、最终效果 


1、引入jar包

 

2、pdf处理工具类

  1. import com.aspose.cells.PdfSaveOptions;
  2. import com.aspose.cells.Workbook;
  3. import com.aspose.words.Document; //引入aspose-words-21.5.0-jdk17包
  4. import com.aspose.words.*;
  5. import com.itextpdf.text.*;
  6. import com.itextpdf.text.pdf.*;
  7. import javax.swing.JLabel;
  8. import java.awt.FontMetrics;
  9. import java.io.*;
  10. import java.lang.reflect.Field;
  11. import java.lang.reflect.Modifier;
  12. import java.util.Arrays;
  13. public class PdfUtil {
  14. //水印字体透明度
  15. private static float opacity = 0.1f;
  16. //水印字体大小
  17. private static int fontsize = 20;
  18. //水印倾斜角度(0-360)
  19. private static int angle = 30;
  20. //数值越大每页竖向水印越少
  21. private static int heightDensity = 15;
  22. //数值越大每页横向水印越少
  23. private static int widthDensity = 2;
  24. private static final String[] WORD = {"doc", "docx", "wps", "wpt", "txt"};
  25. private static final String[] EXCEL = {"xls", "xlsx", "et", "xlsm"};
  26. private static final String[] PPT = {"ppt", "pptx"};
  27. /**
  28. * transToPdf 转换pdf
  29. * @param filePath 输入文件路径
  30. * @param pdfPath 输出pdf文件路径
  31. * @param suffix 输入文件后缀
  32. */
  33. public static void transToPdf(String filePath, String pdfPath, String suffix) {
  34. if (Arrays.asList(WORD).contains(suffix)) {
  35. word2PDF(filePath, pdfPath);
  36. } else if (Arrays.asList(EXCEL).contains(suffix)) {
  37. excel2PDF(filePath, pdfPath);
  38. } else if (Arrays.asList(PPT).contains(suffix)) {
  39. // 暂不实现,需要引入aspose.slides包
  40. }
  41. }
  42. private static void word2PDF(String inputFile, String pdfFile) {
  43. try {
  44. Class<?> aClass = Class.forName("com.aspose.words.zzZDQ");
  45. Field zzYAC = aClass.getDeclaredField("zzYAC");
  46. zzYAC.setAccessible(true);
  47. Field modifiersField = Field.class.getDeclaredField("modifiers");
  48. modifiersField.setAccessible(true);
  49. modifiersField.setInt(zzYAC, zzYAC.getModifiers() & ~Modifier.FINAL);
  50. zzYAC.set(null,new byte[]{76, 73, 67, 69, 78, 83, 69, 68});
  51. long old = System.currentTimeMillis();
  52. File file = new File(pdfFile); // 新建一个空白pdf文档
  53. FileOutputStream os = new FileOutputStream(file);
  54. Document doc = new Document(inputFile); // inputFile是将要被转化的word文档
  55. //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
  56. doc.save(os, com.aspose.words.SaveFormat.PDF);
  57. os.close();
  58. System.out.println(">>>>>>>>>> word文件转换pdf成功!");
  59. long now = System.currentTimeMillis();
  60. System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
  61. } catch (Exception e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. private static boolean getLicense2() {
  66. boolean result = false;
  67. try {
  68. InputStream is = PdfUtil.class.getClassLoader()
  69. .getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
  70. com.aspose.cells.License aposeLic = new com.aspose.cells.License();
  71. aposeLic.setLicense(is);
  72. result = true;
  73. } catch (Exception e) {
  74. e.printStackTrace();
  75. }
  76. return result;
  77. }
  78. private static void excel2PDF(String excelPath, String pdfPath) {
  79. if (!getLicense2()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
  80. return;
  81. }
  82. try {
  83. Workbook wb = new Workbook(excelPath);// 原始excel路径
  84. File pdfFile = new File(pdfPath);// 输出路径
  85. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
  86. //把excel所有内容放在一张PDF 页面上;
  87. pdfSaveOptions.setOnePagePerSheet(false);
  88. //把excel所有表头放在一张pdf上
  89. pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
  90. FileOutputStream fileOS = new FileOutputStream(pdfFile);
  91. wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
  92. fileOS.close();
  93. System.out.println(">>>>>>>>>> excel文件转换pdf成功!");
  94. } catch (Exception e) {
  95. e.printStackTrace();
  96. }
  97. }
  98. /**
  99. * pdf添加水印
  100. *
  101. * @param inputFile 需要添加水印的文件
  102. * @param outputFile 添加完水印的文件存放路径
  103. * @param waterMarkName 需要添加的水印文字
  104. * @param cover 是否覆盖
  105. * @return
  106. */
  107. public static boolean addWaterMark(String inputFile, String outputFile, String waterMarkName, boolean cover) {
  108. if (!cover) {
  109. File file = new File(outputFile);
  110. if (file.exists()) {
  111. return true;
  112. }
  113. }
  114. File file = new File(inputFile);
  115. if (!file.exists()) {
  116. return false;
  117. }
  118. PdfReader reader = null;
  119. PdfStamper stamper = null;
  120. try {
  121. reader = new PdfReader(inputFile);
  122. stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
  123. BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
  124. Rectangle pageRect = null;
  125. PdfGState gs = new PdfGState();
  126. //这里是透明度设置
  127. gs.setFillOpacity(opacity);
  128. //这里是条纹不透明度
  129. gs.setStrokeOpacity(0.2f);
  130. int total = reader.getNumberOfPages() + 1;
  131. System.out.println("Pdf页数:" + reader.getNumberOfPages());
  132. JLabel label = new JLabel();
  133. FontMetrics metrics;
  134. int textH = 0;
  135. int textW = 0;
  136. label.setText(waterMarkName);
  137. metrics = label.getFontMetrics(label.getFont());
  138. //字符串的高, 只和字体有关
  139. textH = metrics.getHeight();
  140. //字符串的宽
  141. textW = metrics.stringWidth(label.getText());
  142. PdfContentByte under;
  143. //循环PDF,每页添加水印
  144. for (int i = 1; i < total; i++) {
  145. pageRect = reader.getPageSizeWithRotation(i);
  146. //在内容上方添加水印
  147. under = stamper.getOverContent(i);
  148. under.saveState();
  149. under.setGState(gs);
  150. under.beginText();
  151. //这里是水印字体大小
  152. under.setFontAndSize(base, fontsize);
  153. for (int height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) {
  154. for (int width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) {
  155. // rotation:倾斜角度
  156. under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, angle);
  157. }
  158. }
  159. //添加水印文字
  160. under.endText();
  161. }
  162. System.out.println("添加水印成功!");
  163. return true;
  164. } catch (IOException e) {
  165. System.out.println("添加水印失败!错误信息为: " + e);
  166. return false;
  167. } catch (DocumentException e) {
  168. System.out.println("添加水印失败!错误信息为: " + e);
  169. return false;
  170. } finally {
  171. //关闭流
  172. if (stamper != null) {
  173. try {
  174. stamper.close();
  175. } catch (DocumentException e) {
  176. System.out.println("文件流关闭失败");
  177. } catch (IOException e) {
  178. System.out.println("文件流关闭失败");
  179. }
  180. }
  181. if (reader != null) {
  182. reader.close();
  183. }
  184. }
  185. }
  186. }

 3、poi模板导出工具类

  1. import java.util.*;
  2. import org.apache.poi.xwpf.usermodel.*;
  3. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
  4. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
  5. public class ExportWordUtil {
  6. private ExportWordUtil() {
  7. }
  8. /**
  9. * 替换文档中段落文本
  10. *
  11. * @param document docx解析对象
  12. * @param textMap 需要替换的信息集合
  13. */
  14. public static void changeParagraphText(XWPFDocument document, Map<String, String> textMap) {
  15. //获取段落集合
  16. List<XWPFParagraph> paragraphs = document.getParagraphs();
  17. for (XWPFParagraph paragraph : paragraphs) {
  18. //判断此段落是否需要进行替换
  19. String text = paragraph.getText();
  20. if (checkText(text)) {
  21. List<XWPFRun> runs = paragraph.getRuns();
  22. for (XWPFRun run : runs) {
  23. //替换模板原来位置
  24. String textValue = changeValue(run.toString(), textMap);
  25. if (run.toString().toLowerCase().indexOf("checkbox_") != -1) {// 复选框填充值
  26. run.setFontFamily("SimSun");
  27. String[] tArr = textValue.split("@@@");
  28. for (int i = 0; i < tArr.length; i++) {
  29. if (i == 0) {
  30. run.setText(tArr[i], 0);
  31. } else {
  32. run.setText(tArr[i]);
  33. }
  34. if (i != tArr.length-1) {
  35. run.addBreak();//换行
  36. }
  37. }
  38. } else {
  39. run.setText(textValue, 0);
  40. }
  41. }
  42. }
  43. }
  44. }
  45. /**
  46. * 复制表头 插入行数据,这里样式和表头一样
  47. * @param document docx解析对象
  48. * @param tableList 需要插入数据集合
  49. * @param tableIndex 表格索引,在word表格对象集合中是第几个表格,从0开始
  50. * @param headerIndex 表头的行索引,从0开始
  51. */
  52. public static void copyHeaderInsertText(XWPFDocument document, List<Map<String,String>> tableList, String[] fields, int tableindex, int headerIndex){
  53. if(null == tableList || null == fields){
  54. return;
  55. }
  56. //获取表格对象集合
  57. List<XWPFTable> tables = document.getTables();
  58. XWPFTableRow copyRow = tables.get(tableindex).getRow(headerIndex);
  59. List<XWPFTableCell> cellList = copyRow.getTableCells();
  60. if (null == cellList) {
  61. return;
  62. }
  63. //遍历要添加的数据的list
  64. for (int i = 0; i < tableList.size(); i++) {
  65. //插入一行
  66. XWPFTableRow targetRow = tables.get(tableindex).insertNewTableRow(headerIndex + i);
  67. //复制行属性
  68. targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());
  69. Map<String,String> map = tableList.get(i);
  70. // 字段匹配后,插入单元格并赋值
  71. for (String field : fields) {
  72. int idx = 0;
  73. for(Map.Entry<String,String> entry: map.entrySet()){
  74. if(!field.equals(entry.getKey())) continue;
  75. XWPFTableCell sourceCell = cellList.get(idx);
  76. //插入一个单元格
  77. XWPFTableCell targetCell = targetRow.addNewTableCell();
  78. //复制列属性
  79. targetCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
  80. //targetCell.setText(entry.getValue());
  81. /** XWPFTableCell 无法直接设置字体样式,故换一种方式 **/
  82. //获取 XWPFTableCell 的CTTc
  83. CTTc ctTc = targetCell.getCTTc();
  84. //获取 CTP
  85. CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0);
  86. //getParagraph(ctP) 获取 XWPFParagraph
  87. XWPFParagraph par = targetCell.getParagraph(ctP);
  88. //XWPFRun 设置格式
  89. XWPFRun run = par.createRun();
  90. String textValue = entry.getValue();
  91. // 复选框填充值
  92. if (field.toLowerCase().indexOf("checkbox_") != -1) {
  93. run.setFontFamily("SimSun");
  94. String[] tArr = textValue.split("@@@");
  95. for (int j = 0; j < tArr.length; j++) {
  96. if (j == 0) {
  97. run.setText(tArr[j], 0);
  98. } else {
  99. run.setText(tArr[j]);
  100. }
  101. if (j != tArr.length-1) {
  102. run.addBreak();//换行
  103. }
  104. }
  105. } else {
  106. run.setText(textValue, 0);
  107. }
  108. idx ++;
  109. };
  110. }
  111. }
  112. if (tableList.size() > 0) {
  113. List<XWPFTableRow> rows = tables.get(tableindex).getRows();
  114. int rowLength = rows.size();
  115. deleteTable(tables.get(tableindex), tableList.size() + headerIndex, rowLength);
  116. }
  117. }
  118. /**
  119. * 删除表格行
  120. * @param table 表格对象
  121. * @param fromIndex 从第几行,从0开始
  122. * @param toIndex 到第几行,从0开始
  123. */
  124. public static void deleteTable(XWPFTable table, int fromIndex, int toIndex){
  125. for (int i = fromIndex; i < toIndex; i++) {
  126. table.removeRow(fromIndex);
  127. }
  128. }
  129. /**
  130. * 替换表格对象方法
  131. *
  132. * @param document docx解析对象
  133. * @param textMap 需要替换的信息集合
  134. */
  135. public static void changeTableText(XWPFDocument document, Map<String, String> textMap) {
  136. //获取表格对象集合
  137. List<XWPFTable> tables = document.getTables();
  138. for (int i = 0; i < tables.size(); i++) {
  139. //只处理行数大于等于2的表格
  140. XWPFTable table = tables.get(i);
  141. if (table.getRows().size() > 1) {
  142. //判断表格是需要替换还是需要插入,判断逻辑有$为替换
  143. if (checkText(table.getText())) {
  144. List<XWPFTableRow> rows = table.getRows();
  145. //遍历表格,并替换模板
  146. eachTable(rows, textMap);
  147. }
  148. }
  149. }
  150. }
  151. /**
  152. * 遍历表格,并替换模板
  153. *
  154. * @param rows 表格行对象
  155. * @param textMap 需要替换的信息集合
  156. */
  157. public static void eachTable(List<XWPFTableRow> rows, Map<String, String> textMap) {
  158. for (XWPFTableRow row : rows) {
  159. List<XWPFTableCell> cells = row.getTableCells();
  160. for (XWPFTableCell cell : cells) {
  161. //判断单元格是否需要替换
  162. if (checkText(cell.getText())) {
  163. List<XWPFParagraph> paragraphs = cell.getParagraphs();
  164. for (XWPFParagraph paragraph : paragraphs) {
  165. List<XWPFRun> runs = paragraph.getRuns();
  166. for (XWPFRun run : runs) {
  167. String textValue = changeValue(run.toString(), textMap);
  168. if (run.toString().toLowerCase().indexOf("checkbox_") != -1) {// 复选框填充值
  169. run.setFontFamily("SimSun");
  170. String[] tArr = textValue.split("@@@");
  171. for (int i = 0; i < tArr.length; i++) {
  172. if (i == 0) {
  173. run.setText(tArr[i], 0);
  174. } else {
  175. run.setText(tArr[i]);
  176. }
  177. if (i != tArr.length-1) {
  178. run.addBreak();//换行
  179. }
  180. }
  181. } else {
  182. run.setText(textValue, 0);
  183. }
  184. }
  185. }
  186. }
  187. }
  188. }
  189. }
  190. /**
  191. * 匹配传入信息集合与模板
  192. *
  193. * @param value 模板需要替换的区域
  194. * @param textMap 传入信息集合
  195. * @return 模板需要替换区域信息集合对应值
  196. */
  197. public static String changeValue(String value, Map<String, String> textMap) {
  198. Set<Map.Entry<String, String>> textSets = textMap.entrySet();
  199. for (Map.Entry<String, String> textSet : textSets) {
  200. //匹配模板与替换值 格式${key}
  201. String key = "${" + textSet.getKey() + "}";
  202. if (value.indexOf(key) != -1) {
  203. value = textSet.getValue();
  204. }
  205. }
  206. //模板未匹配到区域替换为空
  207. if (checkText(value)) {
  208. value = "";
  209. }
  210. return value;
  211. }
  212. /**
  213. * 判断文本中是否包含$
  214. *
  215. * @param text 文本
  216. * @return 包含返回true, 不包含返回false
  217. */
  218. public static boolean checkText(String text) {
  219. boolean check = false;
  220. if (text.indexOf("$") != -1) {
  221. check = true;
  222. }
  223. return check;
  224. }
  225. }

 4、测试类

  1. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  2. import java.io.*;
  3. import java.util.*;
  4. /**
  5. * @ClassName: Mytest
  6. * @Description: 测试类
  7. * @Suthor: mxch
  8. * @Create: 2023-05-13
  9. **/
  10. public class Mytest {
  11. public static void main(String args[]){
  12. // 开始时间
  13. long stime = System.currentTimeMillis();
  14. // 模拟点数据
  15. Map<String, String> paragraphMap = new HashMap<>();
  16. Map<String, String> tableMap = new HashMap<>();
  17. paragraphMap.put("name", "赵云");
  18. paragraphMap.put("date", "2020-03-25");
  19. paragraphMap.put("checkbox_sf", "\u25A1是" + " " + "\u2611否");
  20. tableMap.put("name", "赵云");
  21. tableMap.put("sex", "男");
  22. tableMap.put("birthday", "2020-01-01");
  23. tableMap.put("checkbox_sf", "\u25A1是s" + " " + "\u2611否d" + "@@@" + "\u25A1是" + " " + "\u2611否");
  24. List<Map<String,Object>> tableDatalist = new ArrayList<>();
  25. /*************清单1****************/
  26. List<Map<String,String>> familyList = new ArrayList<>();
  27. Map m = new HashMap();
  28. m.put("name","露娜");
  29. m.put("sex","女");
  30. m.put("position","野友");
  31. m.put("no","6660");
  32. familyList.add(m);
  33. m = new HashMap();
  34. m.put("name","鲁班");
  35. m.put("sex","男");
  36. m.put("position","射友");
  37. m.put("no","2220");
  38. familyList.add(m);
  39. m = new HashMap();
  40. m.put("name","程咬金");
  41. m.put("sex","男");
  42. m.put("position","肉友");
  43. m.put("no","9990");
  44. familyList.add(m);
  45. Map tableData = new HashMap();
  46. tableData.put("list", familyList);
  47. tableData.put("fields", new String[]{"name","sex","position","no"});
  48. tableData.put("tableIndex", 1);
  49. tableData.put("headerIndex", 1);
  50. tableDatalist.add(tableData);
  51. /*************清单2****************/
  52. familyList = new ArrayList<>();
  53. m = new HashMap();
  54. m.put("name","太乙真人");
  55. m.put("sex","男");
  56. m.put("position","辅友");
  57. m.put("no","1110");
  58. m.put("checkbox_fcxz", "\u25A1商品房" + "@@@" + "\u2611福利房" + "@@@" + "\u25A1经济适用房" + "@@@"
  59. + "\u2611限价房" + "@@@" + "\u2611自建房" + "@@@" + "\u25A1车库、车位、储藏间" + "@@@" + "\u25A1其他");
  60. familyList.add(m);
  61. m = new HashMap();
  62. m.put("name","貂蝉");
  63. m.put("sex","女");
  64. m.put("position","法友");
  65. m.put("no","8880");
  66. m.put("checkbox_fcxz", "\u25A1商品房" + "@@@" + "\u2611福利房" + "@@@" + "\u2611经济适用房" + "@@@"
  67. + "\u2611限价房" + "@@@" + "\u2611自建房" + "@@@" + "\u2611车库、车位、储藏间" + "@@@" + "\u25A1其他");
  68. familyList.add(m);
  69. tableData = new HashMap();
  70. tableData.put("list", familyList);
  71. tableData.put("fields", new String[]{"name","sex","position","checkbox_fcxz"});
  72. tableData.put("tableIndex", 2);
  73. tableData.put("headerIndex", 1);
  74. tableDatalist.add(tableData);
  75. exportWord(paragraphMap,tableMap,tableDatalist);
  76. // 结束时间
  77. long etime = System.currentTimeMillis();
  78. // 计算执行时间
  79. System.out.printf("执行时长:%d 毫秒.", (etime - stime));
  80. }
  81. @SuppressWarnings("unchecked")
  82. private static void exportWord(Map<String, String> paragraphMap,Map<String, String> tableMap,List<Map<String,Object>> tableDatalist){
  83. String classpath = Mytest.class.getClass().getResource("/").getPath();
  84. String templatePath = classpath.replace("WEB-INF/classes", "导入模板");
  85. String t_filepath = classpath.replace("WEB-INF/classes", "import");
  86. String filename = "person";
  87. File f = new File(templatePath + filename + ".docx");
  88. File f1 = new File(t_filepath + filename + ".docx");
  89. File f2 = new File(t_filepath + filename + ".pdf");
  90. File f3 = new File(t_filepath + filename + "_水印.pdf");
  91. XWPFDocument document = null;
  92. try {
  93. //解析docx模板并获取document对象
  94. document = new XWPFDocument(new FileInputStream(new File(f.getPath())));
  95. ExportWordUtil.changeParagraphText(document, paragraphMap);
  96. ExportWordUtil.changeTableText(document, tableMap);
  97. for (Map<String,Object> map : tableDatalist) {
  98. ExportWordUtil.copyHeaderInsertText(document, (List<Map<String,String>>) map.get("list"), (String[]) map.get("fields"),
  99. (Integer) map.get("tableIndex"), (Integer) map.get("headerIndex"));
  100. }
  101. FileOutputStream out = new FileOutputStream(new File(f1.getPath()));
  102. document.write(out);
  103. out.close();
  104. } catch (IOException e) {
  105. e.printStackTrace();
  106. } finally {
  107. if (document != null) {
  108. try {
  109. document.close();
  110. } catch (IOException e) {
  111. e.printStackTrace();
  112. }
  113. }
  114. }
  115. String suffix = f1.getPath().substring(f1.getPath().lastIndexOf(".") + 1); // 后缀
  116. // aspose 转 pdf
  117. PdfUtil.transToPdf(f1.getPath(), f2.getPath(), suffix);
  118. // itextpdf给pdf加水印
  119. PdfUtil.addWaterMark(f2.getPath(), f3.getPath(), "测试水印", true);
  120. }
  121. }

5、模板

6、最终效果 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/388492
推荐阅读
相关标签
  

闽ICP备14008679号