当前位置: 首页 > news >正文

导出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.工具类 

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;import java.io.IOException;public class PdfPageSongTiUtil extends PdfPageEventHelper {/*** 文档字体大小,页脚页眉最好和文本大小一致*/public int presentFontSize = 10;/*** 文档页面大小,最好前面传入,否则默认为A4纸张*/public Rectangle pageSize = PageSize.A4;// 模板public PdfTemplate total;// 基础字体对象public BaseFont bf = null;// 利用基础字体生成的字体对象,一般用于生成中文文字public Font fontDetail = null;/****  无参构造方法.**/public PdfPageSongTiUtil() {}public PdfPageSongTiUtil(int presentFontSize, Rectangle pageSize) {this.presentFontSize = presentFontSize;this.pageSize = pageSize;}public void setPresentFontSize(int presentFontSize) {this.presentFontSize = presentFontSize;}/**** 文档打开时创建模板*/@Overridepublic void onOpenDocument(PdfWriter writer, Document document) {// 共 页 的矩形的长宽高total = writer.getDirectContent().createTemplate(50, 50);}/****关闭每页的时候,写入页眉*/@SneakyThrows@Overridepublic void onEndPage(PdfWriter writer, Document document) {this.addPage(writer, document);}//加分页public void addPage(PdfWriter writer, Document document) throws IOException, DocumentException {//设置分页页眉页脚字体try {if (bf == null) {bf = BaseFont.createFont("template/GB2312.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);}if (fontDetail == null) {fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体}} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}// 1.写入页眉
//        ColumnText.showTextAligned(writer.getDirectContent(),
//                Element.ALIGN_LEFT, new Phrase(header, fontDetail),
//                document.left(), document.top() + 20, 0);// 2.写入前半部分的 第 X页/共Phrase footer = new Phrase("来源:中学生统一服务平台", fontDetail);// 4.拿到当前的PdfContentBytePdfContentByte cb = writer.getDirectContent();// 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0FColumnText.showTextAligned(cb,Element.ALIGN_CENTER,footer,document.right()-document.rightMargin()-5 ,document.bottom() - 10, 0);// 调节模版显示的位置//加水印addWatermark(writer);}/**** 关闭文档时,替换模板,完成整个页眉页脚组件*/@Overridepublic void onCloseDocument(PdfWriter writer, Document document) {// 关闭文档的时候,将模板替换成实际的 Y 值total.beginText();// 生成的模版的字体、颜色total.setFontAndSize(bf, presentFontSize);//页脚内容拼接  如  第1页/共2页//String foot2 = " " + (writer.getPageNumber()) + " 页";//页脚内容拼接  如  第1页/共2页String foot2 = String.valueOf(writer.getPageNumber());// 模版显示的内容total.showText(foot2);total.endText();total.closePath();}// 加水印public void addWatermark(PdfWriter writer) throws IOException, DocumentException {PdfContentByte waterMar = writer.getDirectContentUnder();String text="全国中学生会议";waterMar.beginText();PdfGState gs=new PdfGState();//透明度gs.setFillOpacity(0.2F);waterMar.setFontAndSize(BaseFont.createFont("template/GB2312.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED),12);waterMar.setGState(gs);for (int x = 0; x <=800; x+=200) {for (int y = 0; y < 800; y+=100) {//水印对齐方式 水印内容 x坐标 y坐标 旋转角度waterMar.showTextAligned(Element.ALIGN_RIGHT,text,x,y,35);}}waterMar.setColorFill(BaseColor.GRAY);waterMar.endText();waterMar.stroke();}}

3.实体类

@Data
public class PersonnelInfo {private String name;private String phoneNumber;private String sex;private String schoolName;private String workerPosition;private String workerDate;private String certificate;private String OtherCertificate;}

4. 例子

@GetMapping(value = "/createFilePdf", produces = MediaType.APPLICATION_JSON_VALUE)public void createFilePdf(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {request.getSession();response.setContentType("application/pdf;charset=UTF-8");response.setCharacterEncoding("utf-8");String fileName =URLEncoder.encode( "导出pdf人员登记表","UTF-8");response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName+".pdf");List<PersonnelInfo> list=new ArrayList<>();PersonnelInfo personnel=new PersonnelInfo();personnel.setName("张三");personnel.setSex("男");personnel.setPhoneNumber("1101001001");personnel.setSchoolName("清华附中");personnel.setWorkerPosition("北京");personnel.setWorkerDate("1999-12-12");personnel.setCertificate("特级数学老师");personnel.setOtherCertificate("二级心理咨询");list.add(personnel);// 定义全局的字体静态变量Font content = null;Font fontHead = null;try {// 不同字体(这里定义同一种字体:包含不同字号、不同style)BaseFont bfChinese = BaseFont.createFont("template/GB2312.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);content = new Font(bfChinese, 11, Font.NORMAL);//使用字体并给出颜色fontHead = new Font(bfChinese,20,Font.BOLD,BaseColor.BLACK);} catch (Exception e) {e.printStackTrace();}Document document=new Document(new RectangleReadOnly(850F,590F));document.setMargins(50,50,45,45);PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());//用户密码  保证不能修改 设置所有者密码即可String pwdUser="";//所有者密码String pwdOwn="18956723.";writer.setEncryption("".getBytes(),pwdOwn.getBytes(),PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);//添加页脚、水印等PdfPageSongTiUtil myHeadFooter=new PdfPageSongTiUtil();writer.setPageEvent(myHeadFooter);//opendocument.open();Paragraph paragraphHead1=new Paragraph("人员信息列表",fontHead);paragraphHead1.setAlignment(Element.ALIGN_CENTER);document.add(paragraphHead1);document.add(new Paragraph("\n"));PdfPCell cellBg[]=new PdfPCell[2];float[] width={35f,30f};//创建表格PdfPTable table=new PdfPTable(width);table.setWidthPercentage(100.0f);//表格顶端文本PdfPCell celltTableTop[]=new PdfPCell[2];float[] widthTop={55f,15f};PdfPTable tableTop=new PdfPTable(widthTop);tableTop.setWidthPercentage(100.0f);celltTableTop[0]=new PdfPCell(new Paragraph("会议开班负责人(签字):",content));celltTableTop[0].setBorder(0);tableTop.addCell(celltTableTop[0]);celltTableTop[1]=new PdfPCell(new Paragraph("日期:",content));celltTableTop[1].setBorder(0);tableTop.addCell(celltTableTop[1]);document.add(tableTop);//数据列PdfPCell cell=null;//11列  人员表头float[] width2={10f,15f,10f,20f,25f,25f,25f,25f,25f};PdfPTable tabl2=new PdfPTable(width2);PdfPTableHeader pdfPTableHeader=new PdfPTableHeader();tabl2.setSpacingBefore(5f);tabl2.setWidthPercentage(100.0f);//表头  换页显示tabl2.setHeaderRows(1);tabl2.getDefaultCell().setHorizontalAlignment(1);List<String> listTitle=Arrays.asList("序号","姓名","性别","联系方式","工作地点","工作岗位","入职日期","教学相关资格证书","其他相关资质证书");for (String title : listTitle) {tabl2.addCell(createCell(title,content));}int   index=0;for (PersonnelInfo personnelInfo : list) {index++;PdfPCell cel1=new PdfPCell(new Paragraph(String.valueOf(index),content));PdfPCell cel2=new PdfPCell(new Paragraph(personnelInfo.getName(),content));PdfPCell cel3=new PdfPCell(new Paragraph(personnelInfo.getSex(),content));PdfPCell cel4=new PdfPCell(new Paragraph(personnelInfo.getPhoneNumber(),content));PdfPCell cel5=new PdfPCell(new Paragraph(personnelInfo.getSchoolName(),content));PdfPCell cel6=new PdfPCell(new Paragraph(personnelInfo.getWorkerPosition(),content));PdfPCell cel7=new PdfPCell(new Paragraph(personnelInfo.getWorkerDate(),content));PdfPCell cel8=new PdfPCell(new Paragraph(personnelInfo.getCertificate(),content));PdfPCell cel9=new PdfPCell(new Paragraph(personnelInfo.getOtherCertificate(),content));cel1.setVerticalAlignment(Element.ALIGN_MIDDLE);cel1.setHorizontalAlignment(Element.ALIGN_CENTER);cel2.setVerticalAlignment(Element.ALIGN_MIDDLE);cel2.setHorizontalAlignment(Element.ALIGN_CENTER);cel3.setVerticalAlignment(Element.ALIGN_MIDDLE);cel3.setHorizontalAlignment(Element.ALIGN_CENTER);cel4.setVerticalAlignment(Element.ALIGN_MIDDLE);cel4.setHorizontalAlignment(Element.ALIGN_CENTER);cel5.setVerticalAlignment(Element.ALIGN_MIDDLE);cel5.setHorizontalAlignment(Element.ALIGN_CENTER);cel6.setVerticalAlignment(Element.ALIGN_MIDDLE);cel6.setHorizontalAlignment(Element.ALIGN_CENTER);cel7.setVerticalAlignment(Element.ALIGN_MIDDLE);cel7.setHorizontalAlignment(Element.ALIGN_CENTER);cel8.setVerticalAlignment(Element.ALIGN_MIDDLE);cel8.setHorizontalAlignment(Element.ALIGN_CENTER);cel9.setVerticalAlignment(Element.ALIGN_MIDDLE);cel9.setHorizontalAlignment(Element.ALIGN_CENTER);tabl2.addCell(cel1);tabl2.addCell(cel2);tabl2.addCell(cel3);tabl2.addCell(cel4);tabl2.addCell(cel5);tabl2.addCell(cel6);tabl2.addCell(cel7);tabl2.addCell(cel8);tabl2.addCell(cel9);}document.add(tabl2);Paragraph paragraphEnd1=new Paragraph("会议结束负责人签字:",content);paragraphEnd1.setIndentationLeft(460);paragraphEnd1.setSpacingBefore(10f);document.add(paragraphEnd1);//closedocument.close();}/**** @param cont  表头* @param font  字体* @return*/static  PdfPCell createCell(String cont,Font font){PdfPCell cell=new PdfPCell(new Paragraph(cont,font));cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setFixedHeight(30);cell.setBackgroundColor(new BaseColor(153,203,255));return cell;}

相关文章:

  • 计组学习笔记2024/2/5
  • 框架学习Maven
  • Gson源码解读
  • 自动化报告pptx-python|高效通过PPT模版制造报告(三)
  • Jupyter Notebook中的%matplotlib inline详解
  • A系统数据表同步到B系统数据表
  • 2.6作业
  • Java持久化机制和实现的过程
  • 电商推荐系统
  • LabVIEW高精度微小电容测量
  • Django通过Json配置文件分配多个定时任务
  • re:从0开始的CSS学习之路 2. 选择器超长大合集
  • 【数据结构和算法】--- 基于c语言排序算法的实现(1)
  • (篇九)MySQL常用内置函数
  • ffmpeg 时间裁剪之-ss -t与滤镜中trim=start=*:duration=*的区别和联系
  • $translatePartialLoader加载失败及解决方式
  • 【干货分享】SpringCloud微服务架构分布式组件如何共享session对象
  • CSS 提示工具(Tooltip)
  • MobX
  • node入门
  • PaddlePaddle-GitHub的正确打开姿势
  • SwizzleMethod 黑魔法
  • 搞机器学习要哪些技能
  • 关于extract.autodesk.io的一些说明
  • 前端每日实战 2018 年 7 月份项目汇总(共 29 个项目)
  • 使用Tinker来调试Laravel应用程序的数据以及使用Tinker一些总结
  • 源码之下无秘密 ── 做最好的 Netty 源码分析教程
  • 这几个编码小技巧将令你 PHP 代码更加简洁
  • AI算硅基生命吗,为什么?
  • CMake 入门1/5:基于阿里云 ECS搭建体验环境
  • ionic入门之数据绑定显示-1
  • RDS-Mysql 物理备份恢复到本地数据库上
  • 交换综合实验一
  • 如何在招聘中考核.NET架构师
  • $jQuery 重写Alert样式方法
  • (12)Hive调优——count distinct去重优化
  • (16)Reactor的测试——响应式Spring的道法术器
  • (c语言版)滑动窗口 给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度
  • (安全基本功)磁盘MBR,分区表,活动分区,引导扇区。。。详解与区别
  • (附源码)springboot 智能停车场系统 毕业设计065415
  • (力扣题库)跳跃游戏II(c++)
  • (三)docker:Dockerfile构建容器运行jar包
  • (数位dp) 算法竞赛入门到进阶 书本题集
  • (转)JAVA中的堆栈
  • (轉貼)《OOD启思录》:61条面向对象设计的经验原则 (OO)
  • *2 echo、printf、mkdir命令的应用
  • .Net 8.0 新的变化
  • .NET CF命令行调试器MDbg入门(一)
  • .net core使用RPC方式进行高效的HTTP服务访问
  • .Net 知识杂记
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .php结尾的域名,【php】php正则截取url中域名后的内容
  • :O)修改linux硬件时间
  • ??在JSP中,java和JavaScript如何交互?
  • @ConfigurationProperties注解对数据的自动封装