java利用openoffice轉換doc、docx、txt、pptx、xlxs為PDF格式檔案
阿新 • • 發佈:2019-02-09
1、首先安裝openoffice(安裝包可在我的資源中查到名稱:(openoffice))
2、安裝完成後cmd 執行命令
(1)cd C:\Program Files (x86)\openoffice\program
(2)soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
3、程式碼如下(完整工程刻在我的資源中查詢名稱(doc轉PDF),100%可直接使用)
import java.io.File; import java.io.FilenameFilter; import com.shunan.WordToPDF.TestThread; public class Word2PDFUtil { /** * @param dirs doc轉換資料夾,批量轉換 */ public static void word2Pdf(String dirs){ File dir = new File(dirs); File[] files = dir.listFiles(new WordFilenameFilter()); //遍歷資料夾方式 if (files == null||files.length==0){ throw new NullPointerException("該路徑下沒有可轉換的檔案"); } for (int i = 0; i < files.length; i++) { String strFileName = files[i].getAbsolutePath().toLowerCase(); TestThread t1 = new WordToPDF.TestThread(); //輸入檔名 t1.setInputFile(new File(strFileName)); //獲得"."前面的檔名並將其輸入為PDF t1.setOutputFile(new File(strFileName.substring(0,strFileName.indexOf("."))+".pdf")); t1.start(); } } /** * @param orgfileName 原始檔名 * @param descFileName 生成pdf檔名 */ public static void word2Pdf(String orgfileName, String descFileName) { if(!isWord(orgfileName)||descFileName==null){ throw new IllegalArgumentException("原始檔名不是可轉換文件,或者descFileName為空"); } TestThread t1 = new WordToPDF.TestThread(); // 輸入檔名 t1.setInputFile(new File(orgfileName)); // 獲得"."前面的檔名並將其輸入為PDF t1.setOutputFile(new File(descFileName.substring(0, descFileName .indexOf(".")) + ".pdf")); t1.start(); } static class WordFilenameFilter implements FilenameFilter{ @Override //只轉換word文件 public boolean accept(File dir, String name) { return isWord(name); } } /** * @param name 檔名 * @return 判斷是否為doc word文件 */ private static boolean isWord(String name){ return name.endsWith(".doc")||name.endsWith(".docx")||name.endsWith(".wps")||name.endsWith(".txt"); //return true; } }
4、效果圖