java实现文件预览思路和代码分享
思路:在保存文件的时候,先把文件转成pdf,再转成swf文件,预览的时候地址直接指向这个swf文件即可在浏览器中预览。下面代码赋值就可以使用
1.到百度下载openoffice,并安装到本地的D:\OpenOffice目录下。
2.下载pdf2swf.exe工具到web项目的/WebRoot/swftools下
3.代码实现如下:
调用下面方法即可 convert2SWF(String inputFile),其中
inputFile指向文件的物理地址D:/files/20171122161000D8SzydDq.doc
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
javax.servlet.http.HttpServletRequest;
import
net.sourceforge.pinyin4j.PinyinHelper;
import
org.apache.log4j.Logger;
import
org.artofsolving.jodconverter.OfficeDocumentConverter;
import
org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import
org.artofsolving.jodconverter.office.OfficeManager;
import
org.springframework.web.context.request.RequestContextHolder;
import
org.springframework.web.context.request.ServletRequestAttributes;
/**
* OFFICE文档转换服务类
*/
public
class
OpenOfficePDFConverter {
private
static
final
Logger logger = Logger.getLogger(OpenOfficePDFConverter.
class
);
private
static
OfficeManager officeManager;
/** OpenOffice安装根目录 */
private
static
String OFFICE_HOME =
"D:/openOnline"
;
private
static
int
[] port = {
8100
};
public
void
convert2SWF(String inputFile) {
//inputFile指向文件的物理地址D:/files/20171122161000D8SzydDq.doc
String extend=getExtend(inputFile,
""
);
if
(extend.equals(
"pdf"
))
{
String swfFile = getPinYinHeadChar(getFilePrefix2(inputFile)) +
".swf"
;
convert2SWF(inputFile, swfFile, extend);
}
if
(extend.equals(
"doc"
)||extend.equals(
"docx"
)||extend.equals(
"xls"
)||extend.equals(
"pptx"
)||extend.equals(
"xlsx"
)||
extend.equals(
"ppt"
)||extend.equals(
"txt"
)||extend.equals(
"odt"
))
{
String pdfFile = getFilePrefix2(inputFile) +
".pdf"
;
convert2PDF(inputFile, pdfFile, extend);
extend=getExtend(pdfFile,
""
);
String swfFile = getPinYinHeadChar(getFilePrefix2(inputFile)) +
".swf"
;
convert2SWF(pdfFile, swfFile, extend);
}
}
public
void
convert2SWF(String inputFile, String swfFile, String extend) {
File pdfFile =
new
File(inputFile);
File outFile =
new
File(swfFile);
if
(!pdfFile.exists()) {
logger.info(
"PDF文件不存在!"
);
return
;
}
if
(outFile.exists()) {
logger.info(
"SWF文件已存在!"
);
return
;
}
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String SWFTOOLS_HOME=request.getSession().getServletContext().getRealPath(
"/"
) +
"swftools/pdf2swf.exe"
;
String command = SWFTOOLS_HOME +
" \""
+ inputFile
//---update-for--文件预览无效------ scott@2013/05/22 ADD START
+
"\" -o "
+
" \""
+ swfFile +
" \""
+
" -s languagedir=D:\\xpdf-chinese-simplified -T 9 -f"
;
// + "\" -o " + swfFile + " -s languagedir=D:\\xpdf-chinese-simplified -T 9 -f";
// ---update-for--文件预览无效----- scott@2013/05/22 ADD END
try
{
// 开始转换文档
Process process = Runtime.getRuntime().exec(command);
try
{
process.waitFor();
logger.info(
"时间-------"
+process.waitFor());
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
catch
(IOException e) {
e.printStackTrace();
}
}
public
void
convert2PDF(String inputFile, String pdfFile, String extend) {
if
(extend.equals(
"txt"
)) {
String odtFile = getFilePrefix(inputFile) +
".odt"
;
if
(
new
File(odtFile).exists()) {
logger.info(
"odt文件已存在!"
);
inputFile = odtFile;
}
else
{
try
{
copyFile(inputFile, odtFile);
inputFile = odtFile;
}
catch
(FileNotFoundException e) {
logger.info(
"Odt文档不存在!"
);
e.printStackTrace();
}
}
}
startService();
//pdfFile = pdfFile.replaceAll(" ", "").replaceAll(" ", "");
logger.info(
"进行文档转换转换:"
+ inputFile +
" --> "
+ pdfFile);
OfficeDocumentConverter converter =
new
OfficeDocumentConverter(
officeManager);
try
{
converter.convert(
new
File(inputFile),
new
File(pdfFile));
}
catch
(Exception e) {
// TODO: handle exception
}
stopService();
logger.info(
"进行文档转换转换---- 结束----"
);
}
public
static
void
startService() {
DefaultOfficeManagerConfiguration configuration =
new
DefaultOfficeManagerConfiguration();
try
{
// 准备启动服务
configuration.setOfficeHome(OFFICE_HOME);
// 设置OpenOffice.org安装目录
// 设置转换端口,默认为8100
configuration.setPortNumbers(port);
// 设置任务执行超时为5分钟
configuration.setTaskExecutionTimeout(
1000
*
60
* 5L);
// 设置任务队列超时为24小时
configuration.setTaskQueueTimeout(
1000
*
60
*
60
* 24L);
officeManager = configuration.buildOfficeManager();
officeManager.start();
// 启动服务
logger.info(
"office转换服务启动成功!"
);
}
catch
(Exception ce) {
logger.info(
"office转换服务启动失败!详细信息:"
+ ce);
}
}
public
static
void
stopService() {
logger.info(
"关闭office转换服务...."
);
if
(officeManager !=
null
) {
officeManager.stop();
}
logger.info(
"关闭office转换成功!"
);
}
/**
* 获取文件名称[不含后缀名]
* 不去掉文件目录的空格
*/
public
String getFilePrefix2(String fileName) {
int
splitIndex = fileName.lastIndexOf(
"."
);
return
fileName.substring(
0
, splitIndex);
}
/**
* 获取文件名称[不含后缀名]
*
* @param
* @return String
*/
public
static
String getFilePrefix(String fileName) {
int
splitIndex = fileName.lastIndexOf(
"."
);
return
fileName.substring(
0
, splitIndex).replaceAll(
"\\s*"
,
""
);
}
/**
* 提取每个汉字的首字母
*/
public
static
String getPinYinHeadChar(String str) {
String convert =
""
;
for
(
int
j =
0
; j < str.length(); j++) {
char
word = str.charAt(j);
// 提取汉字的首字母
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if
(pinyinArray !=
null
) {
convert += pinyinArray[
0
].charAt(
0
);
}
else
{
convert += word;
}
}
return
convert;
}
/**
* 获取文件扩展名
*/
public
static
String getExtend(String filename, String defExt) {
if
((filename !=
null
) && (filename.length() >
0
)) {
int
i = filename.lastIndexOf(
'.'
);
if
((i >
0
) && (i < (filename.length() -
1
))) {
return
(filename.substring(i+
1
)).toLowerCase();
}
}
return
defExt.toLowerCase();
}
/**
* 文件复制
*方法摘要:这里一句话描述方法的用途
*@param
*@return void
*/
public
static
void
copyFile(String inputFile,String outputFile)
throws
FileNotFoundException{
File sFile =
new
File(inputFile);
File tFile =
new
File(outputFile);
FileInputStream fis =
new
FileInputStream(sFile);
FileOutputStream fos =
new
FileOutputStream(tFile);
int
temp =
0
;
byte
[] buf =
new
byte
[
10240
];
try
{
while
((temp = fis.read(buf))!=-
1
){
fos.write(buf,
0
, temp);
}
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
try
{
fis.close();
fos.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
}