1.JODConverter介绍:
JODConverter automates conversions between office document formats using or LibreOffice.
Supported formats include OpenDocument, PDF, RTF, HTML, Word, Excel, PowerPoint, and Flash.
It can be used as a Java library, a command line tool, or a web application.
JODConverter可以将一般格式的文档转换为PDF格式。
官网地址:/p/jodconverter/
下载地址:/detail/jolingogo/5074520
2.示例
这里用的是3.0的版本
[java]view plaincopyOfficeManagerofficeManager=newDefaultOfficeManagerConfiguration().buildOfficeManager(); officeManager.start(); OfficeDocumentConverterconverter=newOfficeDocumentConverter(officeManager); converter.convert(newFile("test.odt"),newFile("test.pdf"); officeManager.stop(); 如果你直接运行这些代码的话,是不会成功的,报一个错误[java]view plaincopyExceptioninthread"main"java.lang.IllegalStateException:officeHomenotsetandcouldnotbeauto-detected atorg.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration.buildOfficeManager(DefaultOfficeManagerConfiguration.java:163) atorg.ygy.util.PDFUtil.toPDF(PDFUtil.java:11) atorg.ygy.util.PDFUtil.main(PDFUtil.java:21) 要使用JODconverter需要安装OpenOffice或者LibreOffice,我安装了OpenOffice。
然后设置一下officeHome:
[java]view plaincopypublicstaticvoidtoPDF(){ OfficeManagerofficeManager=newDefaultOfficeManagerConfiguration() .setOfficeHome("D:\\programfiles\\3") .buildOfficeManager(); officeManager.start(); OfficeDocumentConverterconverter=newOfficeDocumentConverter(officeManager); converter.convert(newFile("E:\\demo.doc"),newFile("E:\\demo_1.pdf")); officeManager.stop(); } 这下就可以了,之前用2.2的版本,需要手动的开一个服务:[java]view plaincopypublicstaticvoidstartServer(){ Stringcmd="cmd/ksoffice-headless-accept=\"socket,host=127.0.0.1,port=8100;urp;\"-nofirststartwizard"; try{ Runtime.getRuntime().exec(cmd,null,newFile("D:\\programfiles\\3\\program")); }catch(IOExceptione){ e.printStackTrace(); } }
3.TXT转换为PDF
在将.txt文件转换为PDF的时候发现,如果TXT文件的编码是ANSI的话,中文会产生乱码,解决办法是先将.txt保存为.odt文件,再将.odt文件转换为PDF就可以了。
如果TXT文件的编码是UTF-8的话,中文也可以正常转换。
[java]view plaincopypackageorg.ygy.util; importjava.io.File; importorg.artofsolving.jodconverter.OfficeDocumentConverter; importorg.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; importorg.artofsolving.jodconverter.office.OfficeManager; publicclassPDFUtil{ publicstaticvoidtoPDF(StringsourcePath,Stringtargetpath){ if(sourcePath.endsWith(".txt")){ //先保存为.odt StringBufferodtPath=newStringBuffer(sourcePath.substring(0,sourcePath.lastIndexOf("."))); odtPath.append(".odt"); FileUtil.write(sourcePath,odtPath.toString()); sourcePath=odtPath.toString(); } OfficeManagerofficeManager=newDefaultOfficeManagerConfiguration() .setOfficeHome("D:\\programfiles\\3") .buildOfficeManager(); officeManager.start(); OfficeDocumentConverterconverter=newOfficeDocumentConverter(officeManager); converter.convert(newFile(sourcePath),newFile(targetpath)); officeManager.stop(); } publicstaticvoidmain(String[]args){ PDFUtil.toPDF("E:\\type.txt","E:\\type_2.pdf"); } }