为Pdf批量添加水印
生活随笔
收集整理的這篇文章主要介紹了
为Pdf批量添加水印
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?Itext官網下載jar包
/*** PDF工具類*/ public class PdfUtil {public static void main(String[] args) throws Exception {//測試代碼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); //將水印圖片重命名為源文件名 }/**** 【功能描述:添加圖片和文字水印】 【功能詳細描述:功能詳細描述】* @param srcFile 待加水印文件* @param destFile 加水印后存放地址* @param text 加水印的文本內容* @param textWidth 文字橫坐標,起點為左下角* @param textHeight 文字縱坐標,起點為左下角s* @throws Exception*/public void addWaterMark(String srcFile, String destFile, String text,int textWidth, int textHeight) throws Exception{// 待加水印的文件PdfReader reader = new PdfReader(srcFile);// 加完水印的文件PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(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();}/*** 復制文件* @param srcFile* @param destFile* @throws IOException*/public void copyFile(String srcFile, String destFile) throws IOException {File file1 = new File(srcFile);File file2 = new File(destFile);InputStream in = null;OutputStream out = null;if (file1 != null && file1.isFile()) {in = new FileInputStream(file1);}else{System.out.println("復制源文件失敗!");throw new FileNotFoundException(srcFile);}if (file2 != null) {out = new FileOutputStream(file2);}byte[] bytes = new byte[1024*4];int len;while ((len =in.read(bytes))>-1){out.write(bytes,0,len);}out.close();in.close();}/*** 重命名* @param srcFile* @param destFile* @return* @throws IOException*/public boolean reNameFile(String srcFile, String destFile) throws IOException {File file1 = new File(srcFile);File file2 = new File(destFile);System.out.println(srcFile+" 重命名為 "+destFile+" 成功");return file1.renameTo(file2);}/*** 刪除* @param srcFile* @return* @throws IOException*/public boolean delFile(String srcFile) throws IOException {File file1 = new File(srcFile);System.out.println("刪除 "+srcFile+" 成功");return file1.delete();}}
Swing界面
public class PdfWaterMark {private JButton btnSelect;private JList list1;private JList list2;private JPanel mainPnl;private JPanel btnPnl;private JButton btnOK;static PdfWaterMark pdfWaterMark = null;static DefaultListModel dlmCommon = new DefaultListModel();static DefaultListModel dlmError = new DefaultListModel();static File root = null;public static void main(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 = new PdfWaterMark(); 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);}public PdfWaterMark() {btnSelect.addActionListener(new ActionListener() {public void actionPerformed(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(new ActionListener() {public void actionPerformed(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 boolean accept(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 = new OutputStreamWriter(fw);BufferedWriter bw = new BufferedWriter(ost);Object[] arr = dlmError.toArray();SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-hh:mm:ss ");String curtime = simpleDateFormat.format(new Date(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配置文件路徑* @param rootDir 根目錄文件夾* @return more 多個配置文件* zero 無配置文件* 返回ini絕對路徑*/public String getIni(File rootDir){FilenameFilter filenameFilter = new FilenameFilter() { //文件名過濾器public boolean accept(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());return file.getAbsolutePath();}}return null;}/*** 判斷dirName是否存在iniPath配置文件中* @param dirName 文件名* @param iniPath 配置文件絕對路徑* @return*/public String 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批量添加水印的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript之浅复制【拷贝】与深
- 下一篇: 【Android学习笔记】设置App启动