Itext官网下载jar包

/*** PDF工具类*/
public classPdfUtil {public static void main(String[] args) throwsException {//测试代码String inPath= "F://PDF//test3.pdf";String outPath= "F://PDF//test6.pdf";new PdfUtil().addWaterMark(inPath,outPath,"这是一个水印",20,10);    //添加水印new PdfUtil().delFile(inPath);     //删除源文件new PdfUtil().reNameFile(outPath,inPath);   //将水印图片重命名为源文件名
}/**** 【功能描述:添加图片和文字水印】 【功能详细描述:功能详细描述】*@paramsrcFile 待加水印文件*@paramdestFile 加水印后存放地址*@paramtext 加水印的文本内容*@paramtextWidth 文字横坐标,起点为左下角*@paramtextHeight 文字纵坐标,起点为左下角s*@throwsException*/public voidaddWaterMark(String srcFile, String destFile, String text,int textWidth, int textHeight) throwsException{//待加水印的文件PdfReader reader = newPdfReader(srcFile);//加完水印的文件PdfStamper stamper = new PdfStamper(reader, newFileOutputStream(destFile));int total = reader.getNumberOfPages();   //总页数
PdfContentByte content;//设置字体BaseFont font = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);//循环对每页插入水印for (int i = 1; i <= total; i++){//水印的起始content =stamper.getUnderContent(i);//开始
content.beginText();//设置颜色 默认为蓝色
content.setColorFill(BaseColor.BLACK);//设置字体及字号content.setFontAndSize(font, 8);//设置起始位置
content.setTextMatrix(textWidth, textHeight);//开始写入水印content.showTextAligned(Element.ALIGN_LEFT, text, textWidth,textHeight, 0);content.endText();}stamper.close();reader.close();}/*** 复制文件*@paramsrcFile*@paramdestFile*@throwsIOException*/public void copyFile(String srcFile, String destFile) throwsIOException {File file1= newFile(srcFile);File file2= newFile(destFile);InputStream in= null;OutputStream out= null;if (file1 != null &&file1.isFile()) {in= newFileInputStream(file1);}else{System.out.println("复制源文件失败!");throw newFileNotFoundException(srcFile);}if (file2 != null) {out= newFileOutputStream(file2);}byte[] bytes = new byte[1024*4];intlen;while ((len =in.read(bytes))>-1){out.write(bytes,0,len);}out.close();in.close();}/*** 重命名*@paramsrcFile*@paramdestFile*@return*@throwsIOException*/public boolean reNameFile(String srcFile, String destFile) throwsIOException {File file1= newFile(srcFile);File file2= newFile(destFile);System.out.println(srcFile+" 重命名为 "+destFile+" 成功");returnfile1.renameTo(file2);}/*** 删除*@paramsrcFile*@return*@throwsIOException*/public boolean delFile(String srcFile) throwsIOException {File file1= newFile(srcFile);System.out.println("删除 "+srcFile+" 成功");returnfile1.delete();}}

Swing界面

public classPdfWaterMark {privateJButton btnSelect;privateJList list1;privateJList list2;privateJPanel mainPnl;privateJPanel btnPnl;privateJButton btnOK;static PdfWaterMark pdfWaterMark = null;static DefaultListModel dlmCommon = newDefaultListModel();static DefaultListModel dlmError = newDefaultListModel();static File root = null;public static voidmain(String[] args) {JFrame frame= new JFrame("水印添加工具");frame.setIconImage(new ImageIcon("src/main/resources/pdf.png").getImage());    //iconframe.setSize(400,300);    //窗口大小frame.setLocation(200,200);    //窗口位置
pdfWaterMark= newPdfWaterMark();    JPanel panel=pdfWaterMark.mainPnl;JPanel bpnl=pdfWaterMark.btnPnl;bpnl.setBounds(20,20,100,150);pdfWaterMark.list1.setModel(dlmCommon);pdfWaterMark.list2.setModel(dlmError);pdfWaterMark.btnSelect.setSize(50,30);frame.setContentPane(panel);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}publicPdfWaterMark() {btnSelect.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {JFileChooser chooser= new JFileChooser();    //文件选择器chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);   //可选择文件和文件夹chooser.setDialogTitle("选择根文件夹");     //对话框titlechooser.showDialog(new Label(), "选择");   //确定按钮textroot = chooser.getSelectedFile();   //获取选择文件or文件夹if(root!=null){pdfWaterMark.btnSelect.setText(root.getAbsolutePath());}else{pdfWaterMark.btnSelect.setText("选择根文件夹");}}});btnOK.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {if(root == null){JOptionPane.showMessageDialog(null, "请选择跟目录", "提示", JOptionPane.WARNING_MESSAGE);return;}//获取配置文件路径String iniPath = getIni(root);   //获取根文件夹中的ini配置文件绝对路径,返回zero或者more时为异常if (iniPath.equals("more")){JOptionPane.showMessageDialog(null, "请确保只有一个ini配置文件!", "错误", JOptionPane.ERROR_MESSAGE);return;}else if(iniPath.equals("zero")){JOptionPane.showMessageDialog(null, "无ini配置文件!", "错误", JOptionPane.ERROR_MESSAGE);return;}if (root.isDirectory()) {   //判断选择的文件是否为文件夹File[] pdfDirs = root.listFiles();   //获取根文件夹下的所有文件pdfDirs(文件夹和.ini)for (File pdfDir : pdfDirs) {    //遍历pdfDirsif (pdfDir.isDirectory()){    //当时文件夹时String dirName = pdfDir.getName();   //pdfDir文件夹名String detailInfo = null;   //水印详细信息if((detailInfo=isContaint(dirName,iniPath)) != null){   //配置文件中是否有文件名,如果有,则返回所有信息File[] pdfs = pdfDir.listFiles( new FilenameFilter() {    //获得pdfDir文件夹下所有的pdf文件public booleanaccept(File dir, String name) {if (name.endsWith(".pdf")){    //只过滤.ini文件结尾的文件return true;}return false;}});//将pdfDir所有的文件列出来if(pdfs == null || pdfs.length ==0){dlmError.addElement(pdfDir.getAbsoluteFile()+"文件夹下无pdf文件");}for (File pdf:pdfs){   //遍历pdf文件String inPath = pdf.getAbsolutePath();    //pdf绝对路径String outPath = pdf.getParent()+"\\"+System.currentTimeMillis()+pdf.getName(); //水印pdf绝对路径try{new PdfUtil().addWaterMark(inPath,outPath,detailInfo,20,10);   //加水印new PdfUtil().delFile(inPath);   //删除源文件new PdfUtil().reNameFile(outPath,inPath);   //将水印文件名重命名为源文件名dlmCommon.addElement(inPath+"水印添加成功");}catch(Exception e1) {e1.printStackTrace();}}}else{dlmError.addElement("ini配置文件中无 "+dirName+" 信息");}}}}else {   //选择的不是文件夹JOptionPane.showMessageDialog(null, "请选择根文件夹", "警告", JOptionPane.WARNING_MESSAGE);}//执行完毕后将错误日志打印到errorLog.txttry{File errParent= new File(new File("").getCanonicalPath());   //获取项目路径File errLog = new File(errParent.getParent()+"/errLog.txt");  //项目父级if(!errLog.exists()){     //无文件则创建
errLog.createNewFile();}FileOutputStream fw= new FileOutputStream(errLog,true);OutputStreamWriter ost= newOutputStreamWriter(fw);BufferedWriter bw= newBufferedWriter(ost);Object[] arr=dlmError.toArray();SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-hh:mm:ss ");String curtime= simpleDateFormat.format(newDate(System.currentTimeMillis())).toString();bw.write(curtime+"\r\n");for(Object obj : arr){bw.write(new String((obj.toString()+"\r\n").getBytes(),"utf-8"));}bw.write("\r\n");bw.close();ost.close();fw.close();}catch(IOException e1) {e1.printStackTrace();}}});}/*** 根据根目录文件夹获取ini配置文件路径*@paramrootDir  根目录文件夹*@returnmore 多个配置文件*          zero 无配置文件*          返回ini绝对路径*/publicString getIni(File rootDir){FilenameFilter filenameFilter= new FilenameFilter() {    //文件名过滤器public booleanaccept(File dir, String name) {if (name.endsWith(".ini")){    //只过滤.ini文件结尾的文件return true;}return false;}};File[] files= rootDir.listFiles(filenameFilter);    //获取文件夹中的ini配置文件if (files.length > 1){return "more";}else if(files.length == 0){return "zero";}else{for(File file:files){System.out.println("找到配置文件:"+file.getAbsolutePath());returnfile.getAbsolutePath();}}return null;}/*** 判断dirName是否存在iniPath配置文件中*@paramdirName  文件名*@paraminiPath  配置文件绝对路径*@return*/publicString isContaint(String dirName,String iniPath){try{FileReader fileReader= new FileReader(new File(iniPath));   //FileReader封装FileBufferedReader bufferedReader = new BufferedReader(fileReader);  //BufferedReader封装FileReaderString line = null;//逐行读取配置文件while ((line=bufferedReader.readLine())!=null){if (new String(line.replace(" ","").getBytes(),"utf-8").contains(dirName)){  //配置文件中按空格分开信息,将所有信息串为一个字符串System.out.println(dirName+"找到"+line);return line;   //返回文件名在配置文件中的所有信息
}}}catch(FileNotFoundException e1) {e1.printStackTrace();}catch(IOException e1) {e1.printStackTrace();}return null;}}

