• pdf导出实例(itestpdf)


    依赖

    1. <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
    2. <dependency>
    3. <groupId>com.itextpdf</groupId>
    4. <artifactId>itextpdf</artifactId>
    5. <version>5.5.10</version>
    6. </dependency>

    工具类

    1. package org.jeecg.utils;
    2. import com.itextpdf.text.*;
    3. import com.itextpdf.text.pdf.*;
    4. import io.swagger.annotations.ApiOperation;
    5. import org.springframework.beans.factory.annotation.Value;
    6. import org.springframework.core.io.ClassPathResource;
    7. import org.springframework.core.io.Resource;
    8. import org.springframework.stereotype.Component;
    9. import org.springframework.web.bind.annotation.GetMapping;
    10. import org.springframework.web.bind.annotation.RequestMapping;
    11. import org.springframework.web.bind.annotation.RestController;
    12. import javax.servlet.http.HttpServletResponse;
    13. import java.io.ByteArrayOutputStream;
    14. import java.io.FileOutputStream;
    15. import java.io.IOException;
    16. import java.io.OutputStream;
    17. import java.net.URLEncoder;
    18. import java.util.*;
    19. import java.util.List;
    20. public class PDFUtil {
    21. /**
    22. * pdf模板导出
    23. *
    24. * @param map 导出结果
    25. * @param filePath 空pdf路径,作物前端访问路径
    26. * @throws Exception
    27. */
    28. public static void creatPdf(Map<String, Object> map, String filePath) throws Exception {
    29. try {
    30. FileOutputStream fos = new FileOutputStream(filePath);;
    31. BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    32. // 读取pdf模板路径
    33. Resource resource = new ClassPathResource(String.valueOf(map.get("tempPath")));
    34. PdfReader reader = new PdfReader(resource.getURL());
    35. ByteArrayOutputStream bos = new ByteArrayOutputStream();
    36. PdfStamper stamper = new PdfStamper(reader, bos);
    37. stamper.setFormFlattening(true);
    38. AcroFields form = stamper.getAcroFields();
    39. // 文字类的内容处理
    40. Map<String, String> datemap = (Map<String, String>) map.get("dataMap");
    41. form.addSubstitutionFont(bf);
    42. for (String key : datemap.keySet()) {
    43. String value = datemap.get(key);
    44. form.setField(key, value);
    45. form.setFieldProperty(key,"textsize",9f,null);
    46. }
    47. // 图片类的内容处理
    48. Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");
    49. for (String key : imgmap.keySet()) {
    50. String value = imgmap.get(key);
    51. String imgpath = value;
    52. int pageNo = form.getFieldPositions(key).get(0).page;
    53. Rectangle signRect = form.getFieldPositions(key).get(0).position;
    54. float x = signRect.getLeft();
    55. float y = signRect.getBottom();
    56. // 根据路径读取图片
    57. Image image = Image.getInstance(imgpath);
    58. // 获取图片页面
    59. PdfContentByte under = stamper.getOverContent(pageNo);
    60. // 图片大小自适应
    61. image.scaleToFit(signRect.getWidth(), signRect.getHeight());
    62. // 添加图片
    63. image.setAbsolutePosition(x, y);
    64. under.addImage(image);
    65. }
    66. // 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
    67. stamper.setFormFlattening(false);
    68. stamper.close();
    69. Document doc = new Document();
    70. PdfCopy copy = new PdfCopy(doc, fos);
    71. doc.open();
    72. int pageNum = reader.getNumberOfPages();
    73. for (int i = 1; i <= pageNum; i++) {
    74. PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
    75. copy.addPage(importPage);
    76. }
    77. doc.close();
    78. fos.close();
    79. } catch (IOException e) {
    80. System.out.println(e);
    81. } catch (DocumentException e) {
    82. System.out.println(e);
    83. }
    84. }
    85. }

    导出结果数据实例(仅供参考)

    1. package com.fiftheconomic.dataCalculate.service.impl;
    2. import com.fiftheconomic.dataCalculate.domain.TjDataCalculateBase;
    3. import com.fiftheconomic.dataCalculate.domain.TjDataCalculateDetail;
    4. import com.fiftheconomic.dataCalculate.domain.resCompenyIndex;
    5. import com.fiftheconomic.dataCalculate.service.IPdfService;
    6. import org.springframework.stereotype.Service;
    7. import java.text.SimpleDateFormat;
    8. import java.time.LocalDate;
    9. import java.util.*;
    10. /**
    11. * @Author: 苏子龙
    12. * @Date: 2023/08/01/17:00
    13. * @Description:
    14. */
    15. @Service
    16. public class PdfServiceImpl implements IPdfService {
    17. /**
    18. * 123 工业单位填报 124 批发和零售业单位填报 125 住宿和餐饮业单位填报 126 制造业,信息传输、软件和信息技术服务业,科学研究和技术服务业单位填报
    19. *
    20. * @param resMap
    21. * @param list
    22. * @return
    23. */
    24. @Override
    25. public Map<String, Object> oneThree(List<resCompenyIndex> resMap, TjDataCalculateBase base, List<TjDataCalculateDetail> list) {
    26. List<List<String>> lists = new ArrayList<>();//表格 (一行数据一个list)
    27. SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
    28. Map<String, String> map = new HashMap<>();//文本域
    29. for (int i = 0; i < resMap.size(); i++) {
    30. if (resMap.get(i).getIndexCode() != null) {
    31. if (!map.containsKey(resMap.get(i).getIndexCode())) {
    32. map.put(resMap.get(i).getIndexCode(), resMap.get(i).getIndexValue());
    33. }
    34. }
    35. }
    36. //添加tj_data_calculate_index基础信息表数据
    37. for (int j = 0; j < list.size(); j++) {
    38. System.out.println("++++++++" + j);
    39. TjDataCalculateDetail data = list.get(j);
    40. map.put("name" + j, data.getIndexName());
    41. map.put("unit" + j, data.getUnitof());
    42. map.put("value" + j, data.getIndexValue());
    43. }
    44. // map.put("name", "无"); //添加tj_data_calculate_index头信息
    45. // map.put("nameInfo", "无"); //填表人姓名
    46. // map.put("phoen", "无");//填表人电话
    47. // map.put("nameBy", "无");//单位负责人
    48. // map.put("USCI", base.getUSCI());//企业社会信用统一代码
    49. // map.put("comName", base.getComName());//单位详细名称
    50. // //添加日期
    51. // LocalDate now = LocalDate.now();
    52. // map.put("y", String.valueOf(now.getYear()));
    53. // map.put("m", String.valueOf(now.getMonthValue()));
    54. // map.put("d", String.valueOf(now.getDayOfMonth()));
    55. // map.put("time", String.valueOf(now));//填表人电话
    56. Map<String, Object> o = new HashMap<>();
    57. String s = base.getIndustryCode();
    58. if (s.equals("1")) {
    59. o.put("tempPath", "static/pdf/123.pdf");
    60. } else if (s.equals("2") || s.equals("3")) {
    61. o.put("tempPath", "static/pdf/124.pdf");
    62. } else if (s.equals("4") || s.equals("5")) {
    63. o.put("tempPath", "static/pdf/125.pdf");
    64. } else {
    65. o.put("tempPath", "static/pdf/126.pdf");
    66. }
    67. o.put("dataMap", map);
    68. o.put("imgMap", new HashMap<>());
    69. Map<String, List<List<String>>> listMap = new HashMap<>();
    70. listMap.put("table", lists);
    71. o.put("tableList", listMap);
    72. return o;
    73. }
    74. public static void main(String[] args) {
    75. LocalDate now = LocalDate.now();
    76. System.out.println(now.getYear());
    77. System.out.println(now.getMonthValue());
    78. System.out.println(now.getDayOfMonth());
    79. }
    80. }

    优化工具包

    1. public static String creatPdf1(Map<String, Object> map ,OutputStream out,float width[]) throws Exception {
    2. BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    3. // // 输出流
    4. // String outPutPath = "E:/excel/files/pdf模板导出.pdf";
    5. // FileOutputStream out = new FileOutputStream(filePath);
    6. // 读取pdf模板路径
    7. Resource resource = new ClassPathResource(String.valueOf(map.get("tempPath")));
    8. PdfReader reader = new PdfReader(resource.getURL());
    9. ByteArrayOutputStream bos = new ByteArrayOutputStream();
    10. PdfStamper stamper = new PdfStamper(reader, bos);
    11. stamper.setFormFlattening(true);
    12. AcroFields form = stamper.getAcroFields();
    13. // 文字类的内容处理
    14. Map<String, String> datemap = (Map<String, String>) map.get("dataMap");
    15. form.addSubstitutionFont(bf);
    16. for (String key : datemap.keySet()) {
    17. String value = datemap.get(key);
    18. form.setField(key, value);
    19. form.setFieldProperty(key, "textsize", 9f, null);
    20. }
    21. // 图片类的内容处理
    22. Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");
    23. for (String key : imgmap.keySet()) {
    24. String value = imgmap.get(key);
    25. String imgpath = value;
    26. int pageNo = form.getFieldPositions(key).get(0).page;
    27. Rectangle signRect = form.getFieldPositions(key).get(0).position;
    28. float x = signRect.getLeft();
    29. float y = signRect.getBottom();
    30. // 根据路径读取图片
    31. Image image = Image.getInstance(imgpath);
    32. // 获取图片页面
    33. PdfContentByte under = stamper.getOverContent(pageNo);
    34. // 图片大小自适应
    35. image.scaleToFit(signRect.getWidth(), signRect.getHeight());
    36. // 添加图片
    37. image.setAbsolutePosition(x, y);
    38. under.addImage(image);
    39. }
    40. // 表格类
    41. Map<String, List<List<String>>> listMap = (Map>>) map.get("tableList");
    42. if (listMap != null) {
    43. Object[] arr = new Object[]{};
    44. if (listMap.containsKey("table1")) {
    45. List<List<String>> lists1 = listMap.get("table1");
    46. if (lists1.size() > 0) {
    47. arr = new Object[]{"table", "table1"};
    48. } else {
    49. arr = new Object[]{"table"};
    50. }
    51. }else {
    52. arr = new Object[]{"table"};
    53. arr = new Object[]{"tableInfo"};
    54. }
    55. // for (Object key : arr) {
    56. List<List<String>> lists = listMap.get("table");
    57. List<List<String>> listInfo = listMap.get("tableInfo");
    58. List<List<String>> listBy = listMap.get("table1");
    59. //判断
    60. if (listBy!= null && listBy.size()>0) {
    61. //遍历数据添加序号
    62. for (int i = 0; i < listBy.size(); i++) {
    63. List<String> list = listBy.get(i);
    64. // List<String> list = listBy.get(0);
    65. String data = list.get(0);
    66. String on = i + 1 + " " + data;
    67. // String on = 0 + 1 + " " + data;
    68. list.set(0, on);}
    69. int pageNo = 0;
    70. if (form.getFieldPositions("table1") == null) {
    71. pageNo = 0;
    72. } else {
    73. pageNo = form.getFieldPositions("table1").get(0).page;
    74. }
    75. PdfContentByte pcb = stamper.getOverContent(pageNo);
    76. List<AcroFields.FieldPosition> listAf = form.getFieldPositions("table1");
    77. Rectangle signRect = listAf.get(0).position;
    78. //表格位置
    79. int columnInfo = listBy.get(0).size();
    80. int rowInfo = listBy.size();
    81. PdfPTable tableInfo = new PdfPTable(columnInfo);
    82. // float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
    83. tableInfo.setTotalWidth(width);
    84. tableInfo.setLockedWidth(true);
    85. tableInfo.setKeepTogether(true);
    86. tableInfo.setSplitLate(false);
    87. tableInfo.setSplitRows(true);
    88. Font FontProve = new Font(bf, 8, 0);
    89. //表格数据填写
    90. for (int k = 0; k < rowInfo; k++) {
    91. List<String> listTo = listBy.get(k);
    92. // List<String> listTo = listBy.get(i);
    93. for (int j = 0; j < columnInfo; j++) {
    94. Paragraph paragraph = new Paragraph(String.valueOf(listTo.get(j)), FontProve);
    95. PdfPCell cell = new PdfPCell(paragraph);
    96. cell.setBorderWidth(1);
    97. cell.setMinimumHeight(1);
    98. if (j == 0) {
    99. cell.setVerticalAlignment(Element.ALIGN_LEFT);
    100. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    101. } else {
    102. cell.setVerticalAlignment(Element.ALIGN_CENTER);
    103. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    104. }
    105. cell.setLeading(0, (float) 1.4);
    106. cell.disableBorderSide(15);//隐藏
    107. tableInfo.addCell(cell);
    108. }
    109. }
    110. tableInfo.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
    111. // }
    112. }
    113. if (listInfo!= null && listInfo.size()>0) {
    114. //遍历数据添加序号
    115. for (int i = 0; i < listInfo.size(); i++) {
    116. List<String> list = listInfo.get(i);
    117. String data = list.get(0);
    118. String on = i + 1 +" " + data ;
    119. list.set(0,on);
    120. }
    121. int pageNo = 0;
    122. if (form.getFieldPositions("tableInfo") == null) {
    123. pageNo = 0;
    124. } else {
    125. pageNo = form.getFieldPositions("tableInfo").get(0).page;
    126. }
    127. PdfContentByte pcb = stamper.getOverContent(pageNo);
    128. List<AcroFields.FieldPosition> listAf = form.getFieldPositions("tableInfo");
    129. Rectangle signRect = listAf.get(0).position;
    130. //表格位置
    131. int columnInfo = listInfo.get(0).size();
    132. int rowInfo = listInfo.size();
    133. PdfPTable tableInfo = new PdfPTable(columnInfo);
    134. float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
    135. //
    136. tableInfo.setTotalWidth(tatalWidth);
    137. tableInfo.setLockedWidth(true);
    138. tableInfo.setKeepTogether(true);
    139. tableInfo.setSplitLate(false);
    140. tableInfo.setSplitRows(true);
    141. Font FontProve = new Font(bf, 8, 0);
    142. //表格数据填写
    143. for (int i = 0; i < rowInfo; i++) {
    144. List<String> list = listInfo.get(i);
    145. for (int j = 0; j < columnInfo; j++) {
    146. Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
    147. PdfPCell cell = new PdfPCell(paragraph);
    148. cell.setBorderWidth(1);
    149. cell.setMinimumHeight(1);
    150. if (j == 0) {
    151. cell.setVerticalAlignment(Element.ALIGN_LEFT);
    152. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    153. } else {
    154. cell.setVerticalAlignment(Element.ALIGN_CENTER);
    155. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    156. }
    157. cell.setLeading(0, (float) 1.4);
    158. cell.disableBorderSide(15);//隐藏
    159. tableInfo.addCell(cell);
    160. }
    161. }
    162. System.out.println(signRect.getLeft());
    163. System.out.println(signRect.getTop());
    164. System.out.println(pcb);
    165. tableInfo.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
    166. }
    167. if (lists!= null && lists.size()>0) {
    168. //遍历数据添加序号
    169. for (int i = 0; i < lists.size(); i++) {
    170. List<String> list = lists.get(i);
    171. String data = list.get(0);
    172. String on = i + 1 +" "+ data ;
    173. list.set(0,on);
    174. }
    175. int pageNo = 0;
    176. if (form.getFieldPositions("table") == null) {
    177. pageNo = 0;
    178. } else {
    179. pageNo = form.getFieldPositions("table").get(0).page;
    180. }
    181. PdfContentByte pcb = stamper.getOverContent(pageNo);
    182. List<AcroFields.FieldPosition> listAf = form.getFieldPositions("table");
    183. Rectangle signRect = listAf.get(0).position;
    184. //表格位置
    185. int column = lists.get(0).size();
    186. int row = lists.size();
    187. PdfPTable table = new PdfPTable(column);
    188. // float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
    189. // table.setTotalWidth(width);
    190. table.setLockedWidth(true);
    191. table.setKeepTogether(true);
    192. table.setSplitLate(false);
    193. table.setSplitRows(true);
    194. Font FontProve = new Font(bf, 8, 0);
    195. //表格数据填写
    196. for (int i = 0; i < row; i++) {
    197. List<String> list = lists.get(i);
    198. for (int j = 0; j < column; j++) {
    199. Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
    200. PdfPCell cell = new PdfPCell(paragraph);
    201. cell.setBorderWidth(1);
    202. cell.setMinimumHeight(1);
    203. if (j == 0) {
    204. cell.setVerticalAlignment(Element.ALIGN_LEFT);
    205. cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    206. } else {
    207. cell.setVerticalAlignment(Element.ALIGN_CENTER);
    208. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    209. }
    210. cell.setLeading(0, (float) 1.4);
    211. cell.disableBorderSide(15);//隐藏
    212. table.addCell(cell);
    213. }
    214. }
    215. table.writeSelectedRows(1, -1, signRect.getLeft(), signRect.getTop(), pcb);
    216. }
    217. }
    218. // 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
    219. stamper.setFormFlattening(true);
    220. stamper.close();
    221. Document doc = new Document();
    222. PdfCopy copy = new PdfCopy(doc, out);
    223. doc.open();
    224. // File file = new File("ruoyi-admin/src/main/resources/static/pdf/111.pdf");
    225. // File file = new File("D:\\feishu\\yihe\\111.pdf");
    226. //本地路径
    227. File file = new File("E:\\item\\yihe\\ruoyi-admin\\src\\main\\resources\\static\\pdf\\111.pdf");
    228. //线上路径
    229. // File file = new File("D:\\feishu\\yihe\\111.pdf");
    230. PdfCopy copy1 = new PdfCopy(doc, new FileOutputStream(file));
    231. doc.open();
    232. int pageNum = reader.getNumberOfPages();
    233. for (int i = 1; i <= pageNum; i++) {
    234. PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
    235. copy.addPage(importPage);
    236. copy1.addPage(importPage);
    237. }
    238. // String url = AliyunOSSUtil.upload(getMultipartFile(file));
    239. // System.out.println("url = " + url);
    240. doc.close();
    241. return "url";
    242. }

  • 相关阅读:
    配置Kafka消息保留时间
    SpringCloudGateway 入门
    04 使用Keil模拟器和Debug (printf) Viewer窗口实现scanf输入,并进行串口收发回环,无需fgetc重定向
    夜莺日志采集mtail
    CentOS 7 安装 Redis 5 (单机 6379)
    linux安装MySql之错误
    微信小程序overflow-x超出部分样式不渲染
    【JavaSE】阶段性小结,运用Java实现图书管理系统
    C/C++进程超详细详解【中部分】(系统性学习day07)
    Redis数据结构之跳表
  • 原文地址:https://blog.csdn.net/weixin_62108279/article/details/133901131