Java生成PDF文件(附PDF文档)

以你之姓@ 2023-02-14 06:59 133阅读 0赞

pom依赖

  1. <dependency>
  2. <groupId>com.itextpdf</groupId>
  3. <artifactId>itext-asian</artifactId>
  4. <version>5.2.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.itextpdf</groupId>
  8. <artifactId>itextpdf</artifactId>
  9. <version>5.4.3</version>
  10. </dependency>

直接上代码

  1. import com.itextpdf.text.*;
  2. import com.itextpdf.text.pdf.*;
  3. import com.sun.prism.paint.Color;
  4. import java.io.File;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.net.MalformedURLException;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Date;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. /** * 生成PDF文件 * */
  13. public class PDFReportUtil {
  14. private static Font headFont;// 设置字体大小
  15. private static Font keyFont;// 设置字体大小
  16. private static Font textFont;// 设置字体大小
  17. private static Font infoFont;// 设置字体大小
  18. private static Font redTextFont;// 设置字体大小
  19. private static Font redInfoFont;// 设置字体大小
  20. private static Font bigFont;// 设置字体大小
  21. private static Font titleFont;// 设置字体大小
  22. private static Font grayFont;// 设置字体大小
  23. private static Font font2;// 设置字体大小
  24. private int maxWidth = 540;
  25. /** * UniGB-UCS2-H:横向字体 * UniGB-UCS2-V:竖向字体 */
  26. static {
  27. BaseFont bfChinese;
  28. try {
  29. // UniGB-UCS2-H 横向字体
  30. bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  31. headFont = new Font(bfChinese, 10, Font.BOLD);// 设置字体大小
  32. bigFont = new Font(bfChinese, 18, Font.BOLD);// 设置字体大小
  33. keyFont = new Font(bfChinese, 9, Font.BOLD);// 设置字体大小
  34. titleFont = new Font(bfChinese, 14, Font.NORMAL);// 设置字体大小
  35. textFont = new Font(bfChinese, 9, Font.NORMAL);// 设置字体大小
  36. font2 = new Font(bfChinese, 7, Font.NORMAL);// 设置字体大小
  37. infoFont = new Font(bfChinese, 9, Font.NORMAL);// 设置字体大小
  38. redTextFont = new Font(bfChinese, 9, Font.NORMAL, BaseColor.RED);// 红色字体
  39. redInfoFont = new Font(bfChinese, 9, Font.NORMAL, BaseColor.RED);// 红色字体
  40. grayFont = new Font(bfChinese, 9, Font.NORMAL, BaseColor.GRAY);// 灰色字体
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. /** * 生成PDF文件 * * @param map 文件内容 * @return * @throws MalformedURLException * @throws IOException * @throws DocumentException */
  46. public void generatePDF(File file, Map<String, Object> map)
  47. throws MalformedURLException, IOException, DocumentException {
  48. Document doc = null;
  49. try {
  50. //创建Document对象
  51. doc = new Document();
  52. doc.setMargins(20, 20, 30, 30);
  53. SimpleDateFormat sf = new SimpleDateFormat("yyyy.MM.dd");
  54. //创建书写器
  55. PdfWriter.getInstance(doc, new FileOutputStream(file));
  56. // // 添加页眉页脚
  57. // String headertitle = "*****报告" + " " + "*******";
  58. // addheaderandfooter(doc, chinese, headertitle);
  59. //添加标题作者信息
  60. doc.addAuthor("java@pdf");
  61. doc.addTitle("ceshi");
  62. //打开文档。
  63. doc.open();
  64. //初始化pdf基本功能性文本
  65. Image image = null;
  66. PdfPTable table;
  67. PdfPCell cell = null;
  68. Paragraph paragraph = null;
  69. // 准备工作结束,进行文档内容填充:
  70. // 添加公司logo图片
  71. // table = new PdfPTable(1);
  72. // String picpath = NewCorpReportMap.get("reportLogoFilePath").toString();
  73. // addpicture(table, image, picpath, cell, doc);
  74. // 添加报告信息
  75. title(paragraph, "某某科技公司", "张三客户", textFont, bigFont, doc);
  76. // //****************表格
  77. PdfPTable table2 = new PdfPTable(5);
  78. table2.setTotalWidth(maxWidth);
  79. int[] with = { 120, 120, 100, 100, 100};
  80. table2.setWidths(with);
  81. table2.setLockedWidth(true);
  82. table2.setHorizontalAlignment(Element.ALIGN_CENTER);
  83. table2.getDefaultCell().setBorder(1);
  84. table2.addCell(createCell("学生信息列表:", keyFont, Element.ALIGN_LEFT, 5, false));
  85. table2.addCell(createCell("姓名", keyFont, Element.ALIGN_CENTER));
  86. table2.addCell(createCell("年龄", keyFont, Element.ALIGN_CENTER));
  87. table2.addCell(createCell("性别", keyFont, Element.ALIGN_CENTER));
  88. table2.addCell(createCell("住址", keyFont, Element.ALIGN_CENTER));
  89. table2.addCell(createCell("学生总人数", keyFont, Element.ALIGN_CENTER));
  90. int count = 5;
  91. for (int i = 0; i < count; i++) {
  92. table2.addCell(createCell("姓名" + i, textFont));
  93. table2.addCell(createCell(i + 15 + "", textFont));
  94. table2.addCell(createCell((i % 2 == 0) ? "男" : "女", textFont));
  95. table2.addCell(createCell("地址" + i, textFont));
  96. if (i == 0) {
  97. table2.addCell(createCell2(count + "", textFont, Element.ALIGN_CENTER, count, true));
  98. }
  99. }
  100. doc.add(table2);
  101. // //****************表格
  102. // 第三页 报告摘要,每页空2行留给页眉
  103. doc.add(new Paragraph(" ", keyFont));
  104. doc.add(new Paragraph(" ", keyFont));
  105. doc.newPage();
  106. } catch (Exception e) {
  107. e.printStackTrace();
  108. } finally {
  109. doc.close();
  110. }
  111. }
  112. /**
  113. * 给pdf文件添加水印
  114. *
  115. * @param InPdfFile 要加水印的原pdf文件路径
  116. * @param outPdfFile 加了水印后要输出的路径
  117. * // * @param object
  118. * // * 水印图片路径
  119. * // * @param pageSize
  120. * // * 原pdf文件的总页数(该方法是我当初将数据导入excel中然后再转换成pdf所以我这里的值是用excel的行数计算出来的,
  121. * // * 如果不是我这种可以 直接用reader.getNumberOfPages()获取pdf的总页数)
  122. * @throws Exception
  123. */
  124. public static void addPdfMark(String InPdfFile, String outPdfFile, String readpicturepath) throws Exception {
  125. PdfReader reader = new PdfReader(InPdfFile);
  126. int pageSize = reader.getNumberOfPages();
  127. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));
  128. Image img = Image.getInstance(readpicturepath);// 插入水印
  129. img.setAbsolutePosition(0, 0);
  130. for (int i = 1; i <= pageSize; i++) {
  131. PdfContentByte under = stamp.getUnderContent(i);
  132. under.addImage(img);
  133. }
  134. stamp.close();// 关闭
  135. File tempfile = new File(InPdfFile);
  136. if (tempfile.exists()) {
  137. tempfile.delete();
  138. }
  139. }
  140. // paragraph的格式
  141. public static void geshi1(Paragraph paragraph, Document doc) throws DocumentException { // 段落的格式
  142. paragraph.setIndentationLeft(30);
  143. paragraph.setIndentationRight(30);
  144. paragraph.setFirstLineIndent(20f);
  145. paragraph.setSpacingAfter(10f);
  146. paragraph.setSpacingBefore(10f);
  147. doc.add(paragraph);
  148. }
  149. // 居右无边框的cell
  150. public static void geshi3(PdfPCell cell, PdfPTable table) throws DocumentException { // 表格的格式
  151. cell.setBorder(PdfPCell.NO_BORDER);
  152. cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
  153. cell.setVerticalAlignment(PdfPCell.ALIGN_RIGHT);
  154. cell.setVerticalAlignment(PdfPCell.ALIGN_RIGHT);
  155. table.addCell(cell);
  156. }
  157. // 居中无边框的cell
  158. public static void geshi2(PdfPCell cell, PdfPTable table) throws DocumentException { // 表格的格式
  159. cell.setBorder(PdfPCell.NO_BORDER);
  160. cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
  161. cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
  162. cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
  163. table.addCell(cell);
  164. }
  165. // 不居中无边框的cell
  166. public static void geshi12(PdfPCell cell, PdfPTable table) throws DocumentException { // 表格的格式
  167. cell.setBorder(PdfPCell.NO_BORDER);
  168. table.addCell(cell);
  169. }
  170. // 居中有边框的cell
  171. public static void geshi22(PdfPCell cell, PdfPTable table) throws DocumentException { // 表格的格式
  172. cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
  173. cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
  174. cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
  175. table.addCell(cell);
  176. }
  177. // 居中有边框的cell
  178. public static void geshi32(PdfPCell cell, PdfPTable table) throws DocumentException { // 表格的格式
  179. cell.setColspan(3);
  180. cell.setBorder(0);
  181. table.addCell(cell);
  182. }
  183. // 设置字体
  184. public static Font setfont(String fonttype, float fontsize, int fontflag, Color fontcolor, int fontstyle)
  185. throws DocumentException, IOException {
  186. BaseFont baseFont5 = BaseFont.createFont(fonttype, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  187. Font font = new Font(baseFont5, fontsize, fontflag);
  188. font.setColor(BaseColor.BLACK);
  189. if (fontstyle != 0) { // 如果传参为0不设置字体
  190. font.setStyle(fontstyle);
  191. }
  192. return font;
  193. }
  194. // 插入图片
  195. public static void addPicture(PdfPTable table, Image image, String picpath, PdfPCell cell, Document doc)
  196. throws MalformedURLException, IOException, DocumentException {
  197. image = Image.getInstance(picpath);
  198. //图片尺寸
  199. image.scaleAbsolute(75, 75);
  200. cell = new PdfPCell(image);
  201. geshi3(cell, table);
  202. doc.add(table);
  203. }
  204. // 首页--固定格式布局
  205. public static void title(Paragraph paragraph, String company, String cusName,
  206. Font myfont, Font myfont3, Document doc) throws DocumentException {
  207. paragraph = new Paragraph(cusName + company, myfont3);// 公司名
  208. paragraph.setAlignment(1);
  209. doc.add(paragraph);
  210. doc.add(new Paragraph(" ", myfont));
  211. doc.add(new Paragraph(" ", myfont));
  212. }
  213. //非空判断
  214. public static String isNull(Object a) {
  215. if (a == null || a.equals("null")) {
  216. return "";
  217. } else {
  218. return a + "";
  219. }
  220. }
  221. /** * 创建单元格 * * @param value 文本 * @param font 字体 * @param align 对齐方式 0-左对齐 1-居中 2-右对齐 * @return */
  222. public PdfPCell createCell(String value, Font font, int align) {
  223. PdfPCell cell = new PdfPCell();
  224. cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  225. cell.setHorizontalAlignment(align);
  226. cell.setPhrase(new Phrase(value, font));
  227. cell.setPaddingTop(4.0f);
  228. cell.setPaddingBottom(5.0f);
  229. return cell;
  230. }
  231. /** * 无边框 居左 * * @param value * @param font * @param * @return */
  232. public PdfPCell createCell3(String value, Font font) {
  233. PdfPCell cell = new PdfPCell();
  234. cell.setVerticalAlignment(Element.ALIGN_LEFT);
  235. cell.setHorizontalAlignment(0);//居左
  236. cell.setPhrase(new Phrase(value, font));
  237. //无边框
  238. cell.setBorder(0);
  239. cell.setPaddingTop(1.0f);
  240. cell.setPaddingBottom(10.0f);
  241. return cell;
  242. }
  243. /** * 无边框 * * @param value * @param font * @param align 0-居左 1-居中 2-居右 * @return */
  244. public PdfPCell createCell4(String value, Font font, int align) {
  245. PdfPCell cell = new PdfPCell();
  246. cell.setVerticalAlignment(Element.ALIGN_RIGHT);
  247. cell.setHorizontalAlignment(align);//居右
  248. cell.setPhrase(new Phrase(value, font));
  249. //无边框
  250. cell.setBorder(0);
  251. cell.setPaddingTop(1.0f);
  252. cell.setPaddingBottom(10.0f);
  253. return cell;
  254. }
  255. /** * @param value 文本 * @param font 字体 * @return */
  256. public PdfPCell createCell(String value, Font font) {
  257. PdfPCell cell = new PdfPCell();
  258. cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  259. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  260. cell.setPhrase(new Phrase(value, font));
  261. return cell;
  262. }
  263. /** * @param value 文本 * @param font 字体 * @param align 对齐方式 0-左对齐 1-居中 2-右对齐 * @param colspan 合并列 * @param boderFlag 是否有边框 * @return */
  264. public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
  265. PdfPCell cell = new PdfPCell();
  266. cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  267. cell.setHorizontalAlignment(align);
  268. cell.setColspan(colspan);
  269. cell.setPhrase(new Phrase(value, font));
  270. cell.setPadding(3.0f);
  271. if (!boderFlag) {
  272. cell.setBorder(0);
  273. cell.setPaddingTop(15.0f);
  274. cell.setPaddingBottom(8.0f);
  275. }
  276. return cell;
  277. }
  278. /** * @param value 文本 * @param font 字体 * @param align 对齐方式 0-左对齐 1-居中 2-右对齐 * @param rowspan 合并行 * @param boderFlag 是否有边框 * @return */
  279. public PdfPCell createCell2(String value, Font font, int align, int rowspan, boolean boderFlag) {
  280. PdfPCell cell = new PdfPCell();
  281. cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  282. cell.setHorizontalAlignment(align);
  283. cell.setRowspan(rowspan);
  284. cell.setPhrase(new Phrase(value, font));
  285. cell.setPadding(3.0f);
  286. if (!boderFlag) {
  287. cell.setBorder(0);
  288. cell.setPaddingTop(15.0f);
  289. cell.setPaddingBottom(8.0f);
  290. }
  291. return cell;
  292. }
  293. public static void main(String[] args) throws IOException, DocumentException {
  294. Map<String, Object> map = new HashMap<>();
  295. new PDFReportUtil().generatePDF(new File("D:/temp/测试.pdf"), map);
  296. System.out.println("pdf已生成");
  297. }
  298. }

效果展示:
在这里插入图片描述

PDF中文帮助文档
Paragraph API
Phrase API

开心一刻

不小心把50块钱投进去了,司机说我没权打开,只能收后面上来人的散钱了,收到了48块刚好进站有一人要上车,我马上伸手说给钱,他一愣说不是无人售票么,我说快点,司机和车上的人都说快点(他们知道我怎么回事),后面这大哥直接把钱包扔给我说:你们人多,我就这点钱了。然后就跑了……跑了……了

在这里插入图片描述

相关链接
https://blog.csdn.net/weixin\_37848710/article/details/89522862

发表评论

表情:
评论列表 (有 0 条评论,133人围观)

还没有评论,来说两句吧...

相关阅读