Maven POM文件

    <properties><itext.version>5.5.10</itext.version></properties><dependencies><dependency><groupId>antlr</groupId><artifactId>antlr</artifactId><version>2.7.2</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>${itext.version}</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-pdfa</artifactId><version>${itext.version}</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-xtra</artifactId><version>${itext.version}</version></dependency><dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>${itext.version}</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency></dependencies>

然后打包成jar包

structure-->artifacts

新建libs文件夹将jar包拖入

点击jar包编辑classpath

打包结果如图

完成后在jar包所在位置执行java -Dfile.encoding=utf-8 -jar xx.jar即可。

exe4j可将jar转换为exe文件,官网。

因为有的人电脑上没有jdk或者jre,所以为了每个人都能用, 将jre拷贝在项目同级。

新建start.bat文件,文件内容为

"./jre7/bin/java.exe" -Dfile.uncoding=utf-8 -jar ./pdf15_jar/pdf15.jar

源码

转载于:https://www.cnblogs.com/aeolian/p/8856961.html

为Pdf批量添加水印相关推荐

  1. python pdf 图片水印_怎样用python给pdf批量添加水印并加密

    很多时候需要给pdf添加水印,而且还要加密文件,这些在Python中是如何实现的呢?学过编程的小伙伴准备好迎接今天的挑战吧. 1.设置路径 import os os.getcwd() os.chdir ...

  2. 用python给pdf批量添加水印,并给pdf加密

    本文部分参考:https://blog.csdn.net/oh5w6hinug43jvrhhb/article/details/80879026 本文先分别讲解整个代码各个步骤的含义,最后会附上完整代 ...

  3. acrobat给pdf加多行水印_批量pdf如何添加水印 多个pdf批量加相同水印的方法|支持同时添加文字、图片水印...

    本次还是给大家讲讲pdf文件的编辑转换处理,毕竟pdf文件也是在办公学习上是很常用到的,工作时很经常会遇到多个pdf文件要处理的情况,比如说制作好了一系列的pdf文档,需要上传到网络或者传输给他人查阅 ...

  4. python给word添加水印_python 批量给 word,excel,ppt 或 pdf 文件添加水印

    python 批量给 word 或 pdf 文件添加水印 更新 20200310 更新 README,对于中文显示为方块的问题,需使用宋体(simsun.ttc).黑体(simhei.ttf)等字体. ...

  5. keil如何添加h文件_如何给PDF文件添加水印?分享给PDF批量加水印的方法

    如何给PDF文件添加水印?在处理一些重要的商业文件中,很多人害怕文件内容被抄袭盗用,就会在文件中添加水印,其中包括Word.Excel.PPT.图片.PDF等多种不同的文件.那如果是PDF文件,你知道 ...

  6. keil如何添加h文件_如何给PDF文件添加水印?分享给PDF批量加水印的方法-PDF ——快科技(驱动之家旗下媒体)-...

    如何给PDF文件添加水印?在处理一些重要的商业文件中,很多人害怕文件内容被抄袭盗用,就会在文件中添加水印,其中包括Word.Excel.PPT.图片.PDF等多种不同的文件.那如果是PDF文件,你知道 ...

  7. Python3,2段代码,给pdf文件添加水印,原来watermark还可以这么玩。

    pdf添加watermark 1. 引言 2.指定水印内容输出到pdf文件 2.1 模块安装 2.2 思路 2.3 代码示例 3.水印内容批量输出到pdf文件 3.1 模块安装 3.2 思路 3.3 ...

  8. pdf批量加水印logo的方法

    pdf批量加水印logo的方法!在处理办公文件时,我们经常需要给公司的内部文件或者商务文件添加统一的水印logo,添加水印后的文件可以防止文件被别人恶意盗用.word文件添加水印logo操作起来比较简 ...

  9. 如何给多个pdf批量加水印?

    如今PDF已经成为最常用的文件格式,尤其工作中的一些重要文件,比如合同.公司介绍,产品说明书等,都是PDF格式的文件.所以给PDF文件添加水印变成非常的重要,可以有效防止文件被恶意盗用,可是说是非常重 ...

