xpdf讀取pdf檔案並根據pdf內容修改檔名稱
阿新 • • 發佈:2019-02-04
0:前言
1:準備工作今天一哥們說他苦逼,導師逼他看文件,全是pdf,而且還是英文的,而且非常多,1000多個,我了個shit,更搞的是文件名字不是標題名,是編號,什麼5026a001.pdf,都是這種
然後我說你寫個程式把檔名修改了不就完了,他沒空,我就幫他寫了寫
- 上網查資料,C++讀取pdf庫,java讀取pdf庫,最後找到了xpdf庫,還好,下載地址【下載xpdf地址】,我下載的是windows版的,然後按照步驟實驗了一下
- 實驗,開啟壓縮包,讀了讀readme,然後進入bin32資料夾,裡面好多exe可執行檔案,好吧,開始搞起
- 拷貝一個pdf檔案進去,然後cmd命令列進入bin32資料夾,
然後果然生成了一個5026a001.txt,開啟一看,哇,完美轉換,看來不需要配置什麼東西就能執行。pdftotext.exe 5026a001.pdf
- 開始寫程式,java程式碼的,開始的想法是通過pdftotext轉成txt,然後解析txt文件,後來一看還有一個可執行程式pdfinfo.exe,感覺這個是讀取pdf文件資訊的程式。
- 命令列
然後在螢幕上完美輸出,說明他的標題直接可以拿到,那太好了,verygoodpdfinfo.exe 5026a001.pdf
- 下一步的任務就是獲得在cmd中執行程式後返回的結果值的任務了,就是獲得這些Title啊,Subject啊等等,
- 然後就好辦了,把所有的pdf放在一個資料夾中,java讀取這個資料夾,然後每個pdf都執行pdfinfo.exe這個程式,然後解析獲得的結果,然後在修改檔名,其中有等多細節,比如獲得的標題裡面有的字元不能作為檔名的,比如/ 、\ * ?等等,那好吧,開始搞起
package com.sunlei; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import javax.crypto.spec.IvParameterSpec; public class Rename { /** * @param args * @throws IOException */ public static void main(String[] args) { // TODO Auto-generated method stub // System.out.println("hello\n"); File file = new File("D:\\pdf");//pdf資料夾 String xpdfPath = "D:\\TDDOWNLOAD\\xpdfbin-win-3.03\\bin32\\pdfinfo.exe "; //pdfinfo.exe資料夾,注意這個exe和後面的pdf檔名有空格,所以這裡有空格 File[] fileListFiles = file.listFiles();// 取出資料夾下所有的檔案 for (int i = 0; i < fileListFiles.length; i++) { String cmd = xpdfPath + fileListFiles[i].getAbsolutePath(); try { Process process = Runtime.getRuntime().exec(cmd); BufferedReader br = new BufferedReader(new InputStreamReader( process.getInputStream()));//獲得exe執行程式返回結果 String firstLine = br.readLine();//只需要讀取第一行就行,只要標題 // System.out.println(firstLine); // System.out.println(firstLine.indexOf('D')); //下面substring的時候為什麼是16,是通過這個實驗出來的 if (firstLine != null) { String subTitle = firstLine.substring(16); if (!subTitle.equals("")) { subTitle = subTitle.replace(':', ' ');// 去掉檔名不合規範的 subTitle = subTitle.replace('*', ' '); subTitle = subTitle.replace('/', ' '); subTitle = subTitle.replace('?', ' '); String title = subTitle + ".pdf";//加上字尾名 File newFile; if (title != "untitled.pdf" && title != ".pdf") { newFile = new File("D:/pdf/" + title); // System.out.println(title); if (fileListFiles[i].renameTo(newFile)) {//修改檔名 System.out.println(fileListFiles[i].getName() + "修改成功"); } else { System.out.println(fileListFiles[i].getName() + "修改失敗"); } } br.close();//別忘了關閉流 process.destroy(); }else { System.out.println(fileListFiles[i].getName() + "因為文中沒有檔案title而修改失敗"); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
- 結果是除了那些空文件的不修改之外,其他都搞定,上圖
- 程式碼寫的比較亂,如果有需要下載的話【demo下載地址】