1. 程式人生 > >java對office、pdf文件線上預覽解析(融合進專案中)

java對office、pdf文件線上預覽解析(融合進專案中)

最近在專案中要做一個文件的預覽,在網上搜了好多demo,都可以實現其功能,但是放在自己的專案中有點複雜。

先說明本人的開發環境(win7+tomcat7+maven+svn+myeclipse),接下來最直觀的專案需求,如下圖:


當用戶點選預覽的時候能看各種文件,其實在這裡有兩種思路:

 一:如果你的文件是固定的,就是單純的給使用者進行預覽和下載的,那就是在點選預覽的時候,後臺完成將文件轉換成pdf,再將pdf文件轉換成swf檔案,缺點是效率不好,慢,使用者體驗不好。

 二:就是在上傳文件的時候,直接將文件轉換成pdf,再將pdf轉換成swf檔案,這樣使用者點選預覽的時候只是給一個存放swf檔案的路徑,就能直接展示。

專案中我是採用第二種方式:

 實現過程說明:

         1、使用OpenOffice(JODConverter)將不同型別的附件轉換為.pdf字尾的檔案(PDF);

         2、使用SwfTools將pdf檔案轉換為swf檔案;

         3、使用FlexPaper 在jsp中預覽swf檔案;

實現該功能需要安裝兩個軟體、下載FlexPaper元件

         1.openoffice是Apache下的一個開放免費的文書處理軟體

          2.SWFTools是一組用來處理Flash的swf檔案的工具包,我們使用它將pdf檔案轉成swf檔案!

          3.FlexPaper是一個開源輕量級的在瀏覽器上顯示各種文件的元件(下載下來後解壓即可)

一.基礎操作

將下載的兩個軟體進行安裝,可自定義碟符安裝,oppenoffice是一套sun的開源office辦公套件,能在widows,linux,solaris等作業系統上執行可以將word、excel、ppt、txt等檔案轉換為pdf檔案;

安裝完成後,我們還需要啟動openoffice server。有兩種做法:

 第一種:以命令的方式啟動,在cmd命令下,進入C:\Program Files (x86)\OpenOffice 4\program的目錄下,輸入命令:

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

就可以啟動成功,但是這種每次服務重啟都要來執行此命令,比較麻煩。

 第二種:以系統服務的方式啟動,此服務需要下載Windows Resource Kit tools,此軟體可以將openoffice server設定成系統服務。

Windows Resource Kit tools是一組為管理員、開發者和高階使用者設計的軟體工具,包括管理活動目錄組策略、TCP/IP網路、登錄檔、系統安全、監測等涉及Windows Server 2003 作業系統的其它很多方面的非常規安裝的工具組。

下載Windows Resource Kit tools,直接百度輸入Windows Resource Kit tools應該第一個就是點選download就可以,預設安裝即可。

接下來做三個操作:

1.找到Windows Resource Kit tools

在Command Shell中執行以下命令:

 "C:\Program Files (x86)\Windows Resource Kits\Tools\instsrv" OpenOfficeUnoServer "C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe"

這裡注意你的路徑,我的是C:\Program Files (x86)\Windows Resource Kits\Tools

2.開啟登錄檔尋找以下路徑

    HKEY_LOCAL_MACHINE -> SYSTEM ->ControlSet001 ->Services ->OpenOfficeUnoServer

 在OpenOfficeUnoServer上新建“項”Parameters,在Parameters新建字串值Application,添入值:

C:\Program Files (x86)\OpenOffice 4\program\soffice.exe -headless -nofirststartwizard -accept="socket,host=localhost,port=8100;urp;StarOffice.Service"

同樣注意C:\Program Files (x86)\OpenOffice 4的路徑。

3.在服務控制檯啟動 openoffice 服務,也可以在cmd命令中執行netstat -anop tcp,檢視8100是否已被監聽。

2.開啟登錄檔尋找以下路徑

二.開發中詳細步驟解析

 1.我再專案中用的myEclipse+maven,ssm框架,以下是專案所用的jar包:
次jar包可以在百度搜jodconverter-2.2.2直接下載即可,把這些jar包放在對應的專案lib資料夾中   2.同樣還需要一些js檔案,百度搜FlexPaper_2.1.0官方版本下載即可,將FlexPaper_2.1.0的js中的檔案放在在js/knowleage/common中,另外將FlexPaperViewer.swf放在common的上一級也就是knowleage中,這裡要修改一下原始碼flexpaper.js中

