好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java利用jacob将word转pdf

本文实例为大家分享了 java 开发利用 jacob 将 word转pdf 的具体代码,供大家参考,具体内容如下

jacob 缺点:需要 window 环境,而且速度是最慢的需要安装 msofficeword 以及 saveaspdfandxps.exe ( word 的一个插件,用来把 word 转化为 pdf )

开发流程:

SaveAsPDFandXPS  下载地址

jacob 包 下载地址 :

1、先安装saveaspdfandxps

2、下载 jacob 解压后存放路径:

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 目录下

实现代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

package com.casf.hn.core.util;

 

import java.io.file;

 

import com.jacob.activex.activexcomponent;

import com.jacob.com.comthread;

import com.jacob.com.dispatch;

import com.jacob.com.variant;

 

/**

  * 效果最好的一种方法,但是需要 window 环境,而且速度是最慢的需要安装 msofficeword 以及 saveaspdfandxps.exe (

  * word 的一个插件,用来把 word 转化为 pdf,可以不用安装,本次未安装测试通过 )

  *

  *

  *

  */

public class wordtopdf {

 

  private static final int wdformatpdf = 17 ; // pdf 格式

 

  public void wordtopdf(string sfilename, string tofilename) {

 

   system.out.println( "启动 word..." );

   long start = system.currenttimemillis();

   activexcomponent app = null ;

   dispatch doc = null ;

   try {

    app = new activexcomponent( "word.application" );

    app.setproperty( "visible" , new variant( false ));

    dispatch docs = app.getproperty( "documents" ).todispatch();

    doc = dispatch.call(docs, "open" , sfilename).todispatch();

    system.out.println( "打开文档..." + sfilename);

    system.out.println( "转换文档到 pdf..." + tofilename);

    file tofile = new file(tofilename);

    if (tofile.exists()) {

     tofile.delete();

    }

    dispatch.call(doc, "saveas" , tofilename, // filename

      wdformatpdf);

    long end = system.currenttimemillis();

    system.out.println( "转换完成..用时:" + (end - start) + "ms." );

 

   } catch (exception e) {

    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();

  }

 

  public static void main(string[] args) {

   wordtopdf d = new wordtopdf();

   d.wordtopdf( "d:\\cssj\\xxxx.doc" , "d:\\cssj\\xxxx.pdf" );

  }

 

}

运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq493820798/article/details/80420140

查看更多关于java利用jacob将word转pdf的详细内容...

  阅读:13次