/** * 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice * * @param sourceFile 源文件,绝对路径. 可以是Office2003-2007全部格式的文档, Office2010的没测试. 包括.doc, .docx, .xls, * .xlsx, .ppt, .pptx等. * @param destFile 目标文件.绝对路径. */ public static void word2pdf(String inputFilePath) { DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration(); String officeHome = getOfficeHome(); config.setOfficeHome(officeHome); OfficeManager officeManager = config.buildOfficeManager(); officeManager.start(); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); String outputFilePath = getOutputFilePath(inputFilePath); File inputFile = new File(inputFilePath); if (inputFile.exists()) { // 找不到源文件, 则返回 File outputFile = new File(outputFilePath); if (!outputFile.getParentFile().exists()) { // 假如目标路径不存在, 则新建该路径 outputFile.getParentFile().mkdirs(); } converter.convert(inputFile, outputFile); } officeManager.stop(); }
@Override public void afterPropertiesSet() throws Exception { System.out.println("******************"); // 启动libreoffice进程 Windows平台需要启动,linux不需要启动 if (PlatformUtils.isWindows()) { String command = "cmd /c soffice --headless --accept=\"socket,host=127.0.0.1,port=8100;urp\" --nofirststartwizard"; Runtime runtime = Runtime.getRuntime(); runtime.exec(command); } officeManager = configuration.buildOfficeManager(); converter = new OfficeDocumentConverter(officeManager); customDocumentFormatRegistry = (SimpleDocumentFormatRegistry) converter.getFormatRegistry(); /* * // TODO:这里可以增加OpenOffice支持的文件类型 异常json * customDocumentFormatRegistry.addFormat(new * DocumentFormat("OpenOffice.org 1.0 Template", "sxd", * "application/vnd.sun.xml.draw")); * customDocumentFormatRegistry.addFormat(new * DocumentFormat("OpenOffice.org 1.0 Template", "odf", * "application/vnd.oasis.opendocument.formula")); */ DocumentFormat txt = new DocumentFormat("Java", "java", "text/plain"); txt.setInputFamily(DocumentFamily.TEXT); Map<String, Object> txtLoadAndStoreProperties = new LinkedHashMap<String, Object>(); txtLoadAndStoreProperties.put("FilterName", "Text (encoded)"); txtLoadAndStoreProperties.put("FilterOptions", "utf8"); txt.setLoadProperties(txtLoadAndStoreProperties); txt.setStoreProperties(DocumentFamily.TEXT, txtLoadAndStoreProperties); customDocumentFormatRegistry.addFormat(txt); // 添加wps格式 customDocumentFormatRegistry.addFormat( new DocumentFormat("wps文字", "wps", "application/msword")); // wps文字 customDocumentFormatRegistry.addFormat( new DocumentFormat("wps表格", "et", "application/msword")); // wps表格 customDocumentFormatRegistry.addFormat( new DocumentFormat("wps演示", "dps", "application/msword")); // wps演示 // 启动officeManager,保持在Bean的生命周期中一直在启动状态 officeManager.start(); }