当前位置:   article > 正文

java 通过itext生成pdf (干货教学)

java 通过itext生成pdf (干货教学)

我们经常会遇到要导出pdf的需求,方式有很多种  今天的教程是采用itext的方式生成pdf


先来看一下效果

OK,下面开始教程

1.准备工作-下载相关依赖

  1. <!--itext相关-->
  2. <dependency>
  3. <groupId>com.itextpdf</groupId>
  4. <artifactId>kernel</artifactId>
  5. <version>7.0.3</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.itextpdf</groupId>
  9. <artifactId>io</artifactId>
  10. <version>7.0.3</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.itextpdf</groupId>
  14. <artifactId>layout</artifactId>
  15. <version>7.0.3</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>com.itextpdf</groupId>
  19. <artifactId>font-asian</artifactId>
  20. <version>7.0.3</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>com.itextpdf</groupId>
  24. <artifactId>pdfa</artifactId>
  25. <version>7.0.3</version>
  26. </dependency>

2.创建实体对象

  1. package com.example.demo.entity;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. /**
  6. * @Author: Mr.Z
  7. * @Date: 2024年03月22日 14:53
  8. **/
  9. @Data
  10. @AllArgsConstructor
  11. @NoArgsConstructor
  12. public class ChildInfo {
  13. /**
  14. * 幼儿姓名
  15. */
  16. private String stuName;
  17. /**
  18. * 性别
  19. */
  20. private String sex;
  21. /**
  22. * 是否独生子女
  23. */
  24. private String onlyChild;
  25. /**
  26. * 血型
  27. */
  28. private String blood;
  29. /**
  30. * 幼儿身份证号
  31. */
  32. private String stuIdCard;
  33. /**
  34. * 幼儿出生日期
  35. */
  36. private String stuDate;
  37. /**
  38. * 民族
  39. */
  40. private String nation;
  41. /**
  42. * 幼儿照片
  43. */
  44. private String childPic;
  45. /**
  46. * 幼儿籍贯
  47. *
  48. */
  49. private String nativePlace;
  50. /**
  51. * 出生所在地
  52. */
  53. private String birthPlace;
  54. /**
  55. * 幼儿户籍地区码
  56. */
  57. private String nativeCode;
  58. }

