1. 程式人生 > 實用技巧 >Java 使用Jacob.jar 將Word型別文件轉換成PDF,將PDF轉換成TIFF

Java 使用Jacob.jar 將Word型別文件轉換成PDF,將PDF轉換成TIFF

程式碼:

package com.microsys.fax.agent.utils;

import java.awt.image.BufferedImage;
import java.io.File;  
  
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import
java.util.ArrayList; import java.util.List; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import com.jacob.activeX.ActiveXComponent; import
com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; import com.sun.media.jai.codec.ImageCodec; import com.sun.media.jai.codec.ImageEncoder; import com.sun.media.jai.codec.TIFFEncodeParam; /** * * 將jacob.dll放入JDK的bin目錄下 把jacob.jar放入專案的buildPath中(web專案放到WEB-INF\lib目錄下) * *
*/ public class ConvertToPdf { /*轉PDF格式值*/ private static final int wdFormatPDF = 17; private static final int xlFormatPDF = 0; private static final int ppFormatPDF = 32; private static final int msoTrue = -1; private static final int msofalse = 0; /*轉HTML格式值*/ private static final int wdFormatHTML = 8; private static final int ppFormatHTML = 12; private static final int xlFormatHTML = 44; /*轉TXT格式值*/ private static final int wdFormatTXT = 2; //word相關格式轉換PDF public boolean convert2PDF(String inputFile, String pdfFile) { String suffix = getFileSufix(inputFile); File file = new File(inputFile); if (!file.exists()) { Log.debug("檔案不存在!"); return false; } if (suffix.equals("pdf")) { Log.debug("PDF not need to convert!"); return false; } if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) { return word2PDF(inputFile, pdfFile); } else if (suffix.equals("ppt") || suffix.equals("pptx")) { return ppt2PDF(inputFile, pdfFile); } else if (suffix.equals("xls") || suffix.equals("xlsx")) { return excel2PDF(inputFile, pdfFile); } else { Log.debug("檔案格式不支援轉換!"); return false; } } /** * 從輸入流讀取pdf,轉化為tiff後寫入輸出流.<br/> * 參考列表: * <ol> * <li><a href= * "http://www.coderanch.com/t/497492/java/java/Convert-PDF-files-Tiff-files" * >Convert PDF files to Tiff files</a></li> * <li><a href= * "http://www.oracle.com/technetwork/cn/java/javaee/downloads/readme-1-1-2-137176.html" * >Java(TM) Advanced Imaging API README</a></li> * </ol> * * @param is * 輸入流,提供pfg內容. * @param os * 輸出流. */ public static boolean pdf2Tiff(InputStream is, OutputStream os) { PDDocument doc = null; try { doc = PDDocument.load(is); int pageCount = doc.getNumberOfPages(); PDFRenderer renderer = new PDFRenderer(doc); // 根據PDDocument物件建立pdf渲染器 List<PlanarImage> piList = new ArrayList<PlanarImage>(pageCount - 1); for (int i = 0 + 1; i < pageCount; i++) { BufferedImage image = renderer.renderImageWithDPI(i, Pdf2TiffConstant.DPI, ImageType.RGB); PlanarImage pimg = JAI.create("mosaic", image); piList.add(pimg); } TIFFEncodeParam param = new TIFFEncodeParam();// 建立tiff編碼引數類 param.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);// 壓縮引數 param.setExtraImages(piList.iterator());// 設定圖片的迭代器 BufferedImage fimg = renderer.renderImageWithDPI(0, Pdf2TiffConstant.DPI, ImageType.RGB); PlanarImage fpi = JAI.create("mosaic", fimg); // 通過JAI的create()方法例項化jai的圖片物件 ImageEncoder enc = ImageCodec.createImageEncoder(Pdf2TiffConstant.IMG_FORMAT, os, param); enc.encode(fpi);// 指定第一個進行編碼的jai圖片物件,並將輸出寫入到與此 Log.debug("轉換文件 [PDF] >>> [Tiff]"); return true; } catch (IOException e) { e.printStackTrace(); } finally { try { if (doc != null) doc.close(); } catch (IOException e) { e.printStackTrace(); } } return false; } /** * 獲取檔案字尾 * * @param fileName * @return * @author SHANHY */ private String getFileSufix(String fileName) { int splitIndex = fileName.lastIndexOf("."); return fileName.substring(splitIndex + 1); } /** * Word文件轉換 * * @param inputFile * @param pdfFile * @author SHANHY */ private boolean word2PDF(String inputFile, String pdfFile) { ComThread.InitSTA(); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch doc = null; try { app = new ActiveXComponent("Word.Application");// 建立一個word物件 app.setProperty("Visible", new Variant(false)); // 不可見開啟word app.setProperty("AutomationSecurity", new Variant(3)); // 禁用巨集 Dispatch docs = app.getProperty("Documents").toDispatch();// 獲取文擋屬性 Log.debug("開啟文件 >>> " + inputFile); // Object[]第三個引數是表示“是否只讀方式開啟” // 呼叫Documents物件中Open方法開啟文件,並返回開啟的文件物件Document doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch(); // 呼叫Document物件的SaveAs方法,將文件儲存為pdf格式 Log.debug("轉換文件 [" + inputFile + "] >>> [" + pdfFile + "]"); Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);//word儲存為pdf格式巨集,值為17 // Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF); // word儲存為pdf格式巨集,值為17 long end = System.currentTimeMillis(); Log.debug("用時:" + (end - start) + "ms."); return true; } catch (Exception e) { e.printStackTrace(); Log.debug("========Error:Word文件轉換失敗:" + e.getMessage()); } finally { Dispatch.call(doc, "Close", false); Log.debug("關閉文件"); if (app != null) app.invoke("Quit", new Variant[] {}); } // 如果沒有這句話,winword.exe程序將不會關閉 ComThread.Release(); ComThread.quitMainSTA(); return false; } /** * PPT文件轉換 * * @param inputFile * @param pdfFile * @author SHANHY */ private boolean ppt2PDF(String inputFile, String pdfFile) { ComThread.InitSTA(); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch ppt = null; try { app = new ActiveXComponent("PowerPoint.Application");// 建立一個PPT物件 // app.setProperty("Visible", new Variant(false)); // 不可見開啟(PPT轉換不執行隱藏,所以這裡要註釋掉) // app.setProperty("AutomationSecurity", new Variant(3)); // 禁用巨集 Dispatch ppts = app.getProperty("Presentations").toDispatch();// 獲取文擋屬性 Log.debug("開啟文件 >>> " + inputFile); // 呼叫Documents物件中Open方法開啟文件,並返回開啟的文件物件Document ppt = Dispatch.call(ppts, "Open", inputFile, true,// ReadOnly true,// Untitled指定檔案是否有標題 false// WithWindow指定檔案是否可見 ).toDispatch(); Log.debug("轉換文件 [" + inputFile + "] >>> [" + pdfFile + "]"); Dispatch.call(ppt, "SaveAs", pdfFile, ppFormatPDF); long end = System.currentTimeMillis(); Log.debug("用時:" + (end - start) + "ms."); return true; } catch (Exception e) { e.printStackTrace(); Log.debug("========Error:PPT文件轉換失敗:" + e.getMessage()); } finally { Dispatch.call(ppt, "Close"); Log.debug("關閉文件"); if (app != null) app.invoke("Quit", new Variant[] {}); } ComThread.Release(); ComThread.quitMainSTA(); return false; } /** * Excel文件轉換 * * @param inputFile * @param pdfFile * @author SHANHY */ private boolean excel2PDF(String inputFile, String pdfFile) { ComThread.InitSTA(); long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch excel = null; try { app = new ActiveXComponent("Excel.Application");// 建立一個PPT物件 app.setProperty("Visible", new Variant(false)); // 不可見開啟 // app.setProperty("AutomationSecurity", new Variant(3)); // 禁用巨集 Dispatch excels = app.getProperty("Workbooks").toDispatch();// 獲取文擋屬性 Log.debug("開啟文件 >>> " + inputFile); // 呼叫Documents物件中Open方法開啟文件,並返回開啟的文件物件Document excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch(); // 呼叫Document物件方法,將文件儲存為pdf格式 Log.debug("轉換文件 [" + inputFile + "] >>> [" + pdfFile + "]"); // Excel 不能呼叫SaveAs方法 Dispatch.call(excel, "ExportAsFixedFormat", xlFormatPDF, pdfFile); long end = System.currentTimeMillis(); Log.debug("用時:" + (end - start) + "ms."); return true; } catch (Exception e) { e.printStackTrace(); Log.debug("========Error:Excel文件轉換失敗:" + e.getMessage()); } finally { Dispatch.call(excel, "Close", false); Log.debug("關閉文件"); if (app != null) app.invoke("Quit", new Variant[] {}); } ComThread.Release(); ComThread.quitMainSTA(); return false; } /** * 測試 * * @param args * @author SHANHY */ public static void main(String[] args) { ConvertToPdf d = new ConvertToPdf(); // d.convert2PDF("F:\\20170802.docx", "F:\\test.pdf"); d.convert2PDF("F:\\UCS新增功能說明.txt", "F:\\UCS新增功能說明.pdf"); // d.convert2PDF("g:\\testppt.pptx", "g:\\testppt.pdf"); /// d.convert2PDF("F:\\bbbbb.xls", "F:\\bbb.pdf"); try { InputStream is = new FileInputStream(new File("F:\\UCS新增功能說明.pdf")); File out = new File("F:\\UCS新增功能說明.tiff"); if (!out.exists()) { out.createNewFile(); } OutputStream os = new FileOutputStream(out); boolean f=pdf2Tiff(is, os); System.out.println("f:" +f); is.close(); os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

注意事項: