word转PDF

  1. docx4j
    依赖:
 <dependency>
            <groupId>org.docx4j</groupId>
            <artifactId>docx4j-export-fo</artifactId>
            <version>6.1.0</version>
        </dependency>
   /**
     * docx4j
     * @param docxPath
     * @return
     */
    public static String docxToPdf(String docxPath) {
        OutputStream outputStream = null;
        String pdfPath = docxPath.replace(".doc", ".pdf");
        try {
            WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(new File(docxPath));
            mlPackage.setFontMapper(fontMapper);
            outputStream = new BufferedOutputStream(new FileOutputStream(pdfPath));
            FOSettings foSettings = Docx4J.createFOSettings();
            foSettings.setWmlPackage(mlPackage);
            Docx4J.toFO(foSettings, outputStream, Docx4J.FLAG_EXPORT_PREFER_XSL);
        } catch (Exception ex) {
            log.error("docx转PDF失败!", ex);
            pdfPath = null;
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
        return pdfPath;
    }
  1. commons-io
<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
/**
     * commons-io
     * @return
     * 需要安装 libreoffice应用
     * 转出来为 xml
     */
    // 执行转换的方法
    public static boolean wordConverterToPdf(String docxPath,String targetPath) throws IOException {
        File file = new File(docxPath);
        try {
            String osName = System.getProperty("os.name");
            String command = "";
            if (osName.contains("Windows")) {
                command = "soffice -display :0 --headless --convert-to pdf  -outdir " + targetPath + " " + docxPath;
            } else {
                command = "doc2pdf --output=" + targetPath + File.separator + file.getName().replaceAll(".(?i)docx", ".pdf") + " " + docxPath;
            }
            String result = CommandExecute.executeCommand(command);
            if (result.equals("") || result.contains("writer_pdf_Export")) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return false;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值