导出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

相关文章

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

Python实现pdf电子发票信息提取到excel表格

《Python实现pdf电子发票信息提取到excel表格》这篇文章主要为大家详细介绍了如何使用Python实现pdf电子发票信息提取并保存到excel表格,文中的示例代码讲解详细,感兴趣的小伙伴可以跟... 目录应用场景详细代码步骤总结优化应用场景电子发票信息提取系统主要应用于以下场景:企业财务部门:需

Mac备忘录怎么导出/备份和云同步? Mac备忘录使用技巧

《Mac备忘录怎么导出/备份和云同步?Mac备忘录使用技巧》备忘录作为iOS里简单而又不可或缺的一个系统应用,上手容易,可以满足我们日常生活中各种记录的需求,今天我们就来看看Mac备忘录的导出、... 「备忘录」是 MAC 上的一款常用应用,它可以帮助我们捕捉灵感、记录待办事项或保存重要信息。为了便于在不同

使用Java实现Navicat密码的加密与解密的代码解析

《使用Java实现Navicat密码的加密与解密的代码解析》:本文主要介绍使用Java实现Navicat密码的加密与解密,通过本文,我们了解了如何利用Java语言实现对Navicat保存的数据库密... 目录一、背景介绍二、环境准备三、代码解析四、核心代码展示五、总结在日常开发过程中,我们有时需要处理各种软

Python对PDF书签进行添加,修改提取和删除操作

《Python对PDF书签进行添加,修改提取和删除操作》PDF书签是PDF文件中的导航工具,通常包含一个标题和一个跳转位置,本教程将详细介绍如何使用Python对PDF文件中的书签进行操作... 目录简介使用工具python 向 PDF 添加书签添加书签添加嵌套书签Python 修改 PDF 书签Pytho

MySQL Workbench工具导出导入数据库方式

《MySQLWorkbench工具导出导入数据库方式》:本文主要介绍MySQLWorkbench工具导出导入数据库方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录mysql Workbench工具导出导入数据库第一步 www.chinasem.cn数据库导出第二步

Java如何根据word模板导出数据

《Java如何根据word模板导出数据》这篇文章主要为大家详细介绍了Java如何实现根据word模板导出数据,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... pom.XML文件导入依赖 <dependency> <groupId>cn.afterturn</groupId>