Java中實(shí)現(xiàn)文件預(yù)覽的功能(實(shí)例代碼)
前言
日常開發(fā)中常見的文件格式有pdf,word,Excel,PPT,Html,txt,圖片等。pdf,Html,txt,圖片這種實(shí)現(xiàn)在線預(yù)覽非常簡(jiǎn)單,有一些前端的插件可以滿足要求。word,Excel,PPT如果要實(shí)現(xiàn)在線預(yù)覽,就非常的困難。word,Excel,PPT實(shí)現(xiàn)在線預(yù)覽常用的方式就是先轉(zhuǎn)換成pdf,然后在進(jìn)行預(yù)覽。下面我就介紹常用的幾種方案
一、kkfileview 文件在線預(yù)覽
此項(xiàng)目為文件文檔在線預(yù)覽項(xiàng)目解決方案,項(xiàng)目使用流行的 spring boot 搭建,易上手和部署,部署好后可以獨(dú)立提供預(yù)覽服務(wù),使用 http 接口訪問,不需要和應(yīng)用集成,具有跨系統(tǒng)跨語言使用的特性。提供 zip/tar.gz 發(fā)行包、自定義配置文件、和啟動(dòng) / 停止腳本等,極大方便部署使用,同時(shí)官方發(fā)布 Docker 鏡像,方便容器環(huán)境中部署使用。基本支持主流辦公文檔的在線預(yù)覽,如 doc,docx,dwg, ofd, xls,xlsx,ppt,pptx,pdf,txt,zip,rar,7z,mp3,mp4,flv 圖片等等。
項(xiàng)目地址:https://gitee.com/kekingcn/file-online-preview
項(xiàng)目官網(wǎng):https://kkfileview.keking.cn
二、officetohtml純前端的方式
用純 javascript 編寫的 jQuery 插件,用于將現(xiàn)代 Microsoft Office 文件、pptx、docx、xlsx 和 pdf 轉(zhuǎn)換為 html。
實(shí)際上它是一個(gè)應(yīng)用程序,它集成了其他庫,如PPTXjs, mammoth.js,SheetJs結(jié)合 handsontable 和PDF.js,旨在將 Office 文件和 pdf 文件轉(zhuǎn)換為 HTML。
項(xiàng)目官網(wǎng):https://officetohtml.js.org/index.html
三、JODConverter
JODConverter是一種Java OpenDocument轉(zhuǎn)換器,能夠轉(zhuǎn)換不同格式的文檔,它依賴于Apache OpenOffice或 LibreOffice ,它為OpenDocument和Microsoft Office提供了最好的免費(fèi)導(dǎo)入/導(dǎo)出的過濾器。
JODConverter可以用在這幾種地方:
作為一個(gè)Java類庫,嵌入到你的Java應(yīng)用程序中。
作為一個(gè)命令行工具,可以在你的腳本中調(diào)用。
作為一個(gè)簡(jiǎn)單的web應(yīng)用,上傳文檔,選擇轉(zhuǎn)換的格式并下載轉(zhuǎn)換后的版本。
可以用openoffice,實(shí)現(xiàn)原理就是:
通過第三方工具openoffice,將word、excel、ppt、txt等文件轉(zhuǎn)換為pdf文件流;這樣就可以在瀏覽器上實(shí)現(xiàn)預(yù)覽了。
先去openoffice官網(wǎng)下載進(jìn)行安裝,官網(wǎng)地址:https://www.openoffice.org/download/ 安裝完成后啟動(dòng)。

