PdfUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package com.xunmei.file.utils;
  2. import cn.hutool.extra.spring.SpringUtil;
  3. import com.lowagie.text.*;
  4. import com.lowagie.text.pdf.*;
  5. import com.xunmei.file.vo.ItextPdfTableVo;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.core.io.Resource;
  9. import java.io.File;
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. import java.util.Map;
  16. @Slf4j
  17. public class PdfUtil {
  18. public static ItextPdfTableVo createTable(String filename, int numColumns, int fontSize) throws Exception {
  19. Document document = new Document(PageSize.A4, 0, 0, 50, 0);//SUPPRESS
  20. FileOutputStream fos = new FileOutputStream(filename);
  21. log.info("filename,{}",filename);
  22. final PdfWriter writer = PdfWriter.getInstance(document, fos);
  23. document.open();
  24. // 使用语言包字
  25. BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  26. // 外部字体
  27. BaseFont fs = BaseFont.createFont("/fonts/msyh.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  28. Font tableFont = new Font(fs, fontSize, Font.NORMAL);
  29. PdfPTable table = new PdfPTable(numColumns);
  30. // 设置各列列宽
  31. // table.setTotalWidth(new float[]{90, 100, 100, 120, 100, 100});
  32. table.setSpacingBefore(16f);
  33. ItextPdfTableVo itextPdfTableVo = new ItextPdfTableVo();
  34. itextPdfTableVo.setDocument(document);
  35. itextPdfTableVo.setWriter(writer);
  36. itextPdfTableVo.setAbf(abf);
  37. itextPdfTableVo.setFs(fs);
  38. itextPdfTableVo.setTableFont(tableFont);
  39. itextPdfTableVo.setTable(table);
  40. return itextPdfTableVo;
  41. }
  42. public static PdfPCell createPDFCell(Font tableFont, PdfPTable table, String content, int align, Integer colspan, Integer rowspan) {
  43. final PdfPCell cell = cell(tableFont, content, align, colspan, rowspan);
  44. table.addCell(cell);
  45. return cell;
  46. }
  47. public static PdfPCell createPDFCell(Font tableFont, PdfPTable table, String content, int align, Integer colspan, Integer rowspan, Integer lineSpacing) {
  48. final PdfPCell cell = cell(tableFont, content, align, colspan, rowspan, lineSpacing);
  49. table.addCell(cell);
  50. return cell;
  51. }
  52. //底部无边框的单元格
  53. public static PdfPCell createPDFCellWithoutBorder(Font tableFont, PdfPTable table, String content, int align, Integer colspan, Integer rowspan) {
  54. final PdfPCell cell = cell(tableFont, content, align, colspan, rowspan);
  55. cell.setBorder(Rectangle.LEFT | Rectangle.RIGHT);
  56. table.addCell(cell);
  57. return cell;
  58. }
  59. private static PdfPCell cell(Font tableFont, String content, int align, Integer colspan, Integer rowspan) {
  60. PdfPCell cell = new PdfPCell(new Phrase(content, tableFont));
  61. if (colspan != null && colspan > 0) {
  62. cell.setColspan(colspan);
  63. }
  64. if (rowspan != null && rowspan > 0) {
  65. cell.setRowspan(rowspan);
  66. }
  67. if (PdfPCell.ALIGN_MIDDLE != align) {
  68. cell.setHorizontalAlignment(align);
  69. cell.setPaddingLeft(8f);
  70. cell.setPaddingRight(8f);
  71. cell.setPaddingBottom(8f);
  72. } else {
  73. cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//设置单元格的垂直对齐方式
  74. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  75. }
  76. return cell;
  77. }
  78. private static PdfPCell cell(Font tableFont, String content, int align, Integer colspan, Integer rowspan, Integer lineSpacing) {
  79. PdfPCell cell = new PdfPCell(new Phrase(content, tableFont));
  80. if (colspan != null && colspan > 0) {
  81. cell.setColspan(colspan);
  82. }
  83. if (rowspan != null && rowspan > 0) {
  84. cell.setRowspan(rowspan);
  85. }
  86. cell.setLeading(lineSpacing, 0);
  87. if (PdfPCell.ALIGN_MIDDLE != align) {
  88. cell.setHorizontalAlignment(align);
  89. cell.setPaddingLeft(8f);
  90. cell.setPaddingRight(8f);
  91. cell.setPaddingBottom(8f);
  92. } else {
  93. cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//设置单元格的垂直对齐方式
  94. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  95. }
  96. return cell;
  97. }
  98. /**
  99. * 生成文字类型的水印
  100. */
  101. public static void createWatermark(Document document, PdfWriter writer, Font waterMarkFont, String content) throws DocumentException, IOException {
  102. PdfContentByte waterMarkPdfContent = writer.getDirectContentUnder();
  103. Phrase phrase = new Phrase(content, waterMarkFont);
  104. float pageWidth = document.right() + document.left();//获取pdf内容正文页面宽度
  105. float pageHeight = document.top() + document.bottom();//获取pdf内容正文页面高度
  106. //两行三列
  107. ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
  108. pageWidth * 0.25f, pageHeight * 0.2f, 45);
  109. ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
  110. pageWidth * 0.25f, pageHeight * 0.5f, 45);
  111. ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
  112. pageWidth * 0.25f, pageHeight * 0.8f, 45);
  113. ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
  114. pageWidth * 0.65f, pageHeight * 0.2f, 45);
  115. ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
  116. pageWidth * 0.65f, pageHeight * 0.5f, 45);
  117. ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase,
  118. pageWidth * 0.65f, pageHeight * 0.8f, 45);
  119. }
  120. public static void dealHeader(Document document, BaseFont fs, String title, int fontSize) throws DocumentException {
  121. //文件title
  122. Paragraph p = new Paragraph(title, new Font(fs, fontSize, Font.NORMAL));
  123. p.setAlignment(Paragraph.ALIGN_CENTER);
  124. // 文件title 段落下空白
  125. p.setSpacingAfter(10f);
  126. p.setAlignment(Element.ALIGN_CENTER);
  127. document.add(p);
  128. }
  129. public static void dealEduBody(Document document, PdfPTable table, Font tableFont, Map<String, Object> data) throws Exception {
  130. //第一行
  131. createPDFCell(tableFont, table, "时间", Element.ALIGN_CENTER, 1, 1);
  132. createPDFCell(tableFont, table, data.get("time").toString(), Element.ALIGN_CENTER, 2, 1);
  133. createPDFCell(tableFont, table, "地点", Element.ALIGN_CENTER, 1, 1);
  134. createPDFCell(tableFont, table, data.get("address").toString(), Element.ALIGN_CENTER, 2, 1);
  135. //第二行
  136. createPDFCell(tableFont, table, "主持人", Element.ALIGN_CENTER, 1, 1);
  137. createPDFCell(tableFont, table, data.get("hostName").toString(), Element.ALIGN_CENTER, 2, 1);
  138. createPDFCell(tableFont, table, "记录人", Element.ALIGN_CENTER, 1, 1);
  139. createPDFCell(tableFont, table, data.get("recorderName").toString(), Element.ALIGN_CENTER, 2, 1);
  140. //内容
  141. PdfPCell contentCell = new PdfPCell();
  142. contentCell.setColspan(6);
  143. Paragraph content = new Paragraph();
  144. String text = data.get("content").toString();
  145. content.add(new Chunk(text, tableFont));
  146. contentCell.addElement(content);
  147. contentCell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
  148. table.addCell(contentCell);
  149. //总结
  150. PdfPCell noteCell = new PdfPCell();
  151. noteCell.setColspan(6);
  152. Paragraph paragraph = new Paragraph();
  153. String noteText = data.get("note").toString();
  154. paragraph.add(new Chunk(noteText, tableFont));
  155. noteCell.addElement(paragraph);
  156. noteCell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
  157. table.addCell(noteCell);
  158. //签字区域
  159. PdfPCell signCell = new PdfPCell();
  160. signCell.setColspan(6);
  161. Paragraph signParagraph = new Paragraph();
  162. signParagraph.add(new Chunk("参会人员签字:", tableFont));
  163. signCell.addElement(signParagraph);
  164. signCell.setBorder(Rectangle.LEFT | Rectangle.RIGHT);
  165. table.addCell(signCell);
  166. //图片填充
  167. final PdfPTable imageTable = getImage((List<String>) data.get("image"), 12);
  168. final PdfPCell cell = new PdfPCell();
  169. cell.setNoWrap(false);
  170. cell.setPaddingLeft(8f);
  171. cell.setPaddingRight(8f);
  172. cell.setPaddingBottom(8f);
  173. cell.setPaddingTop(8f);
  174. cell.setColspan(6);
  175. cell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
  176. cell.addElement(imageTable);
  177. table.addCell(cell);
  178. /* //第三行
  179. createPDFCell(tableFont, table, "参会人员签字", Element.ALIGN_CENTER, 1, 1);
  180. createPDFCell(tableFont, table, data.get("users").toString(), Element.ALIGN_CENTER, 5, 1);*/
  181. document.add(table);
  182. }
  183. public static void dealDrillBody(Document document, PdfPTable table, Font tableFont, Map<String, Object> data) throws Exception {
  184. //第一行
  185. createPDFCell(tableFont, table, "演练单位", Element.ALIGN_CENTER, 1, 1);
  186. createPDFCell(tableFont, table, data.get("orgName").toString(), Element.ALIGN_CENTER, 2, 1);
  187. createPDFCell(tableFont, table, "地点", Element.ALIGN_CENTER, 1, 1);
  188. createPDFCell(tableFont, table, data.get("drillSite").toString(), Element.ALIGN_CENTER, 2, 1);
  189. //第二行
  190. createPDFCell(tableFont, table, "演练时间", Element.ALIGN_CENTER, 1, 1);
  191. createPDFCell(tableFont, table, data.get("drillTime").toString(), Element.ALIGN_CENTER, 2, 1);
  192. createPDFCell(tableFont, table, "指挥人", Element.ALIGN_CENTER, 1, 1);
  193. createPDFCell(tableFont, table, data.get("hostName").toString(), Element.ALIGN_CENTER, 2, 1);
  194. //第三行
  195. createPDFCell(tableFont, table, "演练项目", Element.ALIGN_CENTER, 1, 1);
  196. createPDFCell(tableFont, table, data.get("typeText").toString(), Element.ALIGN_CENTER, 5, 1);
  197. //预设案由
  198. PdfPCell contentCell = new PdfPCell();
  199. contentCell.setColspan(6);
  200. Paragraph content = new Paragraph();
  201. String text = data.get("presetCase").toString();
  202. content.add(new Chunk(text, tableFont));
  203. contentCell.addElement(content);
  204. contentCell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
  205. table.addCell(contentCell);
  206. //演练情况
  207. PdfPCell noteCell = new PdfPCell();
  208. noteCell.setColspan(6);
  209. Paragraph paragraph = new Paragraph();
  210. String noteText = data.get("drillSituation").toString();
  211. paragraph.add(new Chunk(noteText, tableFont));
  212. noteCell.addElement(paragraph);
  213. noteCell.setBorder(Rectangle.LEFT | Rectangle.RIGHT);
  214. table.addCell(noteCell);
  215. //演练情况 图片填充
  216. final PdfPTable imageTable1 = getImage((List<String>) data.get("imageData"), 6);
  217. final PdfPCell cell1 = new PdfPCell();
  218. cell1.setNoWrap(false);
  219. cell1.setPaddingLeft(8f);
  220. cell1.setPaddingRight(8f);
  221. cell1.setPaddingBottom(8f);
  222. cell1.setPaddingTop(8f);
  223. cell1.setColspan(6);
  224. cell1.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
  225. cell1.addElement(imageTable1);
  226. table.addCell(cell1);
  227. //签字区域
  228. PdfPCell signCell = new PdfPCell();
  229. signCell.setColspan(6);
  230. Paragraph signParagraph = new Paragraph();
  231. signParagraph.add(new Chunk("参会演练人员(签字):", tableFont));
  232. signCell.addElement(signParagraph);
  233. signCell.setBorder(Rectangle.LEFT | Rectangle.RIGHT);
  234. table.addCell(signCell);
  235. //图片填充
  236. final PdfPTable imageTable = getImage((List<String>) data.get("image"), 6);
  237. final PdfPCell cell = new PdfPCell();
  238. cell.setNoWrap(false);
  239. cell.setPaddingLeft(8f);
  240. cell.setPaddingRight(8f);
  241. cell.setPaddingBottom(8f);
  242. cell.setPaddingTop(8f);
  243. cell.setColspan(6);
  244. cell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM);
  245. cell.addElement(imageTable);
  246. table.addCell(cell);
  247. //第三行
  248. createPDFCell(tableFont, table, "记录人", Element.ALIGN_CENTER, 1, 1);
  249. createPDFCell(tableFont, table, data.get("recorderName").toString(), Element.ALIGN_CENTER, 5, 1);
  250. /* //第三行
  251. createPDFCell(tableFont, table, "参会人员签字", Element.ALIGN_CENTER, 1, 1);
  252. createPDFCell(tableFont, table, data.get("users").toString(), Element.ALIGN_CENTER, 5, 1);*/
  253. document.add(table);
  254. }
  255. public static Image getImage(String image) throws Exception {
  256. Image imageData = null;
  257. if (image.contains("black.png")) {
  258. final ApplicationContext applicationContext = SpringUtil.getApplicationContext();
  259. final Resource[] resources = applicationContext.getResources("classpath:file/black.png");
  260. imageData = Image.getInstance(resources[0].getURL());
  261. } else {
  262. try {
  263. imageData = convertFileToByteArray(new File(image));
  264. } catch (IOException e) {
  265. //此处如果未能读取到图片则放弃,选择使用空白图片来填充,继续生成pdf
  266. log.error("读取图片失败,图片路径:{}", image);
  267. final ApplicationContext applicationContext = SpringUtil.getApplicationContext();
  268. final Resource[] resources = applicationContext.getResources("classpath:file/black.png");
  269. imageData = Image.getInstance(resources[0].getURL());
  270. }
  271. }
  272. imageData.scaleAbsolute(100, 100);
  273. return imageData;
  274. }
  275. private static PdfPTable getImage(List<String> images, int totalImages) throws Exception {
  276. if (images == null) {
  277. images = new ArrayList<>();
  278. }
  279. PdfPTable innerTable = new PdfPTable(3);
  280. //这里根据实际图片数量来判断是否需要补充白色图片,保证每行显示3张图片,用以填充空白
  281. final int reallySize = images.size();
  282. List<String> list = new ArrayList<>(images);
  283. for (int i = 0; i < totalImages - reallySize && totalImages > reallySize; i++) {
  284. list.add("black.png");
  285. }
  286. //分割,每行显示3张图片,获取分割的行数
  287. List<List<String>> rows = new ArrayList<>();
  288. for (int i = 0; i < list.size(); i += 3) {
  289. List<String> row = list.subList(i, Math.min(i + 3, list.size()));
  290. rows.add(row);
  291. }
  292. for (List<String> row : rows) {
  293. for (String image : row) {
  294. Image imageData = null;
  295. try {
  296. imageData= getImage(image);
  297. } catch (Exception e) {
  298. final ApplicationContext applicationContext = SpringUtil.getApplicationContext();
  299. final Resource[] resources = applicationContext.getResources("classpath:file/black.png");
  300. imageData = Image.getInstance(resources[0].getURL());
  301. }
  302. imageData.scaleAbsolute(100, 100);
  303. PdfPCell cell = new PdfPCell(imageData);
  304. cell.setBorder(Rectangle.NO_BORDER);
  305. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  306. cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  307. innerTable.addCell(cell);
  308. }
  309. //实际上这儿永远不会存在不满足3个的情况,因为上面会根据图片数量补全到十二个
  310. //具体补全数量可以根据实际图片大小与页面尺寸来调整
  311. int size = row.size();
  312. while (size < 3) {
  313. PdfPCell emptyCell = new PdfPCell();
  314. emptyCell.setBorder(Rectangle.NO_BORDER);
  315. innerTable.addCell(emptyCell);
  316. size++;
  317. }
  318. }
  319. PdfPTable outerTable = new PdfPTable(1);
  320. PdfPCell innerCell = new PdfPCell(innerTable);
  321. innerCell.setBorder(Rectangle.NO_BORDER);
  322. outerTable.addCell(innerCell);
  323. return outerTable;
  324. }
  325. public static Image convertFileToByteArray(File file) throws Exception {
  326. try {
  327. FileInputStream fis = new FileInputStream(file);
  328. byte[] byteArray = new byte[(int) file.length()];
  329. fis.read(byteArray);
  330. fis.close();
  331. return Image.getInstance(byteArray);
  332. } catch (IOException e) {
  333. return getLocalImage();
  334. }
  335. }
  336. private static Image getLocalImage() {
  337. try {
  338. final ApplicationContext applicationContext = SpringUtil.getApplicationContext();
  339. final Resource[] resources = applicationContext.getResources("classpath:file/black.png");
  340. return Image.getInstance(resources[0].getURL());
  341. } catch (IOException | BadElementException e) {
  342. throw new RuntimeException(e);
  343. }
  344. }
  345. }