1,application.yml

company:
  office:
    convertWindowsCmd: ${project.office.convertWindowsCmd}
    convertLinuxCmd: ${project.office.convertLinuxCmd}

2,application-dev/other.yml,或直接写在application.yml

project:
  office:
   convertWindowsCmd: soffice --headless --convert-to pdf $/{inputPath} --outdir $/{outDir}
   convertLinuxCmd: libreoffice --convert-to pdf:writer_pdf_Export $/{inputPath} --outdir $/{outDir}

3,获取自定义配置

@Component("libreOfficeUtils")
public class LibreOfficeUtils {

    @Value("${company.office.convertWindowsCmd}")
    private String convertWindowsCmd;

    @Value("${company.office.convertLinuxCmd}")
    private String convertLinuxCmd;

    private static final Logger log = LoggerFactory.getLogger(LibreOfficeUtils.class);

    /**
     * 文档转换
     * @param newAttachmentId 附件id
     * @throws Exception
     */
    public static void fileConverter(Long newAttachmentId) {
        LibreOfficeUtils libreOfficeUtils = SpringUtil.getBean("libreOfficeUtils");
        libreOfficeUtils.fileConverter2(newAttachmentId);
    }
    /**
     * 文档转换
     * @param newAttachmentId 附件id
     * @throws Exception
     */
    public void fileConverter2(Long newAttachmentId) {
        // 输出pdf的文件夹
        String outDir = null;
        // 转换进程
        Process process = null;
        // word 源路径
        String filePath = "...";
        // 系统命令行选择
        String cmdString = null;
        // liberoffic命令行模板
        String liberofficeCmd = null;
        // 最终执行命令行
        String cmd = null;

        // 系统判断
        String linuxRegex = "Linux.*";
        String windowRegex = "Windows.*";
        String osName = System.getProperty("os.name");
        if (Pattern.matches(linuxRegex, osName)) {
            cmdString = convertLinuxCmd;
        } else if (Pattern.matches(windowRegex, osName)) {
            cmdString = convertWindowsCmd;
        }

        if (StringUtil.isNotBlank(filePath)) {
            if (filePath.contains("\\")) {
                outDir = filePath.substring(0, filePath.lastIndexOf("\\"));
            } else {
                outDir = filePath.substring(0, filePath.lastIndexOf("/"));
            }
        }

        liberofficeCmd = cmdString.replace("/","");
        Map map = new HashMap();
        map.put("inputPath", filePath);
        map.put("outDir", outDir);    
        // 字符串替换
        cmd = TemplateUtil.toStrForStrTemplate(liberofficeCmd, map);

        try {
            log.info("word2pdf:正在执行liberoffice命令行...");
            process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
            log.info("word2pdf:转换成功");
            // do other thing
        } catch (IOException|InterruptedException e) {
            log.warn("liberoffice转换异常,错误码:" + e);
            e.printStackTrace();
        } finally {
            if(process.isAlive()) {
                process.destroy();
            }
        }
    }
}

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