当前位置:   article > 正文

导出pdf 加密、加水印、加页脚

导出pdf 加密、加水印、加页脚

1.依赖

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.65</version>
        </dependency>
 

2.工具类 

  1. import com.itextpdf.text.*;
  2. import com.itextpdf.text.pdf.*;
  3. import lombok.SneakyThrows;
  4. import java.io.IOException;
  5. public class PdfPageSongTiUtil extends PdfPageEventHelper {
  6. /**
  7. * 文档字体大小,页脚页眉最好和文本大小一致
  8. */
  9. public int presentFontSize = 10;
  10. /**
  11. * 文档页面大小,最好前面传入,否则默认为A4纸张
  12. */
  13. public Rectangle pageSize = PageSize.A4;
  14. // 模板
  15. public PdfTemplate total;
  16. // 基础字体对象
  17. public BaseFont bf = null;
  18. // 利用基础字体生成的字体对象,一般用于生成中文文字
  19. public Font fontDetail = null;
  20. /**
  21. *
  22. * 无参构造方法.
  23. *
  24. */
  25. public PdfPageSongTiUtil() {
  26. }
  27. public PdfPageSongTiUtil(int presentFontSize, Rectangle pageSize) {
  28. this.presentFontSize = presentFontSize;
  29. this.pageSize = pageSize;
  30. }
  31. public void setPresentFontSize(int presentFontSize) {
  32. this.presentFontSize = presentFontSize;
  33. }
  34. /**
  35. *
  36. * 文档打开时创建模板
  37. */
  38. @Override
  39. public void onOpenDocument(PdfWriter writer, Document document) {
  40. // 共 页 的矩形的长宽高
  41. total = writer.getDirectContent().createTemplate(50, 50);
  42. }
  43. /**
  44. *
  45. *关闭每页的时候,写入页眉
  46. */
  47. @SneakyThrows
  48. @Override
  49. public void onEndPage(PdfWriter writer, Document document) {
  50. this.addPage(writer, document);
  51. }
  52. //加分页
  53. public void addPage(PdfWriter writer, Document document) throws IOException, DocumentException {
  54. //设置分页页眉页脚字体
  55. try {
  56. if (bf == null) {
  57. bf = BaseFont.createFont("template/GB2312.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  58. }
  59. if (fontDetail == null) {
  60. fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
  61. }
  62. } catch (DocumentException e) {
  63. e.printStackTrace();
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. }
  67. // 1.写入页眉
  68. // ColumnText.showTextAligned(writer.getDirectContent(),
  69. // Element.ALIGN_LEFT, new Phrase(header, fontDetail),
  70. // document.left(), document.top() + 20, 0);
  71. // 2.写入前半部分的 第 X页/
  72. Phrase footer = new Phrase("来源:中学生统一服务平台", fontDetail);
  73. // 4.拿到当前的PdfContentByte
  74. PdfContentByte cb = writer.getDirectContent();
  75. // 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F
  76. ColumnText
  77. .showTextAligned(
  78. cb,
  79. Element.ALIGN_CENTER,
  80. footer,
  81. document.right()-document.rightMargin()-5 ,
  82. document.bottom() - 10, 0);
  83. // 调节模版显示的位置
  84. //加水印
  85. addWatermark(writer);
  86. }
  87. /**
  88. *
  89. * 关闭文档时,替换模板,完成整个页眉页脚组件
  90. */
  91. @Override
  92. public void onCloseDocument(PdfWriter writer, Document document) {
  93. // 关闭文档的时候,将模板替换成实际的 Y 值
  94. total.beginText();
  95. // 生成的模版的字体、颜色
  96. total.setFontAndSize(bf, presentFontSize);
  97. //页脚内容拼接 如 第1/2
  98. //String foot2 = " " + (writer.getPageNumber()) + " 页";
  99. //页脚内容拼接 如 第1/2
  100. String foot2 = String.valueOf(writer.getPageNumber());
  101. // 模版显示的内容
  102. total.showText(foot2);
  103. total.endText();
  104. total.closePath();
  105. }
  106. // 加水印
  107. public void addWatermark(PdfWriter writer) throws IOException, DocumentException {
  108. PdfContentByte waterMar = writer.getDirectContentUnder();
  109. String text="全国中学生会议";
  110. waterMar.beginText();
  111. PdfGState gs=new PdfGState();
  112. //透明度
  113. gs.setFillOpacity(0.2F);
  114. waterMar.setFontAndSize(BaseFont.createFont("template/GB2312.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED),12);
  115. waterMar.setGState(gs);
  116. for (int x = 0; x <=800; x+=200) {
  117. for (int y = 0; y < 800; y+=100) {
  118. //水印对齐方式 水印内容 x坐标 y坐标 旋转角度
  119. waterMar.showTextAligned(Element.ALIGN_RIGHT,text,x,y,35);
  120. }
  121. }
  122. waterMar.setColorFill(BaseColor.GRAY);
  123. waterMar.endText();
  124. waterMar.stroke();
  125. }
  126. }

3.实体类

  1. @Data
  2. public class PersonnelInfo {
  3. private String name;
  4. private String phoneNumber;
  5. private String sex;
  6. private String schoolName;
  7. private String workerPosition;
  8. private String workerDate;
  9. private String certificate;
  10. private String OtherCertificate;
  11. }

4. 例子

  1. @GetMapping(value = "/createFilePdf", produces = MediaType.APPLICATION_JSON_VALUE)
  2. public void createFilePdf(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
  3. request.getSession();
  4. response.setContentType("application/pdf;charset=UTF-8");
  5. response.setCharacterEncoding("utf-8");
  6. String fileName =URLEncoder.encode( "导出pdf人员登记表","UTF-8");
  7. response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName+".pdf");
  8. List<PersonnelInfo> list=new ArrayList<>();
  9. PersonnelInfo personnel=new PersonnelInfo();
  10. personnel.setName("张三");
  11. personnel.setSex("男");
  12. personnel.setPhoneNumber("1101001001");
  13. personnel.setSchoolName("清华附中");
  14. personnel.setWorkerPosition("北京");
  15. personnel.setWorkerDate("1999-12-12");
  16. personnel.setCertificate("特级数学老师");
  17. personnel.setOtherCertificate("二级心理咨询");
  18. list.add(personnel);
  19. // 定义全局的字体静态变量
  20. Font content = null;
  21. Font fontHead = null;
  22. try {
  23. // 不同字体(这里定义同一种字体:包含不同字号、不同style)
  24. BaseFont bfChinese = BaseFont.createFont("template/GB2312.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  25. content = new Font(bfChinese, 11, Font.NORMAL);
  26. //使用字体并给出颜色
  27. fontHead = new Font(bfChinese,20,Font.BOLD,BaseColor.BLACK);
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. Document document=new Document(new RectangleReadOnly(850F,590F));
  32. document.setMargins(50,50,45,45);
  33. PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
  34. //用户密码 保证不能修改 设置所有者密码即可
  35. String pwdUser="";
  36. //所有者密码
  37. String pwdOwn="18956723.";
  38. writer.setEncryption("".getBytes(),pwdOwn.getBytes(),PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
  39. //添加页脚、水印等
  40. PdfPageSongTiUtil myHeadFooter=new PdfPageSongTiUtil();
  41. writer.setPageEvent(myHeadFooter);
  42. //open
  43. document.open();
  44. Paragraph paragraphHead1=new Paragraph("人员信息列表",fontHead);
  45. paragraphHead1.setAlignment(Element.ALIGN_CENTER);
  46. document.add(paragraphHead1);
  47. document.add(new Paragraph("\n"));
  48. PdfPCell cellBg[]=new PdfPCell[2];
  49. float[] width={35f,30f};
  50. //创建表格
  51. PdfPTable table=new PdfPTable(width);
  52. table.setWidthPercentage(100.0f);
  53. //表格顶端文本
  54. PdfPCell celltTableTop[]=new PdfPCell[2];
  55. float[] widthTop={55f,15f};
  56. PdfPTable tableTop=new PdfPTable(widthTop);
  57. tableTop.setWidthPercentage(100.0f);
  58. celltTableTop[0]=new PdfPCell(new Paragraph("会议开班负责人(签字):",content));
  59. celltTableTop[0].setBorder(0);
  60. tableTop.addCell(celltTableTop[0]);
  61. celltTableTop[1]=new PdfPCell(new Paragraph("日期:",content));
  62. celltTableTop[1].setBorder(0);
  63. tableTop.addCell(celltTableTop[1]);
  64. document.add(tableTop);
  65. //数据列
  66. PdfPCell cell=null;
  67. //11列 人员表头
  68. float[] width2={10f,15f,10f,20f,25f,25f,25f,25f,25f};
  69. PdfPTable tabl2=new PdfPTable(width2);
  70. PdfPTableHeader pdfPTableHeader=new PdfPTableHeader();
  71. tabl2.setSpacingBefore(5f);
  72. tabl2.setWidthPercentage(100.0f);
  73. //表头 换页显示
  74. tabl2.setHeaderRows(1);
  75. tabl2.getDefaultCell().setHorizontalAlignment(1);
  76. List<String> listTitle=Arrays.asList("序号","姓名","性别","联系方式","工作地点","工作岗位","入职日期","教学相关资格证书","其他相关资质证书");
  77. for (String title : listTitle) {
  78. tabl2.addCell(createCell(title,content));
  79. }
  80. int index=0;
  81. for (PersonnelInfo personnelInfo : list) {
  82. index++;
  83. PdfPCell cel1=new PdfPCell(new Paragraph(String.valueOf(index),content));
  84. PdfPCell cel2=new PdfPCell(new Paragraph(personnelInfo.getName(),content));
  85. PdfPCell cel3=new PdfPCell(new Paragraph(personnelInfo.getSex(),content));
  86. PdfPCell cel4=new PdfPCell(new Paragraph(personnelInfo.getPhoneNumber(),content));
  87. PdfPCell cel5=new PdfPCell(new Paragraph(personnelInfo.getSchoolName(),content));
  88. PdfPCell cel6=new PdfPCell(new Paragraph(personnelInfo.getWorkerPosition(),content));
  89. PdfPCell cel7=new PdfPCell(new Paragraph(personnelInfo.getWorkerDate(),content));
  90. PdfPCell cel8=new PdfPCell(new Paragraph(personnelInfo.getCertificate(),content));
  91. PdfPCell cel9=new PdfPCell(new Paragraph(personnelInfo.getOtherCertificate(),content));
  92. cel1.setVerticalAlignment(Element.ALIGN_MIDDLE);
  93. cel1.setHorizontalAlignment(Element.ALIGN_CENTER);
  94. cel2.setVerticalAlignment(Element.ALIGN_MIDDLE);
  95. cel2.setHorizontalAlignment(Element.ALIGN_CENTER);
  96. cel3.setVerticalAlignment(Element.ALIGN_MIDDLE);
  97. cel3.setHorizontalAlignment(Element.ALIGN_CENTER);
  98. cel4.setVerticalAlignment(Element.ALIGN_MIDDLE);
  99. cel4.setHorizontalAlignment(Element.ALIGN_CENTER);
  100. cel5.setVerticalAlignment(Element.ALIGN_MIDDLE);
  101. cel5.setHorizontalAlignment(Element.ALIGN_CENTER);
  102. cel6.setVerticalAlignment(Element.ALIGN_MIDDLE);
  103. cel6.setHorizontalAlignment(Element.ALIGN_CENTER);
  104. cel7.setVerticalAlignment(Element.ALIGN_MIDDLE);
  105. cel7.setHorizontalAlignment(Element.ALIGN_CENTER);
  106. cel8.setVerticalAlignment(Element.ALIGN_MIDDLE);
  107. cel8.setHorizontalAlignment(Element.ALIGN_CENTER);
  108. cel9.setVerticalAlignment(Element.ALIGN_MIDDLE);
  109. cel9.setHorizontalAlignment(Element.ALIGN_CENTER);
  110. tabl2.addCell(cel1);
  111. tabl2.addCell(cel2);
  112. tabl2.addCell(cel3);
  113. tabl2.addCell(cel4);
  114. tabl2.addCell(cel5);
  115. tabl2.addCell(cel6);
  116. tabl2.addCell(cel7);
  117. tabl2.addCell(cel8);
  118. tabl2.addCell(cel9);
  119. }
  120. document.add(tabl2);
  121. Paragraph paragraphEnd1=new Paragraph("会议结束负责人签字:",content);
  122. paragraphEnd1.setIndentationLeft(460);
  123. paragraphEnd1.setSpacingBefore(10f);
  124. document.add(paragraphEnd1);
  125. //close
  126. document.close();
  127. }
  128. /**
  129. *
  130. * @param cont 表头
  131. * @param font 字体
  132. * @return
  133. */
  134. static PdfPCell createCell(String cont,Font font){
  135. PdfPCell cell=new PdfPCell(new Paragraph(cont,font));
  136. cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
  137. cell.setHorizontalAlignment(Element.ALIGN_CENTER);
  138. cell.setFixedHeight(30);
  139. cell.setBackgroundColor(new BaseColor(153,203,255));
  140. return cell;
  141. }

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

闽ICP备14008679号