Java实现Word转PDF

java实现word文档转pdf

最近在做一个Web项目,需要将Word转换成PDF然后展示出来。其中遇到许多问题,特此记录,如有不妥之处请指正。

  • 实现功能
    • docx文档转换为PDF
    • 转换之后排版不混乱
  • 使用工具(Jar包)
    • aspose-words-15.11.0.jar(用于PDF转换 )
  • 环境
    • JDK1.8
  • 代码
package com.utils;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Word文件转PDF文件
 *
 * @author yq
 * @version V1.0
 * @Time 2019-03-11
 */
public class WordToPdfUtils {

    private static Logger logger = LoggerFactory.getLogger(WordToPdfUtils.class);

    public static void main(String[] args) {
        doc2pdf("D:\\word.docx", "D:\\word.pdf");
    }

    /**
     * Word 转 PDF
     *
     * @param inPath  word文件地址
     * @param outPath pdf文件地址
     */
    public static void doc2pdf(String inPath, String outPath) {
        File wordFile = new File(inPath);
        if (!wordFile.exists()) {
            logger.info("源文件不存在:{}", inPath);
            return;
        }

        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return;
        }
        try {
            logger.info("PDF转换开始");
            //开始时间
            long old = System.currentTimeMillis();
            //获取文件
            File file = new File(outPath);
            //获取文件流
            FileOutputStream os = new FileOutputStream(file);
            // Address是将要被转化的word文档
            Document doc = new Document(inPath);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF
            doc.save(os, SaveFormat.PDF);
            //结束时间
            long now = System.currentTimeMillis();
            logger.info("PDF转换结束 共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 去除水印
     *
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            InputStream is = WordToPdfUtils.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

  • 0
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JAVA界小学僧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值