java實作辦公檔案在線預覽功能是一個大家在作業中也許會遇到的需求,網上些公司專門提供這樣的服務,不過需要收費 如果想要免費的,可以用openoffice,實作原理就是:
通過第三方工具openoffice,將word、excel、ppt、txt等檔案轉換為pdf檔案流;
當然如果裝了Adobe Reader XI,那把pdf直接拖到瀏覽器頁面就可以直接打開預覽,前提就是瀏覽器支持pdf檔案瀏覽,
我這里介紹通過poi實作word、excel、ppt轉pdf流,這樣就可以在瀏覽器上實作預覽了,
1.到官網下載Apache OpenOffice 安裝包,安裝運行,
不同系統的安裝方法,自行百度,這里不做過多說明,

2.再專案的pom檔案中引入依賴
<!--openoffice-->
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
3.將word、excel、ppt轉換為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;
/**
* 檔案格式轉換工具類
*
* @author tarzan
* @version 1.0
* @since JDK1.8
*/
public class FileConvertUtil {
/** 默認轉換后檔案后綴 */
private static final String DEFAULT_SUFFIX = "pdf";
/** openoffice_port */
private static final Integer OPENOFFICE_PORT = 8100;
/**
* 方法描述 office檔案轉換為PDF(處理本地檔案)
*
* @param sourcePath 源檔案路徑
* @param suffix 源檔案后綴
* @return InputStream 轉換后檔案輸入流
* @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檔案轉換為PDF(處理網路檔案)
*
* @param netFileUrl 網路檔案路徑
* @param suffix 檔案后綴
* @return InputStream 轉換后檔案輸入流
* @author tarzan
*/
public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
// 創建URL
URL url = new URL(netFileUrl);
// 試圖連接并取得回傳狀態碼
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;
}
/**
* 方法描述 將檔案以流的形式轉換
*
* @param inputStream 源檔案輸入流
* @param suffix 源檔案后綴
* @return InputStream 轉換后檔案輸入流
* @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轉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");
}
}
4.serve層在線預覽方法代碼
/**
* @Description:系統檔案在線預覽介面
* @Author: tarzan
*/
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("檔案格式不支持預覽");
}
InputStream in=FileConvertUtil.convertNetFile(url,suffix);
OutputStream outputStream = response.getOutputStream();
//創建存放檔案內容的陣列
byte[] buff =new byte[1024];
//所讀取的內容使用n來接收
int n;
//當沒有讀取完時,繼續讀取,回圈
while((n=in.read(buff))!=-1){
//將位元組陣列的資料全部寫入到輸出流中
outputStream.write(buff,0,n);
}
//強制將快取區的資料進行輸出
outputStream.flush();
//關流
outputStream.close();
in.close();
}
5.controler層代碼
@ApiOperation(value = "https://www.cnblogs.com/javastack/p/系統檔案在線預覽介面 by tarzan")
@PostMapping("/api/file/onlinePreview")
public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{
fileService.onlinePreview(url,response);
}
原文鏈接:https://blog.csdn.net/weixin_40986713/article/details/109527294
著作權宣告:本文為CSDN博主「洛陽泰山」的原創文章,遵循CC 4.0 BY-SA著作權協議,轉載請附上原文出處鏈接及本宣告,
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2021最新版)
2.別在再滿屏的 if/ else 了,試試策略模式,真香!!
3.臥槽!Java 中的 xx ≠ null 是什么新語法?
4.Spring Boot 2.6 正式發布,一大波新特性,,
5.《Java開發手冊(嵩山版)》最新發布,速速下載!
覺得不錯,別忘了隨手點贊+轉發哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/376826.html
標籤:Java
上一篇:實作用戶注冊功能2
下一篇:SpringSecurity