3.编写pdf样式及内容,这里相关介绍我都写到注释里面了,很详细

  1. package com.example.demo.service.impl;
  2. import com.example.demo.entity.ChildInfo;
  3. import com.itextpdf.io.image.ImageDataFactory;
  4. import com.itextpdf.kernel.color.Color;
  5. import com.itextpdf.kernel.color.DeviceRgb;
  6. import com.itextpdf.kernel.font.PdfFont;
  7. import com.itextpdf.kernel.font.PdfFontFactory;
  8. import com.itextpdf.kernel.pdf.PdfDocument;
  9. import com.itextpdf.kernel.pdf.PdfWriter;
  10. import com.itextpdf.layout.Document;
  11. import com.itextpdf.layout.element.Cell;
  12. import com.itextpdf.layout.element.Image;
  13. import com.itextpdf.layout.element.Paragraph;
  14. import com.itextpdf.layout.element.Table;
  15. import com.itextpdf.layout.property.TextAlignment;
  16. import org.springframework.stereotype.Service;
  17. import javax.servlet.http.HttpServletResponse;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import java.util.UUID;
  22. /**
  23. * @Author: Mr.Z
  24. * @Date: 2024年03月22日 9:37
  25. **/
  26. @Service
  27. public class ItextPdfServiceImpl {
  28. /**
  29. * 下载到本地
  30. * @param stu
  31. * @throws IOException
  32. */
  33. public void downLoad(ChildInfo stu) throws IOException {
  34. //获取项目根路径
  35. String baseUrl=System.getProperty("user.dir")+"/";
  36. //随机命名
  37. String templateUUId = UUID.randomUUID().toString();
  38. //生成的pdf路径+名称
  39. String pdf = baseUrl+templateUUId+".pdf";
  40. //1、创建流对象
  41. PdfWriter pdfWriter=new PdfWriter(new File(pdf));
  42. //2、创建文档对象
  43. PdfDocument pdfDocument=new PdfDocument(pdfWriter);
  44. //3、创建内容文档对象
  45. Document document=new Document(pdfDocument);
  46. //创建内容
  47. Paragraph paragraph=new Paragraph("报名信息");
  48. //设置字体,解决中文显示问题
  49. PdfFont font= PdfFontFactory.createFont("STSongStd-Light","UniGB-UCS2-H",true);
  50. paragraph.setFont(font);
  51. paragraph.setTextAlignment(TextAlignment.CENTER);//居中
  52. document.add(paragraph);
  53. //设置表格每列宽度
  54. Table table=new Table(new float[]{108,65,35,50,90,70,40,40,80});
  55. //设置表格宽度百分比
  56. table.setWidthPercent(100);
  57. //创建表头
  58. Cell head=new Cell(1,9); //一行9列
  59. //创建标题
  60. Color customColor = new DeviceRgb(255, 165, 0); //这是一个橙色示例,您可以替换为其他RGB值
  61. head.add(new Paragraph("幼儿身份信息"))
  62. .setFont(font) // 设置字体
  63. .setTextAlignment(TextAlignment.LEFT) // 居左
  64. .setBackgroundColor(customColor); // 设置自定义背景颜色
  65. Cell cell1=new Cell().add(new Paragraph("姓名").setFont(font));
  66. Cell cell2=new Cell().add(new Paragraph(stu.getStuName()).setFont(font));
  67. Cell cell3=new Cell().add(new Paragraph("性别").setFont(font));
  68. Cell cell4=new Cell().add(new Paragraph(stu.getSex()).setFont(font));
  69. Cell cell5=new Cell().add(new Paragraph("是否独生子女").setFont(font));
  70. Cell cell6=new Cell().add(new Paragraph(stu.getOnlyChild()).setFont(font));
  71. Cell cell7=new Cell().add(new Paragraph("血型").setFont(font));
  72. Cell cell8=new Cell().add(new Paragraph(stu.getBlood()).setFont(font));
  73. table.addCell(cell1);
  74. table.addCell(cell2);
  75. table.addCell(cell3);
  76. table.addCell(cell4);
  77. table.addCell(cell5);
  78. table.addCell(cell6);
  79. table.addCell(cell7);
  80. table.addCell(cell8);
  81. //加入表格
  82. table.addHeaderCell(head);
  83. table.addHeaderCell(new Cell(1,9));//一行9列
  84. //加入图片
  85. String picUrl = stu.getChildPic();
  86. Image image=new Image(ImageDataFactory.create(picUrl));
  87. //设置图片缩放比例 水平 垂直
  88. //image.scale(0.5f,0.5f);
  89. float scaledWidth =60; // 设置宽度(毫米)
  90. float scaledHeight = 150; // 设置高度(毫米)
  91. image.scaleToFit(scaledWidth, scaledHeight);
  92. /**
  93. * 这里解释一下new Cell(3,1)的意思 相当于垂直合并一列的3行单元格
  94. * 其他单元格的合并都是如此进行调试
  95. */
  96. //将图片插入表格
  97. Cell cell9 = new Cell(3,1);
  98. cell9.add(image);
  99. table.addCell(cell9);
  100. table.addCell(new Cell().add(new Paragraph("身份证号码").setFont(font)));
  101. table.addCell(new Cell(1,3).add(new Paragraph(stu.getStuIdCard()).setFont(font)));
  102. table.addCell(new Cell().add(new Paragraph("幼儿出生日期").setFont(font)));
  103. table.addCell(new Cell().add(new Paragraph(stu.getStuDate()).setFont(font)));
  104. table.addCell(new Cell().add(new Paragraph("民族").setFont(font)));
  105. table.addCell(new Cell().add(new Paragraph(stu.getNation()).setFont(font)));
  106. table.addCell(new Cell().add(new Paragraph("幼儿籍贯").setFont(font)));
  107. table.addCell(new Cell(1,7).add(new Paragraph(stu.getNativePlace()).setFont(font)));
  108. table.addCell(new Cell().add(new Paragraph("出生所在地").setFont(font)));
  109. table.addCell(new Cell(1,8).add(new Paragraph(stu.getBirthPlace()).setFont(font)));
  110. table.addCell(new Cell().add(new Paragraph("幼儿户籍地区码").setFont(font)));
  111. table.addCell(new Cell(1,8).add(new Paragraph(stu.getNativeCode()).setFont(font)));
  112. Cell head2=new Cell(1,9); //一行9列
  113. //创建标题
  114. Color customColor2 = new DeviceRgb(0,255,0); //这是一个绿色示例,您可以替换为其他RGB值
  115. head2.add(new Paragraph("家长信息"))
  116. .setFont(font) // 设置字体
  117. .setTextAlignment(TextAlignment.LEFT) // 居左
  118. .setBackgroundColor(customColor2); // 设置自定义背景颜色
  119. table.addCell(head2);
  120. table.addCell(new Cell().add(new Paragraph("父母信息").setFont(font)));
  121. table.addCell(new Cell(1,8).add(new Paragraph("爸爸胡英俊,妈妈张小丽").setFont(font)));
  122. //输出表格
  123. document.add(table);
  124. document.close();
  125. System.out.println("pdf生成完成!");
  126. }
  127. /**
  128. * 生成流返回给浏览器
  129. */
  130. public void downLoadStream(ChildInfo stu, HttpServletResponse response) throws Exception {
  131. OutputStream os = response.getOutputStream();
  132. //1、创建流对象
  133. PdfWriter pdfWriter=new PdfWriter(os);
  134. //2、创建文档对象
  135. PdfDocument pdfDocument=new PdfDocument(pdfWriter);
  136. //3、创建内容文档对象
  137. Document document=new Document(pdfDocument);
  138. //创建内容
  139. Paragraph paragraph=new Paragraph("报名信息");
  140. //设置字体,解决中文显示问题
  141. PdfFont font= PdfFontFactory.createFont("STSongStd-Light","UniGB-UCS2-H",true);
  142. paragraph.setFont(font);
  143. paragraph.setTextAlignment(TextAlignment.CENTER);//居中
  144. document.add(paragraph);
  145. //设置表格每列宽度
  146. Table table=new Table(new float[]{108,65,35,50,90,70,40,40,80});
  147. //设置表格宽度百分比
  148. table.setWidthPercent(100);
  149. //创建表头
  150. Cell head=new Cell(1,9); //一行9列
  151. //创建标题
  152. Color customColor = new DeviceRgb(255, 165, 0); //这是一个橙色示例,您可以替换为其他RGB值
  153. head.add(new Paragraph("幼儿身份信息"))
  154. .setFont(font) // 设置字体
  155. .setTextAlignment(TextAlignment.LEFT) // 居左
  156. .setBackgroundColor(customColor); // 设置自定义背景颜色
  157. Cell cell1=new Cell().add(new Paragraph("姓名").setFont(font));
  158. Cell cell2=new Cell().add(new Paragraph(stu.getStuName()).setFont(font));
  159. Cell cell3=new Cell().add(new Paragraph("性别").setFont(font));
  160. Cell cell4=new Cell().add(new Paragraph(stu.getSex()).setFont(font));
  161. Cell cell5=new Cell().add(new Paragraph("是否独生子女").setFont(font));
  162. Cell cell6=new Cell().add(new Paragraph(stu.getOnlyChild()).setFont(font));
  163. Cell cell7=new Cell().add(new Paragraph("血型").setFont(font));
  164. Cell cell8=new Cell().add(new Paragraph(stu.getBlood()).setFont(font));
  165. table.addCell(cell1);
  166. table.addCell(cell2);
  167. table.addCell(cell3);
  168. table.addCell(cell4);
  169. table.addCell(cell5);
  170. table.addCell(cell6);
  171. table.addCell(cell7);
  172. table.addCell(cell8);
  173. //加入表格
  174. table.addHeaderCell(head);
  175. table.addHeaderCell(new Cell(1,9));//一行9列
  176. //加入图片
  177. String picUrl = stu.getChildPic();
  178. Image image=new Image(ImageDataFactory.create(picUrl));
  179. //设置图片缩放比例 水平 垂直
  180. //image.scale(0.5f,0.5f);
  181. float scaledWidth =60; // 设置宽度(毫米)
  182. float scaledHeight = 150; // 设置高度(毫米)
  183. image.scaleToFit(scaledWidth, scaledHeight);
  184. /**
  185. * 这里解释一下new Cell(3,1)的意思 相当于垂直合并一列的3行单元格
  186. * 其他单元格的合并都是如此进行调试
  187. */
  188. //将图片插入表格
  189. Cell cell9 = new Cell(3,1);
  190. cell9.add(image);
  191. table.addCell(cell9);
  192. table.addCell(new Cell().add(new Paragraph("身份证号码").setFont(font)));
  193. table.addCell(new Cell(1,3).add(new Paragraph(stu.getStuIdCard()).setFont(font)));
  194. table.addCell(new Cell().add(new Paragraph("幼儿出生日期").setFont(font)));
  195. table.addCell(new Cell().add(new Paragraph(stu.getStuDate()).setFont(font)));
  196. table.addCell(new Cell().add(new Paragraph("民族").setFont(font)));
  197. table.addCell(new Cell().add(new Paragraph(stu.getNation()).setFont(font)));
  198. table.addCell(new Cell().add(new Paragraph("幼儿籍贯").setFont(font)));
  199. table.addCell(new Cell(1,7).add(new Paragraph(stu.getNativePlace()).setFont(font)));
  200. table.addCell(new Cell().add(new Paragraph("出生所在地").setFont(font)));
  201. table.addCell(new Cell(1,8).add(new Paragraph(stu.getBirthPlace()).setFont(font)));
  202. table.addCell(new Cell().add(new Paragraph("幼儿户籍地区码").setFont(font)));
  203. table.addCell(new Cell(1,8).add(new Paragraph(stu.getNativeCode()).setFont(font)));
  204. Cell head2=new Cell(1,9); //一行9列
  205. //创建标题
  206. Color customColor2 = new DeviceRgb(0,255,0); //这是一个绿色示例,您可以替换为其他RGB值
  207. head2.add(new Paragraph("家长信息"))
  208. .setFont(font) // 设置字体
  209. .setTextAlignment(TextAlignment.LEFT) // 居左
  210. .setBackgroundColor(customColor2); // 设置自定义背景颜色
  211. table.addCell(head2);
  212. table.addCell(new Cell().add(new Paragraph("父母信息").setFont(font)));
  213. table.addCell(new Cell(1,8).add(new Paragraph("爸爸胡英俊,妈妈张小丽").setFont(font)));
  214. //输出表格
  215. document.add(table);
  216. // 设置响应头信息
  217. response.setContentType("application/pdf");
  218. response.setHeader("Content-disposition", "attachment;filename="+new String(stu.getStuName().getBytes("gb2312"),"iso-8859-1") + ".pdf");
  219. // 关闭文档,此时PDF内容已写入到HttpServletResponse的OutputStream
  220. document.close();
  221. os.close();
  222. System.out.println("pdf生成完成!");
  223. }
  224. }

