前言 當前的主瀏覽器都支持直接打開pdf文件,從而實現文件預覽。如果是其他格式文件則得下載,因此用openOffice實現文件轉pdf格式。 一、 openOffice的安裝 下載地址:http://www.openoffice.org/ 安裝教程可參考:openOffice下載和安裝 進入安裝目錄 ...
前言
當前的主瀏覽器都支持直接打開pdf文件,從而實現文件預覽。如果是其他格式文件則得下載,因此用openOffice實現文件轉pdf格式。
一、 openOffice的安裝
-
下載地址:http://www.openoffice.org/
安裝教程可參考:openOffice下載和安裝 -
進入安裝目錄,輸入cmd
-
命令視窗輸入以下命令啟動:
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" –nofirststartwizard
二、測試
- 導包
<!--openoffice-->
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
- 文件工具類
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 Simon
* @version 1.0
* @since JDK1.8
*/
public class FileConvertUtil {
/** 預設轉換後文件尾碼 */
private static final String DEFAULT_SUFFIX = "pdf";
/** openoffice_port */
public static final String DEFAULT_HOST = "127.0.0.1";
private static final Integer OPENOFFICE_PORT = 8100;
/**
* office文檔轉換為PDF(處理本地文件)
*/
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(處理網路文件)
*/
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;
}
/**
* 將文件以流的形式轉換
*/
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
*/
public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
return new ByteArrayInputStream(baos.toByteArray());
}
}
- controler層代碼
@PostMapping("/onlinePreview")
public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception {
//獲取文件類型 根據實際的url截斷
String suffix = url.substring(url.lastIndexOf('.') + 1);
if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
&& !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx") && !suffix.equals("sheet") && !suffix.equals("pdf")) {
throw new Exception("文件格式不支持預覽");
}
//我的文件是存在本地上的,該url是為了別的電腦能訪問到,再傳到這的時候就是解析本地文件了,所以找到我的本地文件路徑
//根據具體情況來,否則會報錯
url=url.replace("192.168.1.125:8765/knowledge/","G:/creo/knowledge/");
//處理本地文件
InputStream in = FileConvertUtil.convertLocaleFile(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();
}
- 常見異常
java.lang.IllegalArgumentException: inputFormat is null at com.artofsolving.jodconverter.openoffice.converter.AbstractOpenOfficeDocumentConverter.ensureNotNull(AbstractOpenOfficeDocumentConverter.java:113)
這是因為轉換07版本及高版本(.docx/.xlsx/.pptx)時,這三種格式不在所支持的文件格式中。
** 解決辦法: **
重寫BasicDocumentFormatRegistry (一定得在com.artofsolving.jodconverter包下)
package com.artofsolving.jodconverter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
private List documentFormats = new ArrayList();
public BasicDocumentFormatRegistry() {
}
public void addDocumentFormat(DocumentFormat documentFormat) {
this.documentFormats.add(documentFormat);
}
protected List getDocumentFormats() {
return this.documentFormats;
}
public DocumentFormat getFormatByFileExtension(String extension) {
if (extension == null) {
return null;
} else {
if (extension.indexOf("doc") >= 0) {
extension = "doc";
}
if (extension.indexOf("ppt") >= 0) {
extension = "ppt";
}
if (extension.indexOf("xls") >= 0) {
extension = "xls";
}
String lowerExtension = extension.toLowerCase();
Iterator it = this.documentFormats.iterator();
DocumentFormat format;
do {
if (!it.hasNext()) {
return null;
}
format = (DocumentFormat)it.next();
} while(!format.getFileExtension().equals(lowerExtension));
return format;
}
}
public DocumentFormat getFormatByMimeType(String mimeType) {
Iterator it = this.documentFormats.iterator();
DocumentFormat format;
do {
if (!it.hasNext()) {
return null;
}
format = (DocumentFormat)it.next();
} while(!format.getMimeType().equals(mimeType));
return format;
}
}
參考:解決jodconverter 2.2.1 版本不支持docx、xlsx、pptx 轉換成PDF格式異常