最近项目上打算做一个文档的在线浏览器(主要是文本文件),但是考虑到有可能有word,excel之类文档也需要在线浏览,所以采取:文档--->PDF---->swf(前端FlexPaper浏览)
这里只贴一下文档转PDF,PDF转swf的代码
文档转PDF使用OpenOffice和以下几个jar包实现
主要java代码:
// 获取转换配置
DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
DocumentFormat format = formatReg.getFormatByFileExtension(fileExt);
// 不存在的文档类型全部使用txt的format,默认的txt Format使用utf8编码
if (format == null) {
format = formatReg.getFormatByFileExtension("txt");
}
try {
converter.convert(source, format, pdfFile,
formatReg.getFormatByFileExtension("pdf"));
pdfFile.createNewFile();
} catch (ConnectException e) {
e.printStackTrace();
} catch (OpenOfficeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
我这里默认扩展名不存在的文档类型全部是纯文档类型(java,jsp文件等等),来看下txt的配置(jodconverter-2.2.2.jar 里面的document-formats.xml文件中)
<document-format>
<name>Plain Text</name>
<family>Text</family>
<mime-type>text/plain</mime-type>
<file-extension>txt</file-extension>
<export-options>
<entry>
<family>Text</family>
<map>
<entry>
<string>FilterOptions</string>
<string>UTF8,CRLF</string>
</entry>
<entry>
<string>FilterName</string>
<string>Text (encoded)</string>
</entry>
</map>
</entry>
</export-options>
<import-options>
<entry>
<string>FilterOptions</string>
<string>UTF8,CRLF</string>
</entry>
<entry>
<string>FilterName</string>
<string>Text (encoded)</string>
</entry>
</import-options>
</document-format>
这里要注意的是纯文本文件需以utf-8编写,否则将导致转出来的pdf中文乱码
pdf文件转换为swf供flash播放器(FlexPaper)使用
这里使用SWFTool就可以了,区别是在windows和在linux系统下实现不一样(我这里服务器是win server2003):
windows操作系统使用:
Runtime r = Runtime.getRuntime();
Process p = r.exec(SWFTOOLS_PDF2SWF_EXE_PATH + " " + pdfPath + " -o " + swfFile.getPath() + " -T 9 -s flashversion=9");
p.waitFor();
swfFile.createNewFile();
其实就是在Java中执行一条cmd命令来转换