java word转pdf

1.下载 jacob 解压

2.存放路径:

 jacob.jar 放在 C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext目录下
 jacob.dll 放在 C:\Program Files\Java\jdk1.8.0_171\jre\bin 目录下

public class Word2PdfJacobUtil {
 
	/* 转PDF格式值 */
	private static final int wdFormatPDF = 17;
	/**
	 * Word文档转换
	 * 
	 * @param inputFile
	 * @param pdfFile
	 */
	public static boolean word2PDF(String inputFile, String pdfFile) {
		ComThread.InitMTA(true);
	    long start = System.currentTimeMillis();
	    ActiveXComponent app = null;
	    Dispatch doc = null;
	    try {
	        app = new ActiveXComponent("Word.Application");// 创建一个word对象
	        app.setProperty("Visible", new Variant(false)); // 不可见打开word
	        app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
	        Dispatch docs = app.getProperty("Documents").toDispatch();// 获取文挡属性
 
	        System.out.println("打开文档 >>> " + inputFile);
	        // Object[]第三个参数是表示“是否只读方式打开”
	        // 调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
	        doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();
	        System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
            // 调用Document对象的SaveAs方法,将文档保存为pdf格式
            // word保存为pdf格式宏,值为17
            Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);// word保存为pdf格式宏,值为17
 
	        long end = System.currentTimeMillis();
 
	        System.out.println("用时:" + (end - start) + "ms.");
	        return true;
	    } catch (Exception e) {
	        e.printStackTrace();
	        System.out.println("========Error:文档转换失败:" + e.getMessage());
	    } finally {
	        Dispatch.call(doc, "Close", false);
	        System.out.println("关闭文档");
	        if (app != null)
	            app.invoke("Quit", new Variant[] {});
            // 如果没有这句话,winword.exe进程将不会关闭
            ComThread.Release();
            ComThread.quitMainSTA();
        }
	    return false;
	}
	}

public static void main(String[] arg){
		String docPath = "D:\opt\upFiles\detectionResult\text.docx";
		String pdfPath = "D:\opt\upFiles\detectionResult\text.pdf";
        boolean res = Word2PdfJacobUtil.word2PDF(docPath, pdfPath);
        System.out.println(res);
}

结果如下:

偶尔能碰到异常,但是不常见,也不知道怎么发生的,重启了项目就没出现了 

服务器部署可能出现错误:操作失败,Can't pass in null Dispatch object

友情提示,服务器一定要装WPS或者office。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值