java中的代碼如下:
Maven中添加如下依賴
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>將word、excel、ppt轉(zhuǎn)換為pdf流的工具類代碼
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* 文件格式轉(zhuǎn)換工具類
*
* @version 1.0
* @since JDK1.8
*/
public class FileConvertUtil {
/** 默認(rèn)轉(zhuǎn)換后文件后綴 */
private static final String DEFAULT_SUFFIX = "pdf";
/** openoffice_port */
private static final Integer OPENOFFICE_PORT = 8100;
/**
* 方法描述 office文檔轉(zhuǎn)換為PDF(處理本地文件)
*
* @param sourcePath 源文件路徑
* @param suffix 源文件后綴
* @return InputStream 轉(zhuǎn)換后文件輸入流
* @author tarzan
*/
public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
File inputFile = new File(sourcePath);
InputStream inputStream = new FileInputStream(inputFile);
return covertCommonByStream(inputStream, suffix);
}
/**
* 方法描述 office文檔轉(zhuǎn)換為PDF(處理網(wǎng)絡(luò)文件)
*
* @param netFileUrl 網(wǎng)絡(luò)文件路徑
* @param suffix 文件后綴
* @return InputStream 轉(zhuǎn)換后文件輸入流
* @author tarzan
*/
public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
// 創(chuàng)建URL
URL url = new URL(netFileUrl);
// 試圖連接并取得返回狀態(tài)碼
URLConnection urlconn = url.openConnection();
urlconn.connect();
HttpURLConnection httpconn = (HttpURLConnection) urlconn;
int httpResult = httpconn.getResponseCode();
if (httpResult == HttpURLConnection.HTTP_OK) {
InputStream inputStream = urlconn.getInputStream();
return covertCommonByStream(inputStream, suffix);
}
return null;
}
/**
* 方法描述 將文件以流的形式轉(zhuǎn)換
*
* @param inputStream 源文件輸入流
* @param suffix 源文件后綴
* @return InputStream 轉(zhuǎn)換后文件輸入流
* @author tarzan
*/
public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_PORT);
connection.connect();
DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
converter.convert(inputStream, sourceFormat, out, targetFormat);
connection.disconnect();
return outputStreamConvertInputStream(out);
}
/**
* 方法描述 outputStream轉(zhuǎn)inputStream
*
* @author tarzan
*/
public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
return new ByteArrayInputStream(baos.toByteArray());
}
public static void main(String[] args) throws IOException {
//convertNetFile("http://172.16.10.21/files/home/upload/department/base/201912090541573c6abdf2394d4ae3b7049dcee456d4f7.doc", ".pdf");
//convert("c:/Users/admin/Desktop/2.pdf", "c:/Users/admin/Desktop/3.pdf");
}
}serve層在線預(yù)覽方法代碼
/**
* @Description:系統(tǒng)文件在線預(yù)覽接口
*/
public void onlinePreview(String url, HttpServletResponse response) throws Exception {
//獲取文件類型
String[] str = SmartStringUtil.split(url,"\\.");
if(str.length==0){
throw new Exception("文件格式不正確");
}
String suffix = str[str.length-1];
if(!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
&& !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")){
throw new Exception("文件格式不支持預(yù)覽");
}
InputStream in=FileConvertUtil.convertNetFile(url,suffix);
OutputStream outputStream = response.getOutputStream();
//創(chuàng)建存放文件內(nèi)容的數(shù)組
byte[] buff =new byte[1024];
//所讀取的內(nèi)容使用n來接收
int n;
//當(dāng)沒有讀取完時(shí),繼續(xù)讀取,循環(huán)
while((n=in.read(buff))!=-1){
//將字節(jié)數(shù)組的數(shù)據(jù)全部寫入到輸出流中
outputStream.write(buff,0,n);
}
//強(qiáng)制將緩存區(qū)的數(shù)據(jù)進(jìn)行輸出
outputStream.flush();
//關(guān)流
outputStream.close();
in.close();
}四、Aspose
Aspose.Words是一款先進(jìn)的類庫,通過它可以直接在各個(gè)應(yīng)用程序中執(zhí)行各種文檔處理任務(wù)。Aspose.Words支持DOC,OOXML,RTF,HTML,OpenDocument, PDF, XPS, EPUB和其他格式。使用Aspose.Words,可以生成,更改,轉(zhuǎn)換,渲染和打印文檔而不使用Microsoft Word。
實(shí)現(xiàn)原理也是通過Aspose把文件轉(zhuǎn)換成pdf然后在預(yù)覽,實(shí)現(xiàn)步驟如下:
添加jar包,下載地址:https://download.csdn.net/download/xinghui_liu/85931977
配置License.xml,去掉水印
<?xml version="1.0" encoding="UTF-8" ?>
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>添加如下工具類,程序中調(diào)用doc2pdf即可實(shí)現(xiàn)文件轉(zhuǎn)pdf
package com.weemambo.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
public class Word2PdfAsposeUtil {
public static boolean getLicense() {
boolean result = false;
InputStream is = null;
try {
Resource resource = new ClassPathResource("license.xml");
is = resource.getInputStream();
//InputStream is = Word2PdfAsposeUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml應(yīng)放在..\WebRoot\WEB-INF\classes路徑下
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static boolean doc2pdf(String inPath, String outPath) {
if (!getLicense()) { // 驗(yàn)證License 若不驗(yàn)證則轉(zhuǎn)化出的pdf文檔會(huì)有水印產(chǎn)生
return false;
}
FileOutputStream os = null;
try {
long old = System.currentTimeMillis();
File file = new File(outPath); // 新建一個(gè)空白pdf文檔
os = new FileOutputStream(file);
Document doc = new Document(inPath); // Address是將要被轉(zhuǎn)化的word文檔
doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
// EPUB, XPS, SWF 相互轉(zhuǎn)換
long now = System.currentTimeMillis();
System.out.println("pdf轉(zhuǎn)換成功,共耗時(shí):" + ((now - old) / 1000.0) + "秒"); // 轉(zhuǎn)化用時(shí)
} catch (Exception e) {
e.printStackTrace();
return false;
}finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
}如上代碼在window下不會(huì)出現(xiàn)亂碼,在Linux系統(tǒng)中會(huì)出現(xiàn)亂碼,原因?yàn)長(zhǎng)inux系統(tǒng)中缺少相應(yīng)的字體。解決方案如下:
獲取window字體C:\Windows\Fonts目錄下字體復(fù)制到 Linux /usr/share/fonts/win,具體步驟如下:
1.把字體上傳到ninux服務(wù)器。這里上傳到 /home 目錄。
2.把剛剛上傳的字體解壓:unzip Fonts.zip -d Fonts
3.創(chuàng)建字體目錄:mkdir /usr/share/fonts/win
4.把解壓后的字體復(fù)制到創(chuàng)建的字體目錄中:cp /home/Fonts/Fonts/* /usr/share/fonts/win
5.安裝字體:
cd /usr/share/fonts sudo mkfontscale sudo mkfontdir sudo fc-cache -fv
6.執(zhí)行命令讓字體生效
source /etc/profile
7.如果安裝失敗,可以考慮修改字體權(quán)限
chmod 755 *.ttf
8.重啟服務(wù)器就可以正常轉(zhuǎn)換了
總結(jié)
上面介紹了四種文件預(yù)覽的方法,每種方法的優(yōu)缺點(diǎn)如下:
方法一:kkfileview支持文件格式多,而且不用開發(fā)。不過需要單獨(dú)部署一個(gè)文件預(yù)覽的服務(wù),而且服務(wù)器也需要安裝openoffice。
方法二:officetohtml純前端的方式可以不用安裝任何插件及服務(wù),但是目前只支持文件地址的方式預(yù)覽,如果是文件流的話無法使用
方法三:JODConverter 依賴于openoffice,需要在服務(wù)器單獨(dú)安裝openoffice。
方法四:Aspose使用的是破解版的,如果商用使用需要考慮版權(quán)問題。
綜上所述,如果不能在服務(wù)器安裝相應(yīng)的軟件,而且程序中的附件是以地址的方式訪問的話使用officetohtml。如果服務(wù)器可以安裝插件,優(yōu)先kkfileview,Aspose,JODConverter 。
三,四都是將文件轉(zhuǎn)換成pdf,前端可以使用pdfjs,官網(wǎng)地址為:http://mozilla.github.io/pdf.js/getting_started/#download
下載完成后放入到項(xiàng)目中,如下:

在項(xiàng)目中新建一個(gè)viewPdf.jsp頁面:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<title>文件預(yù)覽</title>
<head>
<meta charset="UTF-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/resources/layui/css/layui.css" rel="external nofollow" >
<script type="text/javascript" src="<%=request.getContextPath()%>/resources/layui/layui.js?v=1.1"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {
$("#pdf").attr("height", $(document).height());
var fileId='${fileId}';
var url = "${pageContext.request.contextPath}/pdfjs/web/viewer.html?file=${pageContext.request.contextPath}/xxxx.do?fileId="+fileId;
$("#pdf").attr("src", url);
})
</script>
</head>
<body>
<div class="main">
<iframe id="pdf" width="100%"></iframe>
</div>
</body>
</html>file后面可以直接寫一個(gè)文件地址,如果是文件流的方式寫一個(gè)后端的請(qǐng)求并傳遞相應(yīng)的參差。文件流要注意的地方是下面這個(gè)要設(shè)置為inline
response.setHeader(“Content-disposition”, “inline; filename=” + fileName);
參考資料:
https://blog.csdn.net/weixin_40986713/article/details/109527294
https://blog.csdn.net/qq_20143059/article/details/106427297
https://blog.csdn.net/wybaby168/article/details/122842866
到此這篇關(guān)于Java中如何實(shí)現(xiàn)文件預(yù)覽的功能的文章就介紹到這了,更多相關(guān)java文件預(yù)覽內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Struts 2 實(shí)現(xiàn)Action的幾種方式
本篇文章主要介紹了Struts 2 實(shí)現(xiàn)Action的幾種方式,Struts 2框架下實(shí)現(xiàn)Action類有三種方式,有興趣的可以了解一下2017-10-10
Java請(qǐng)求Http接口OkHttp超詳細(xì)講解(附帶工具類)
這篇文章主要給大家介紹了關(guān)于Java請(qǐng)求Http接口OkHttp超詳細(xì)講解的相關(guān)資料,OkHttp是一款優(yōu)秀的HTTP客戶端框架,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2024-02-02
微服務(wù)中使用Maven BOM來管理你的版本依賴詳解
這篇文章主要介紹了微服務(wù)中使用Maven BOM來管理你的版本依賴,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Servlet實(shí)現(xiàn)共享數(shù)據(jù)JavaWeb組件的幾種方法
本文將結(jié)合實(shí)例代碼,介紹Servlet實(shí)現(xiàn)共享數(shù)據(jù)JavaWeb組件的幾種方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07
SpringBoot+Vue中的Token續(xù)簽機(jī)制
本文主要介紹了SpringBoot+Vue中的Token續(xù)簽機(jī)制,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06