最新文章

  1. 简易在线实验室管理系统
  2. DotNetNuke(DNN)升级攻略(DNN 4.3.7至DNN 4.6.0)
  3. CUDA,C++,Java,Python,Fortran运行速度比较
  4. ORACLE如何一次性修改用户连接数?
  5. [Android开源项目] GitHub开源项目总结 (转)
  6. python r转义_Python快速入门系列之二:还学不会我直播跪搓衣板
  7. [日常] 算法-单链表的创建-尾插法
  8. linux系统 qt开发,老板让我写一个Windows程序,结果我在Linux下用Qt开发
  9. 深度学习head、neck、backbone三个术语分别是指什么?
  10. 跨平台数据库ODB实战4-Person类的聚合查询
  11. 使用Excel批量生成SQL语句
  12. Mysql日志与备份以及恢复
  13. 那个直播软件有软件测试课程,资讯详情-直播软件有哪些测试方法-柠檬班-自动化测试-软件测试培训-自学官网...
  14. 联想拯救者Y7000P触摸板无法使用
  15. 深入boot.img格式文件结构解析
  16. 爬虫--爬取单张图片
  17. 【错误处理】RuntimeError: Attempting to deserialize object on CUDA device 1 but torch.cuda.device_count
  18. excel下拉菜单vba_一站式提供不同的Excel下拉菜单
  19. jscript和javascript区别
  20. 华为手机如何更新鸿蒙系统_华为鸿蒙系统可以更新用上啦

热门文章

  1. gridview、datalist、repeater、FormView、DetailsView的区别详解
  2. git 移动分支指针_图解4种git合并分支方法
  3. 函数 —— strchr() 例如:字符串中的 192.168.1.2|00:11:22:33:44:55 取出字符串中的ip与mac值
  4. 设计模式的六大原则(个人笔记)
  5. 服务器报错您的主机中的软件中止了一个已建立的连接
  6. 一千行MySQL学习笔记
  7. 2013应届毕业生“京北方”校招应聘总结
  8. 利用 sys.sysprocesses 检查 Sql Server的阻塞和死锁
  9. 轻量级大规模机器学习算法库Fregata开源:快速,无需调参
  10. HOG:从理论到OpenCV实践