好得很程序员自学网

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

java使用jacob实现word转pdf

背景:日常开发erp系统,会有一些工单或者合同之类需要填写打印。我们就会将其word模板来通过系统自动化填写并转换为pdf格式(pdf文件打印可保证文件质量,是一种通用的格式。文件不易去修改,比较稳定)。所以我们将通过jacob来实现这些功能。

准备工作:

1.服务器需要安装office2007,因为我们就是调用这个来实现转换。
2.需要安装插件jacob,安装jacob-1.14.3-x86.dll到jdk\jdk1.7.0\jre\bin(你自己电脑安装的jdk)
3.需要使用jacob-1.14.3.jar包
    maven代码如下: 
 

?

1

2

3

4

5

<dependency>

   <groupid>net.sf.jacob-project</groupid>

   <artifactid>jacob</artifactid>

   <version> 1.14 . 3 </version>

</dependency>

4.假如通过以上准备工作未成功转换,就下载一个saveaspdfandxps.exe组件(office2007里的)。我就是通过这个组件才完成转换。

5.上面的在系统为windows7中就可以了,假如你的项目需要发布到服务器(服务器系统一般都是windows2008)。则还需要一步。在上面的基础上再安装安装jacob-1.14.3-x64.dll到jdk\jdk1.7.0\jre\bin(你自己电脑安装的jdk)中。很多人在win7下都能成功转换,但在win2008就是出问题。我就是通过磨了一天的时间,看了各种日志才发现问题。

一、工具类(operationio.java), 这里面可以不做任何修改,复制粘贴就可以了。

 

?

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

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

package com.repair.util.pub;

 

import java.awt.image.bufferedimage;

import java.io.bytearrayinputstream;

import java.io.file;

import java.io.fileinputstream;

import java.io.ioexception;

import java.io.inputstream;

 

import javax.imageio.imageio;

 

import sun.misc.base64decoder;

import sun.misc.base64encoder;

 

import com.jacob.activex.activexcomponent;

import com.jacob测试数据测试数据thread;

import com.jacob测试数据.dispatch;

import com.jacob测试数据.variant;

 

public class operationio {

 

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

  /**

  * word转换pdf

  * @param sfilename word文件存在位置

  * @param tofilename pdf文件存放位置

  */

  public static void wordtopdf(string sfilename,string tofilename){ 

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

     long start = system.currenttimemillis(); 

     activexcomponent app = null ;

     dispatch doc = null ;

     try {  

      //调用office word

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

   }

 

  /**

    * 递归删除目录下的所有文件及子目录下所有文件

    * @param dir 将要删除的文件目录

    * @return boolean returns "true" if all deletions were successful.

    *         if a deletion fails, the method stops attempting to

    *         delete and returns "false".

    */

   public static boolean deletedir(file dir) {

     if (dir.isdirectory()) {

       string[] children = dir.list();

       for ( int i= 0 ; i<children.length; i++) {

         boolean success = deletedir( new file(dir, children[i]));

         if (!success) {

           return false ;

         }

       }

     }

     // 目录此时为空,可以删除

     return dir.delete();

   }

  /**

    * 将图片文件转化为字节数组字符串,并对其进行base64编码处理

    * @param imgfilepath 图片地址路径

    */

   public static string getimagestr(string imgfilepath) { //

     byte [] data = null ;

     

     // 读取图片字节数组

     try {

      inputstream in = new fileinputstream(imgfilepath);

      data = new byte [in.available()];

      in.read(data);

      in.close();

     } catch (ioexception e) {

      e.printstacktrace();

     }

     

     // 对字节数组base64编码

     base64encoder encoder = new base64encoder();

     return encoder.encode(data); // 返回base64编码过的字节数组字符串

    }

  

  

   /**

    * 将二进制转换为图片

    *

    * @param base64string

    */

   public static void base64stringtoimage(string base64string,string imageoutpath) {

     try {

      base64decoder decoder = new sun.misc.base64decoder();

       byte [] bytes1 = decoder.decodebuffer(base64string);

       bytearrayinputstream bais = new bytearrayinputstream(bytes1);

       bufferedimage bi1 = imageio.read(bais);

       file w2 = new file(imageoutpath); // 可以是jpg,png,gif格式

       imageio.write(bi1, "jpg" , w2); // 不管输出什么格式图片,此处不需改动

     } catch (ioexception e) {

       e.printstacktrace();

     }

   }

}

二、业务类(printwordtopdf.java) ,这里

 

?

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

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

package com.hjm.test;

 

import java.io.bufferedwriter;

import java.io.file;

import java.io.filenotfoundexception;

import java.io.fileoutputstream;

import java.io.ioexception;

import java.io.outputstreamwriter;

import java.io.unsupportedencodingexception;

import java.io.writer;

import java.util.hashmap;

import java.util.map;

 

import com.engineering.pojos.pub.gcrecordarchive;

import com.repair.util.pub.operationio;

 

import freemarker.template.configuration;

import freemarker.template.template;

import freemarker.template.templateexception;

 

public class printwordtopdf {

 

  public static void main(string[] args) {

  //创建一个configuration的实例

  configuration configuration = new configuration();

  //设置编码

  configuration.setdefaultencoding( "utf-8" );

  //创建map对象,来保存要填写的数据

  map<string, object> paramap = new hashmap<string, object>();

  //下面这些是我测试的一些数据

  paramap.put( "receivingparty" , "中国民航" );

 

  paramap.put( "packinglistno" , 10087 );

 

  paramap.put( "conno" , 10088 );

 

  try {

   //调用模板的文件夹,new file("d:\\测试")是一个绝对路径,你可以自己设置为服务器路径。

   configuration.setdirectoryfortemplateloading( new file( "d:\\测试" ));

  } catch (ioexception e) {

   e.printstacktrace();

  }

  template t = null ;

  try {

   //获取模板文件

   t = configuration.gettemplate( "fmo-08 packing list.ftl" ); // 获取模板文件

  } catch (ioexception e) {

   e.printstacktrace();

  }

  //生成一个文件保存的文件夹

  file file = new file( "d:\\最终" );

  //判断文件夹是否存在,存在删除并重创

  if (!file .exists() && !file .isdirectory())  

  {   

    file.mkdir(); 

  } else

  {

   boolean b = operationio.deletedir(file);

   if (b){

   file.mkdir();

   }

  }

  //填写数据后生成的word文件。

  string outfilepath = "d:/最终\\结果" + ".doc" ;

  file outfile = new file(outfilepath); // 导出文件

  writer out = null ;

  try {

   try {

   out = new bufferedwriter( new outputstreamwriter(

    new fileoutputstream(outfile), "utf-8" ));

   } catch (unsupportedencodingexception e) {

   // todo auto-generated catch block

   e.printstacktrace();

   }

  } catch (filenotfoundexception e1) {

   e1.printstacktrace();

  }

  try {

   t.process(paramap,out); // 将填充数据填入模板文件并输出到目标文件

   out.flush();

   out.close();

   //转换pdf的文件

   operationio.wordtopdf(outfilepath, "d:/最终\\结果" + ".pdf" );

  } catch (templateexception e) {

   e.printstacktrace();

  } catch (ioexception e) {

   e.printstacktrace();

  }

  }

}

总结:通过以上代码,就可以在模板中填写好数据,并将其生成word文件与其pdf文件。

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

原文链接:https://blog.csdn.net/qq_31170429/article/details/78424973

查看更多关于java使用jacob实现word转pdf的详细内容...

  阅读:28次