java实现word转pdf

前提:word是office 2010版的(提取码:ba1b)

1、引入jacob.jar

2、分别在对应位置引入jacob-1.17-x64.dll文件

(1)Tomcat的bin下

(2)jdk的bin下

(3)jre的bin下

(4)C:\Windows\System32 的下面

3、编写代码

package com.test;

import java.io.File;


import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class Test {
	public static void main(String[] args) {
		String realPath="D:/file/"; //文件路径
		String fileName="测试文档.docx"; //word文件名称
		 
		wordToPDF(realPath+fileName,realPath+fileName.substring(0,fileName.lastIndexOf("."))+".pdf");
	   
		if(new File(realPath+fileName.substring(0,fileName.lastIndexOf("."))+".pdf").exists()){
		  System.out.println("转换成功,请前往"+realPath+"查看"); 
	    }else{
		   System.out.println("转换失败"); 
	    }
	}
	//转换:参数【原word文件地址,转换后的pdf文件地址】
	public static void wordToPDF(String wordpath,String pdfpath){   
		 //ActiveXComponent 一个已经编译好的基于COM的软件组件,通过DCOM实现了对调用程序的透明化
		ActiveXComponent app = null; 
		Dispatch doc = null; //Dispatch:调度处理类,封装了一些方法来操作office,里面所有的可操作对象基本都是这种类型
		try {      
			app = new ActiveXComponent("Word.Application");  //调用word应用程序     
			app.setProperty("Visible", new Variant(false));  //设置组件是否可见(不可见:打开的过程都是隐藏的)
			Dispatch docs = app.getProperty("Documents").toDispatch();  //获取所有文档并将文档转换成 Dispatch类型 
			doc = Dispatch.call(docs, "Open" ,wordpath).toDispatch(); //call()方法:调用COM对象的方法;Open:打开word文档
			File tofile = new File(pdfpath);      
			if (tofile.exists()) {      
				tofile.delete();    //存在便删除  
			}      
			Dispatch.call(doc,"SaveAs",pdfpath,17);   //将文档另存到pdfpath,文档类型是17【pdf格式】   
		} catch (Exception e) {      
			System.out.println(e.getMessage());      
		} finally {  
			Dispatch.call(doc,"Close",false);   //关闭
			if (app != null)      
				app.invoke("Quit", new Variant[] {});      
		}  
		//结束后关闭进程   
		ComThread.Release();
	}
}
 

4、在文件路径中放入word文件

5、启动项目

6、查看效果

PS:完整版项目(提取码:9o7h)

(1)new Variant(true)组件的是否可见

(2)文档参数参考值,数据来源于网络

0

Doc

1

Dot

2-5

Txt

6

Rtf

7

Txt

8、10

htm

11

Xml

12、16

Docx

13

Docm

14

Dotx

15

Dotm

17

Pdf

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值