有时候项目所需,要将Word文档转换为PDF文档,网上的资料很多,这里整理一下。
- 利用apache poi
平常项目中遇到需要将word转换为pdf,我们一般利用的是组件,这个组件利用的是微软office组件,但有时项目需要部署到liunx下,liunx中没有office,我们可以利用apache poi实现这一功能。
/huanshirenjian/article/details/46379153
/semengzhu/article/details/74989816
- 使用jacob(Java COM Bridge)操作office的方式
SaveAsPDFandXPS+jacob(Windows操作系统下,电脑里有office)--几乎不管水印还是格式都完美的转换,但是只能支持windows
/****FlyFun/article/details/79523262
/m0_37568521/article/details/78545887
/hsj1213522415/article/details/70917508
使用xdocreport进行转(优点效率高,缺点对word格式要求较大,适合对生成pdf要求不高的情况)
使用libreoffice来进行转(效果好,格式便于控制,基本上转出来的pdf和用libreoffice查看看到的word样子已经非常接近了)
/qwert678000/article/details/72770109
- JobConverter + OpenOffice(Windows系统下)--windows、linux 都可以配置
/warrior4236/p/
/weixin_41623274/article/details/79044422
/songqiang2011/article/details/51819468
我在项目中使用的是OpenOffice,代码如下:
import ; import ; import ; import ; import ; import org.; import org.; //Word文档转换为PDF文档 public class ConvertToPdf { private static Logger logger = (); private static OfficeManager officeManager; //private static String OPEN_OFFICE_HOME = ("open_office_home"); private static int OPEN_OFFICE_PORT[] = { (("open_officce_port")) }; /** * 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice * 源文件,绝对路径. 可以是Office2003-2007全部格式的文档, Office2010的没测试. 包括.doc, * .docx, .xls, .xlsx, .ppt, .pptx等. * 目标文件.绝对路径. * @param inputFilePath */ public static File word2pdf(String inputFilePath) { //把输入的word路径,后缀替换为pdf. String pdfPath = (0, (".") + 1)+".pdf"; //启动openoffice服务 startService(); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); File inputFile = new File(inputFilePath); File outputFile = new File(pdfPath); if (()) {// 找不到源文件, 则返回 //假如目标路径不存在,则新建该路径 if (!().exists()) { ().mkdirs(); } (inputFile, outputFile); } //关闭openoffice服务 stopService(); return outputFile; } /** * 根据操作系统获取openoffice安装地址 * @return office_home */ public static String getOfficeHome() { String osName = (""); if (("Linux.*", osName)) { return ("open_office_home"); } else if (("Windows.*", osName)) { return ("win_open_office_home"); } return null; } /** * 启动openoffice服务 */ public static void startService() { DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration(); try { ("准备启动服务...."); (getOfficeHome());//设置安装目录 (OPEN_OFFICE_PORT); //设置转换端口,默认为8100 (1000 * 60 * 5L);//设置任务执行超时为5分钟 (1000 * 60 * 60 * 24L);//设置任务队列超时为24小时 officeManager = (); ();// 启动服务 ("office转换服务启动成功!"); } catch (Exception ce) { ("office转换服务启动失败!详细信息:" + ce); } } /** * 关闭openoffice服务 */ public static void stopService() { ("关闭office转换服务...."); if (officeManager != null) { (); } ("关闭office转换成功!"); } }
- 使用docx4j
网上看到的都是利用OpenOffice来转化word为pdf的,其实局限性很大,下载那么大一个软件,却只是为了它的服务。docx4j这个jar包也可以实现转换
/u011763190/article/details/51017682