在我的專案中我寫了兩個工具類以便更好的呼叫:

1.DocumentUtil 

package com.elitel.ioms.base.comm.utils;


import java.io.File;


import javax.servlet.http.HttpServletRequest;


public class DocumentUtil {

/**
* 文件工具類,根據上傳的檔案生成pwf和swf檔案。
* @param request
* @param url
*/
public static void topdfAndswf(HttpServletRequest request,String url){
String path = request.getRequestURI();
File f = new File(path+url);
if (f != null) {
String tomcatURL_1 =request.getSession().getServletContext().getRealPath("/");
String tomcatURL_2 = tomcatURL_1.replaceAll("\\\\", "/");
//呼叫轉換類DocConverter,並將需要轉換的檔案傳遞給該類的構造方法
DocConverterUtil d = new DocConverterUtil(tomcatURL_2+url);
//呼叫conver方法開始轉換,先執行doc2pdf()將office檔案轉換為pdf;再執行pdf2swf()將pdf轉換為swf;
d.conver();
}
}

}

2.DocConverterUtil  轉換類

package com.elitel.ioms.base.comm.utils;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;


import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
/**
 * doc docx,ppt,pptx等格式轉換
 * 
 * 
 *
 */
public class DocConverterUtil {
private static final int environment = 1;// 環境 1:Windows 2:Linux
private String fileString;// (只涉及PDF2swf路徑問題)
private String outputPath = "";// 輸入路徑 ,如果不設定就輸出在預設 的位置
private String fileName;
private File pdfFile;
private File swfFile;
private File docFile;


public DocConverterUtil(String fileString) {
ini(fileString);
System.out.println("檔案路徑" + fileString);
}


/**
* * 重新設定file

* @param fileString
*            32.
*/
public void setFile(String fileString) {
ini(fileString);
}


/**
* * 初始化

* @param fileString

*/
private void ini(String fileString) {
this.fileString = fileString;
fileName = fileString.substring(0, fileString.lastIndexOf("."));
docFile = new File(fileString);
pdfFile = new File(fileName + ".pdf");
swfFile = new File(fileName + ".swf");
}


/**
* 轉為PDF

* @param file

*/
private void doc2pdf() throws Exception {
//docFile = new File(fileString);
//System.out.println(docFile.exists());
if (docFile.exists()) {
System.out.println("====");
if (!pdfFile.exists()) {
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
try {
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(docFile, pdfFile);
// close the connection
connection.disconnect();
System.out.println("****pdf轉換成功,PDF輸出=====: " + pdfFile.getPath() + "****");
} catch (java.net.ConnectException e) {
e.printStackTrace();
System.out.println("****swf轉換器異常,openoffice 服務未啟動!****");
throw e;
} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
e.printStackTrace();
System.out.println("****swf轉換器異常,讀取轉換檔案 失敗****");
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else {
System.out.println("****已經轉換為pdf,不需要再進行轉化 ****");
}
} else {
System.out.println("****swf轉換器異常,需要轉換的文件不存在, 無法轉換****");
}
}


/** * 轉換成 swf */
@SuppressWarnings("unused")
private void pdf2swf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!swfFile.exists()) {
if (pdfFile.exists()) {
if (environment == 1) {// windows環境處理
try {
Process p = r.exec("E:/tools/pdf2swf.exe "
+ pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
System.out.print(loadStream(p.getInputStream()));
System.err.print(loadStream(p.getErrorStream()));
System.out.print(loadStream(p.getInputStream()));
System.err.println("****swf轉換成功,檔案輸出: " + swfFile.getPath() + "****");
if (pdfFile.exists()) {
//pdfFile.delete();
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
} else if (environment == 2) {// linux環境處理
try {
Process p = r.exec("pdf2swf" + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
System.out.print(loadStream(p.getInputStream()));
System.err.print(loadStream(p.getErrorStream()));
System.err.println("****swf轉換成功,檔案輸出: " + swfFile.getPath() + "****");
if (pdfFile.exists()) {
//pdfFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
} else {
System.out.println("****pdf不存在,無法轉換****");
}
} else {
System.out.println("****swf已經存在不需要轉換****");
}
}


static String loadStream(InputStream in) throws IOException {
int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer();
while ((ptr = in.read()) != -1) {
buffer.append((char) ptr);
}
return buffer.toString();
}


/**
* * 轉換主方法
*/
@SuppressWarnings("unused")
public boolean conver() {
if (swfFile.exists()) {
System.out.println("****swf轉換器開始工作,該檔案已經轉換為 swf****");
return true;
}
if (environment == 1) {
System.out.println("****swf轉換器開始工作,當前設定執行環境 windows****");
} else {
System.out.println("****swf轉換器開始工作,當前設定執行環境 linux****");
}
try {
doc2pdf();
pdf2swf();
} catch (Exception e) {
e.printStackTrace();
return false;
}
System.out.println("檔案存在嗎?" + swfFile);
if (swfFile.exists()) {
System.out.println("存在");
return true;
} else {
System.out.println("不存在");
return false;
}
}


/**
* 返回檔案路徑       @param     
*/
public String getswfPath() {
if (this.swfFile.exists()) {
String tempString = swfFile.getPath();
tempString = tempString.replaceAll("\\\\", "/");
System.out.println("最後檔案路徑為" + tempString);
return tempString;
} else {
return "檔案不存在";
}
}


/**
* 設定輸出路徑

* @param outputPath
*/
public void setOutputPath(String outputPath) {
this.outputPath = outputPath;
if (!outputPath.equals("")) {
String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
if (outputPath.charAt(outputPath.length()) == '/') {
swfFile = new File(outputPath + realName + ".swf");
} else {
swfFile = new File(outputPath + realName + ".swf");
}
}
}
}

接下來就是當你上傳檔案成功的同時,直接呼叫DocumentUtil工具類:

if ("".equals(msg)) {
makeSrvResult.setResultType(ResultType.Ok.getValue());
//上傳成功,同步生成pdf和swf檔案
DocumentUtil.topdfAndswf(request, document.getFilelink());
} else {
makeSrvResult.setResultType(ResultType.AppError.getValue());
makeSrvResult.setStackMsg(msg);
}

其中你要用的就是DocumentUtil.topdfAndswf(request, document.getFilelink());這句程式碼,其中document.getFilelink()這個就是你上傳成功的資料夾路徑,例如:upload/konwleage/file/20171116/20171116_1510815885273.doc,我這裡上傳方法不做解析,而在我們專案中這個資料夾是在tomcat中的,所以在這個DocumentUtil工具類中我獲取了tomcat路徑進行了拼接,後臺程式碼基本就是這些。

當點選預覽的時候我們需要拿到轉換後的swf檔案的路徑,預設應該是跟原檔案在一起的。

前端程式碼:

jsp頁面:

<%@page import="com.elitel.ioms.main.entity.UserInfo"%>
<%@ page language="java" import="java.util.*,com.elitel.ioms.core.common.*,com.elitel.ioms.base.comm.utils.*,javax.servlet.http.HttpServletRequest,com.elitel.ioms.main.entity.UserInfo" pageEncoding="UTF-8"%>
<%
String basePath = PathUtil.getBasePathFromRequest(request);
String userTheme = ThemeUtil.getUserTheme();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="${basePath}">
<%-- 瀏覽器相容 --%>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<jsp:include page="<%=PathUtil.url_cssjslib%>">
<jsp:param name="scope"
value="jQuery,bootstrap,artDialog,easyui" />
</jsp:include>
<script src="static/js/js_plugins/bootbox.js"></script>
<link href="static/theme/<%=userTheme%>/common/table.css" rel="stylesheet" type="text/css"> 
<link href="static/theme/<%=userTheme%>/common/button.css" rel="stylesheet" type="text/css">
<link href="static/theme/<%=userTheme%>/common/common.css" rel="stylesheet" type="text/css">
<link href="static/theme/<%=userTheme%>/common/commBusinessFrame.css" rel="stylesheet" type="text/css">
<link href="static/theme/<%=userTheme%>/knowleage/k01.css" rel="stylesheet" type="text/css">


<script type="text/javascript" src="static/js/knowleage/common/jquery.js"></script>
<script type="text/javascript" src="static/js/knowleage/common/flexpaper.js"></script>
<script type="text/javascript" src="static/js/knowleage/common/flexpaper_flash.js"></script>
<script type="text/javascript" src="static/js/knowleage/common/flexpaper_flash_debug.js"></script>

<script src="static/js/knowleage/k05.js"></script>
<style type="text/css" media="screen">
html, body {
height: 100%;
}


body {
margin: 0;
padding: 0;
overflow: auto;
}


#flashContent {
display: none;
}
</style>
<title>線上文件預覽</title>
</head>
<body>   
      <div id="viewerPlaceHolder" class="flexpaper_viewer" style="width:630px;height:670px;text-align:center;">
      
      </div> 

</body> 
</html>

注意看標紅的部分,

js程式碼:



var url = art.dialog.data('url');
$(function(){
DocumentView();
});
//預覽
function DocumentView(){
$("#viewerPlaceHolder").FlexPaperViewer(     
        { config : {  
        SWFFile : escape(url),  
        Scale : 1,   
        ZoomTransition : 'easeOut',  
        ZoomTime : 0.5,  
        ZoomInterval : 0.2,  
        FitPageOnLoad : false,  
        FitWidthOnLoad : true,  
        FullScreenAsMaxWindow : false,  
        ProgressiveLoading : false,  
        MinZoomSize : 0.5,  
        MaxZoomSize : 2,  
        SearchMatchAll : true,  
        InitViewMode : 'Portrait',
        ReaderingOrder :'false',
        StartAtPage :'',
        ViewModeToolsVisible : true,  
        ZoomToolsVisible : true,  
        NavToolsVisible : true,  
        CursorToolsVisible : true,  
        SearchToolsVisible : true,
        
        localeChain: 'zh_CN',  
        }});
}

其中這個url就是生成swf檔案的地方,預設是跟原檔案在一起的。


預覽效果:


相關推薦

javaofficepdf線上解析融合專案

最近在專案中要做一個文件的預覽,在網上搜了好多demo,都可以實現其功能,但是放在自己的專案中有點複雜。 先說明本人的開發環境(win7+tomcat7+maven+svn+myeclipse),接下來最直觀的專案需求,如下圖: 當用戶點選預覽的時候能看各種文件,其實在這

office轉html線上

要想實現office文件線上預覽,可以使用紅櫻楓軟體公司開發的資料格式轉換軟體HTML Filter,實現MS Office系列文件到HTML的快速轉換,通過瀏覽器瀏覽HTML的內容。該產品可以將 word轉html, excel轉html, ppt轉html,方便使用者

office(doc,xls,txt,pdf,ppt)線上及轉換(office2pdf)

本想用OpenOffice的類, 但OpenOffice的類太複雜了.. Google docs(谷歌文件)也是用的這個商業解決方案.. 當然還有PSVIEW 大家有興趣研究下..是開源的 但是在偷竊的心理作用下..決定利用了下Google的優良服務. 演示地址: ht

C# web實現word 轉Htmloffice轉Htmlpdf轉圖片 線上檔案

 改篇 pdf 預覽再本機沒問題,釋出再iis中 不行 ,(使用剪貼簿的問題..excel和word 可以,) 詳細配置及程式碼 word 轉Html 複製程式碼  1 /// <summary>  2         /// word轉成html  3  

Java Spring Boot 上傳地址解析

jar包 tof form loader index res for catch div @RequestMapping(value ="/upload",method = RequestMethod.POST) @Permission(isAjax=fa

java web通過openoffice實現網頁類似百度文庫

  最近研究了一下在網頁上預覽文件(包括office文件和txt、pdf),發現用openoffice+FlexPlayer實現比較理想,就參考了https://blog.csdn.net/ITBigGod/article/details/80300177#commentBox這個部落格自己研究了一下。原始碼

使用openoffice實現線上

下載地址:http://www.openoffice.org/zh-cn/download/ 安裝 wget https://jaist.dl.sourceforge.net/project/openofficeorg.mirror/4.1.6/binaries/zh-CN/Apache_OpenOffi

利用python3爬蟲下載圖片pdf

環境 語言環境:python3.6 作業系統:Win10 第三方庫 requests 網際網路上的資源大都是以二進位制形式儲存和運輸的,如圖片、pdf、音訊、視訊等,像.dat、.ts等這些不常用的檔案也都是二進位制。我們知道python3爬蟲是利用爬蟲模擬瀏覽器向服務端傳送請求

java 使用openoffice 轉換文,成.pdf,實現線上效果

1. 下載 openoffice 地址     https://pan.baidu.com/s/1dfpoG6zlawoW1pqpDvBL0A 密碼: v4ej     如果上面的地址無法訪問請訪問這個地址:下載地址如下:http://www.openof

學習筆記:從0開始學習大資料-30. solr通過java匯入doc,pdf建立全文檢索

1. eclipse 新建maven專案solr,pom.xml 加入依賴 2 在專案下新建類updoctest package com.linbin.solr; import java.io.File; import java.io.IOException; import org.

Java 如何給現有PDF新增頁碼

有些PDF文件沒有頁碼,使用者在閱讀的時候很不方便。這篇文章將介紹如何使用免費PDF Java元件 - Free Spire.PDF for Java給現有PDF文件新增頁碼。 匯入jar包 首先,下載Free Spire.PDF for Java元件包,並解壓縮,從lib資料夾下引用以

將jsp頁面生成wordexcelpdf

      開發過程中,有時要求將顯示查詢結果的jsp頁面生成word、excel、pdf等型別的文件,甚至可能要求將那些格式的文件下載下來,因為這樣更符合客戶的需求,也更利於他們的辦公使用。        基於此,上網查閱了一些資料,現簡單整理一下,以供自己和大家學習。

Qt 生成wordpdf

需求:將軟體處理的結果儲存為一個報告文件,文件中包含表格、圖片、文字,格式為word的.doc和.pdf。生成word是為了便於使用者編輯。 開發環境:qt4.8.4+vs2010 在qt的官網上

移動端利用pdf.js實現線上pdf

專案中要求在移動端實現線上預覽pdf檔案,通過一番折騰,最後選擇用pdf.js實現。1、下載pdf.js    官網地址:https://mozilla.github.io/pdf.js/2、各種配置    下載下來的檔案包,就是一個demo,我們仿照這個demo做就可以啦 

VS2010下asp.net 現有的PDF進行加密(利用iTextSharp)

到2011年8月iTextSharp最新版本下載地址: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI;

WPF查看PDF - 基於開源的MoonPdfPanel 無需安裝任何PDF閱讀器問題匯總

報錯 博客 mil iss 用法 責任 位置 通過 連接 致敬Yang-Fei—有一個簡單的用法示例: http://www.cnblogs.com/yang-fei/p/4885570.html。 寫MoonPdfPanel的哥們關於這個開源軟件的實現介紹

通過AsposeWord,Excel檔案進行Pdf轉換,實現線上

解決思路:1.利用AsposeCells,AsposeWords相關Jar包提供的轉換功能,將Excel及Word型別文件轉換為Pdf檔案,並存於當前專案目錄下2.通過瀏覽器的iframe標籤功能,直接訪問應用下的相關Pdf檔案,目前主流瀏覽器均支援直接在頁面上瀏覽Pdf檔案

基於MVC4+EasyUI的Web開發框架經驗總結8--實現Office

在部落格園很多文章裡面,曾經有一些介紹Office文件預覽檢視操作的,有些通過轉為PDF進行檢視,有些通過把它轉換為Flash進行檢視,但是過程都是曲線救國,真正能夠簡潔方便的實現Office文件的預覽的還是比較少,這裡的Office文件包括了Word、Excel、PPT文件。本文介紹兩種方式,一種方式是通過

Atitit.office word  excel  ppt pdf 的web線上方案與html轉換方案 attilax 總結

個人說明 提供相關技術諮詢,以及解決方案編制,編制相關標準化規範草案,軟體培訓與技術點體系建設,知識圖譜體系化,提供軟體行業顧問佈道,12年的軟體行業背景,歡迎有志於軟體行業的同仁們互相交流,群名稱:標準化規範工作組草案,群   號:518818717, 聯絡方式: [

Linux基礎管理——查找和壓縮高級使用方法

正則表達式 預覽 ges 模糊 [] 復制 pattern 臨時文件 mode 前言: GNU Linux操作系統的哲學思想之一即是一切皆是文件,因此使用必要的手段對文件進行搜索、匹配、處理、壓縮解壓,以實現快速定位、快速處置是十分必要的。1、文件搜索查找原理