1. 程式人生 > >java實現word文件轉pdf線上瀏覽

java實現word文件轉pdf線上瀏覽

現在著手做的專案是一個關於考試的,裡面有許多考生的資料資訊是word文件,在這裡耗費了不少的時間,也看了眾多的博文,在這裡發一下我的個人總結,有不對的地方還望指正
用到的jar
 jacob.jar
這是Maven地址http://mvnrepository.com/artifact/net.sf.jacob-project/jacob
/**
     * 申報人doc轉pdf線上瀏覽
     * 
     * @author lrl
     * @date 建立時間 2018-5-24
     * @since V1.0
     */
    public final DataMap queryApplicantDOC2PDF
(final DataMap para) throws Exception { String sbrid = para.getString("sbrid"); if (StringUtil.chkStrNull(sbrid)) { throw new PadException("申報人ID不允許為空,請檢查重試"); } StringBuffer sqlBF = new StringBuffer(); sqlBF.setLength(0); sqlBF.append(" select sbrdoc, upper(zjhm) zjhm "
); sqlBF.append(" from vt.applicant "); sqlBF.append(" where sbrid = ? "); this.sql.setSql(sqlBF.toString()); sql.setString(1, sbrid); DataSet dsApplicant = sql.executeQuery(); if (dsApplicant.size() <= 0) { return null; } String zjhm = dsApplicant.getString(0
, "zjhm"); String filePath = "temp" + File.separator + GlobalVars.APP_ID; String path = filePath + File.separator + zjhm; File docFile = new File(path + File.separator + zjhm + ".doc"); File docPdfFile = new File(path + File.separator + zjhm + "doc.pdf"); //減少資料庫負擔,直接存在伺服器上快取了 if (!docPdfFile.exists()) { Blob sbrpdf = dsApplicant.getBlob(0, "sbrdoc"); int len = (new BigDecimal(sbrpdf.length())).intValue(); byte[] byteDoc = sbrpdf.getBytes(1, len); path = path + File.separator; File dir = new File(path); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("建立目錄失敗!"); } } FileIOUtil.writeBytesToFile(byteDoc, docFile); } try { app = new ActiveXComponent("Word.Application"); Dispatch documents = app.getProperty("Documents").toDispatch(); Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch(); // 判斷檔案存在 File target = new File(docPdfFile); if (!docPdfFile.exists()) { Dispatch.call(document, "SaveAs", pdfFile, 17); Dispatch.call(document, "Close", false); } }catch(Exception e) { System.out.println("轉換失敗"+e.getMessage()); }finally { // 關閉office app.invoke("Quit", 0); } String filePath = Path + File.separator + zjhm + "doc.pdf" String fileName = zjhm + "doc.pdf" FileInputStream inputstream = null; HttpServletResponse response = null; try { inputstream = new FileInputStream(filePath); FileIOUtil.writeStreamToResponse(inputstream, fileName, response); } catch (IOException e) { throw new Exception("檔案讀取異常:" + e.getMessage()); } finally { try { if (inputstream != null) { inputstream.close(); } } catch (Exception e) { throw new Exception("檔案損壞或不存在:" + e.getMessage()); } } return null; }