4.调用示例   controller调用

  1. package com.example.demo.itext;
  2. import com.example.demo.entity.ChildInfo;
  3. import com.example.demo.service.impl.ItextPdfServiceImpl;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import javax.servlet.http.HttpServletResponse;
  9. /**
  10. * @Author: Mr.Z
  11. * @Date: 2024年03月22日 9:36
  12. **/
  13. @RestController
  14. @RequestMapping("/itext")
  15. public class ItextPdfController {
  16. @Autowired
  17. private ItextPdfServiceImpl itextPdfService;
  18. @GetMapping("/download")
  19. public void downLoad(HttpServletResponse response) throws Exception {
  20. ChildInfo childInfo = new ChildInfo();
  21. childInfo.setStuName("胡图图");
  22. childInfo.setSex("男");
  23. childInfo.setOnlyChild("是");
  24. childInfo.setBlood("O");
  25. childInfo.setStuIdCard("123456789987654321");
  26. childInfo.setStuDate("2018-05-20");
  27. childInfo.setNation("汉");
  28. childInfo.setNativePlace("翻斗花园");
  29. childInfo.setBirthPlace("翻斗人民医院");
  30. childInfo.setNativeCode("8899");
  31. childInfo.setChildPic("https://img2.baidu.com/it/u=294455873,3061678111&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1711213200&t=a29267da1ffde9810763fb027091cee0");
  32. itextPdfService.downLoadStream(childInfo,response);
  33. }
  34. }

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

闽ICP备14008679号