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

2024-02-03 09:36
文章标签 加密 导出 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.工具类 

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;}

这篇关于导出pdf 加密、加水印、加页脚的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/673719

相关文章

Java高效实现PowerPoint转PDF的示例详解

《Java高效实现PowerPoint转PDF的示例详解》在日常开发或办公场景中,经常需要将PowerPoint演示文稿(PPT/PPTX)转换为PDF,本文将介绍从基础转换到高级设置的多种用法,大家... 目录为什么要将 PowerPoint 转换为 PDF安装 Spire.Presentation fo

使用EasyPoi快速导出Word文档功能的实现步骤

《使用EasyPoi快速导出Word文档功能的实现步骤》EasyPoi是一个基于ApachePOI的开源Java工具库,旨在简化Excel和Word文档的操作,本文将详细介绍如何使用EasyPoi快速... 目录一、准备工作1、引入依赖二、准备好一个word模版文件三、编写导出方法的工具类四、在Export

5 种使用Python自动化处理PDF的实用方法介绍

《5种使用Python自动化处理PDF的实用方法介绍》自动化处理PDF文件已成为减少重复工作、提升工作效率的重要手段,本文将介绍五种实用方法,从内置工具到专业库,帮助你在Python中实现PDF任务... 目录使用内置库(os、subprocess)调用外部工具使用 PyPDF2 进行基本 PDF 操作使用

前端导出Excel文件出现乱码或文件损坏问题的解决办法

《前端导出Excel文件出现乱码或文件损坏问题的解决办法》在现代网页应用程序中,前端有时需要与后端进行数据交互,包括下载文件,:本文主要介绍前端导出Excel文件出现乱码或文件损坏问题的解决办法,... 目录1. 检查后端返回的数据格式2. 前端正确处理二进制数据方案 1:直接下载(推荐)方案 2:手动构造

C#自动化实现检测并删除PDF文件中的空白页面

《C#自动化实现检测并删除PDF文件中的空白页面》PDF文档在日常工作和生活中扮演着重要的角色,本文将深入探讨如何使用C#编程语言,结合强大的PDF处理库,自动化地检测并删除PDF文件中的空白页面,感... 目录理解PDF空白页的定义与挑战引入Spire.PDF for .NET库核心实现:检测并删除空白页

Java实现为PDF设置背景色和背景图片

《Java实现为PDF设置背景色和背景图片》在日常的文档处理中,PDF格式因其稳定性和跨平台兼容性而广受欢迎,本文将深入探讨如何利用Spire.PDFforJava库,以简洁高效的方式为你的PDF文档... 目录库介绍与安装步骤Java 给 PDF 设置背景颜色Java 给 PDF 设置背景图片总结在日常的

Java轻松实现PDF转换为PDF/A的示例代码

《Java轻松实现PDF转换为PDF/A的示例代码》本文将深入探讨Java环境下,如何利用专业工具将PDF转换为PDF/A格式,为数字文档的永续保存提供可靠方案,文中的示例代码讲解详细,感兴趣的小伙伴... 目录为什么需要将PDF转换为PDF/A使用Spire.PDF for Java进行转换前的准备通过

C#使用iText获取PDF的trailer数据的代码示例

《C#使用iText获取PDF的trailer数据的代码示例》开发程序debug的时候,看到了PDF有个trailer数据,挺有意思,于是考虑用代码把它读出来,那么就用到我们常用的iText框架了,所... 目录引言iText 核心概念C# 代码示例步骤 1: 确保已安装 iText步骤 2: C# 代码程

JAVA实现亿级千万级数据顺序导出的示例代码

《JAVA实现亿级千万级数据顺序导出的示例代码》本文主要介绍了JAVA实现亿级千万级数据顺序导出的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 前提:主要考虑控制内存占用空间,避免出现同时导出,导致主程序OOM问题。实现思路:A.启用线程池

java 恺撒加密/解密实现原理(附带源码)

《java恺撒加密/解密实现原理(附带源码)》本文介绍Java实现恺撒加密与解密,通过固定位移量对字母进行循环替换,保留大小写及非字母字符,由于其实现简单、易于理解,恺撒加密常被用作学习加密算法的入... 目录Java 恺撒加密/解密实现1. 项目背景与介绍2. 相关知识2.1 恺撒加密算法原理2.2 Ja