1、开发前准备
1)下载第三方软件或插件进行安装
2)下载相关的jar包,如下图:
3)集成插件
解压FlexPaper_1.4.5_flash.zip,将以下文件移植到web目录下,如图
2、编写代码
readfile.jsp
只支持office文件在线预览,如doc,docx,ppt,pptx,xls,xlxs
UploadServlet.java
packageservlet;
importjava.io.File;
importjava.io.IOException;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.commons.fileupload.FileItem;
importorg.apache.commons.fileupload.FileUploadException;
importorg.apache.commons.fileupload.disk.DiskFileItemFactory;
importorg.apache.commons.fileupload.servlet.ServletFileUpload;
importutil.Office2Swf;
publicclassUploadServletextendsHttpServlet
{
privatestaticfinallongserialVersionUID= 1L;
@Override
protectedvoiddoGet(HttpServletRequest req, HttpServletResponse resp)
throwsServletException, IOException
{
String inputFilePath =this.uploadFile(req);
if(null!= inputFilePath && !"".equals(inputFilePath.trim()))
{
String outFilePath = inputFilePath.replace(newFile(inputFilePath).getName(), System.currentTimeMillis() +".swf");
outFilePath = Office2Swf.office2Swf(inputFilePath, outFilePath);
req.getSession().setAttribute("fileName",newFile(outFilePath).getName());
}
req.getRequestDispatcher("/readonline.jsp").forward(req, resp);
}
@Override
protectedvoiddoPost(HttpServletRequest req, HttpServletResponse resp)
throwsServletException, IOException
{
this.doGet(req, resp);
}
@SuppressWarnings({"unchecked","deprecation"})
privateString uploadFile(HttpServletRequest request)throwsServletException, IOException
{
request.setCharacterEncoding("utf-8");//设置编码
//获得磁盘文件条目工厂
DiskFileItemFactory factory =newDiskFileItemFactory();
//获取文件需要上传到的路径
String path = request.getRealPath("/upload");
factory.setRepository(newFile(path));
//设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室
factory.setSizeThreshold(1024*1024) ;
//文件上传处理
ServletFileUpload upload =newServletFileUpload(factory);
String uploadFilePath =null;
//可以上传多个文件
try{
List list = (List)upload.parseRequest(request);
for(FileItem item : list)
{
//获取表单的属性名字
String name = item.getFieldName();
//表单文本信息
if(item.isFormField())
{
String value = item.getString() ;
request.setAttribute(name, value);
}
//表单上传的文件
else
{
//获取路径
String value = item.getName() ;
intstart = value.lastIndexOf("\\");
//截取上传文件名称
String filename = value.substring(start+1);
request.setAttribute(name, filename);
item.write(newFile(path,filename));
uploadFilePath = path + File.separator+ filename;
}
}
}catch(FileUploadException e) {
e.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
returnuploadFilePath;
}
}
Office2PDF.java
packageutil;
importjava.io.File;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.regex.Pattern;
importorg.artofsolving.jodconverter.OfficeDocumentConverter;
importorg.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
importorg.artofsolving.jodconverter.office.OfficeManager;
/**
*
*@authorhwl_sz
*
*@desc需要OpenOffice第三插件的支持,支持window\linux\mac等系统
*/
publicclassOffice2PDF
{
publicstaticfinalString[]OFFICE_POSTFIXS= {"doc","docx","xls",
"xlsx","ppt","pptx"};
/**
*根据操作系统的名称,获取OpenOffice的安装目录
*如我的安装目录:C:/Program Files/OpenOffice 4
*/
privatestaticString getOfficeHome()
{
String osName = System.getProperty("os.name");
if(Pattern.matches("Linux.*", osName))
{
return"/opt/openoffice.org3";
}
elseif(Pattern.matches("Windows.*", osName))
{
return"C:/Program Files/OpenOffice 4";
}
elseif(Pattern.matches("Mac.*", osName))
{
return"/Application/OpenOffice.org.app/Contents";
}
returnnull;
}
/**
*转换文件
*
*@paraminputFilePath转换的office源文件路径
*@paramoutputFilePath输出目标文件路径
*/
privatestaticvoidconverterFile(String inputFilePath, String outputFilePath)
{
File inputFile =newFile(inputFilePath);
File outputFile =newFile(outputFilePath);
//假如目标路径不存在,则新建该路径
if(!outputFile.getParentFile().exists())
{
outputFile.getParentFile().mkdirs();
}
DefaultOfficeManagerConfiguration config =newDefaultOfficeManagerConfiguration();
//获取OpenOffice的安装目录
String officeHome = getOfficeHome();
config.setOfficeHome(officeHome);
//启动OpenOffice的服务
OfficeManager officeManager = config.buildOfficeManager();
officeManager.start();
OfficeDocumentConverter converter =newOfficeDocumentConverter(
officeManager);
converter.convert(inputFile, outputFile);
System.out.println("文件:"+ inputFilePath +"\n转换为\n目标文件:"+ outputFile
+"\n成功!");
officeManager.stop();
}
/**
*将(.doc|.docx|.xls|.xlsx|.ppt|.pptx)等office文件转化为pdf文件
*
*@paraminputFilePath待转换的源文件路径
*@paramoutputFilePath输出的目录文件路径,如果未指定(null),则按在源文件当前目录生成同名的pdf文件
*@return处理结果
*/
publicstaticbooleanopenOffice2Pdf(String inputFilePath, String outputFilePath)
{
booleanflag =false;
File inputFile =newFile(inputFilePath);
ArrayList office_Formats =newArrayList();
Collections.addAll(office_Formats,OFFICE_POSTFIXS);
if((null!= inputFilePath) && (inputFile.exists()))
{
//判断目标文件路径是否为空
if(office_Formats.contains(getPostfix(inputFilePath)))
{
if(null== outputFilePath)
{
//转换后的文件路径
String outputFilePath_new = inputFilePath.toLowerCase().replaceAll("."
+ getPostfix(inputFilePath),".pdf");
converterFile(inputFilePath, outputFilePath_new);
flag =true;
}
else
{
converterFile(inputFilePath, outputFilePath);
flag =true;
}
}
}
returnflag;
}
/**
*获取文件的后缀名
*/
privatestaticString getPostfix(String inputFilePath)
{
String[] p = inputFilePath.split("\\.");
if(p.length> 0)
{
returnp[p.length- 1];
}
else
{
returnnull;
}
}
/**
*@paramargs
*/
publicstaticvoidmain(String[] args)
{
Office2PDF.openOffice2Pdf("E:/黄色地球商务PPT模板.ppt",null);
}
}
Office2Swf.java
packageutil;
importjava.util.regex.Pattern;
/**
*
*@authorhwl_sz
*
*@desc需要swftools第三插件的支持,支持window\linux\mac等系统
*/
publicclassOffice2Swf
{
/**
*根据操作系统的名称,获取执行pdf->swf文件的命令
*@parampdfFile转换的pdf源文件路径
*@paramswfOutFilePath输出的swf文件路径
*@return
*/
privatestaticString getCommand(String pdfFile, String swfOutFilePath)
{
String command =null;
String osName = System.getProperty("os.name");
if(null== swfOutFilePath ||"".equals(swfOutFilePath.trim()))
{
swfOutFilePath = pdfFile.toLowerCase().replaceAll(".pdf",".swf");
}
if(Pattern.matches("Linux.*", osName))
{
command ="pdf2swf -f "+ pdfFile +" "+ swfOutFilePath;
}
elseif(Pattern.matches("Windows.*", osName))
{
command ="C:/Program Files/SWFTools/pdf2swf.exe -t "+ pdfFile +" -o "+ swfOutFilePath +" -T 9";
}
elseif(Pattern.matches("Mac.*", osName))
{
}
returncommand;
}
/**
*将pdf转换swf文件,在线预览
*@parampdfInputFilePath待转换的pdf源文件路径
*@paramswfOutFilePath输出的swf目标文件路径,如果未指定(null),则按在源文件当前目录生成同名的swf文件
*@returnswf目标文件路径
*/
publicstaticString pdf2Swf(String pdfInputFilePath, String swfOutFilePath)
{
String command = getCommand(pdfInputFilePath, swfOutFilePath);
try
{
Process pro = Runtime.getRuntime().exec(command);
pro.waitFor();
returnpdfInputFilePath.replaceAll("."+ getPostfix(pdfInputFilePath),".swf");
}
catch(Exception ex)
{
ex.printStackTrace();
}
returnnull;
}
/**
*将office文件直接转换为swf文件
*@paraminputFilePath待转换的源office文件路径
*@paramoutputSwfPath输出的swf目标文件路径,如果未指定(null),则按在源文件当前目录生成同名的swf文件
*@returnswf目标文件路径
*/
publicstaticString office2Swf(String inputFilePath, String outputSwfPath)
{
String outputPdfPath =null;
if(null== outputSwfPath ||"".equals(outputSwfPath.trim()))
{
outputPdfPath = inputFilePath.replace("."+ getPostfix(inputFilePath),".pdf");
}
else
{
outputPdfPath = outputSwfPath.replace("."+ getPostfix(outputSwfPath),".pdf");
}
booleanisSucc = Office2PDF.openOffice2Pdf(inputFilePath, outputPdfPath);
if(isSucc)
{
outputSwfPath = pdf2Swf(outputPdfPath, outputSwfPath);
}
returnoutputSwfPath;
}
/**
*获取文件的后缀名
*/
privatestaticString getPostfix(String inputFilePath)
{
String postfix =null;
if(null!= inputFilePath && !"".equals(inputFilePath.trim()))
{
intidx = inputFilePath.lastIndexOf(".");
if(idx > 0)
{
postfix = inputFilePath.substring(idx + 1, inputFilePath.trim().length());
}
}
returnpostfix;
}
}
readonline.jsp
在线预览--%>
varfp =newFlexPaperViewer(
'FlexPaper/swfFiles/FlexPaperViewer',
'viewerPlaceHolder',
{ config : {
SwfFile : escape('upload/'),
Scale : 0.6,
ZoomTransition :'easeOut',
ZoomTime : 0.5,
ZoomInterval : 0.2,
FitPageOnLoad :true,
FitWidthOnLoad :false,
PrintEnabled :true,
FullScreenAsMaxWindow :false,
ProgressiveLoading :false,
MinZoomSize : 0.2,
MaxZoomSize : 5,
SearchMatchAll :false,
InitViewMode :'Portrait',
ViewModeToolsVisible :true,
ZoomToolsVisible :true,
NavToolsVisible :true,
CursorToolsVisible :true,
SearchToolsVisible :true,
localeChain:'en_US'
}});