项目要用到doc转pdf的功能,一番google之后总结出了三种方法(免费方案),于是一一试了一下,做个总结记录,下次要用直接查,省的忘了……

  1. 方法1.poi读取doc + itext生成pdf (实现最方便,效果最差,跨平台)
  2. 方法2.jodconverter + openOffice (一般格式实现效果还行,复杂格式容易有错位,跨平台)
  3. 方法3.jacob + msOfficeWord + SaveAsPDFandXPS (完美保持原doc格式,效率最慢,只能在windows环境下进行)

方法1:使用jdoctopdf来实现,这是一个封装好的包,可以把doc转换成pdf,html,xml等格式,调用很方便
地址:http://www.maxstocker.com/jdoctopdf/downloads.php(项目不维护了,官网也没了)
需要自己导入poi包与itext包,需要注意的是itext要导入itext-2.1.5版本,新版本由于包名不同,会出错
也可以自己根据网上的其他教程根据需要自己写方法来实现。
用jdoctopdf的实现方法如下:

  1. public void doc2pdf(String docFileName) throws Exception{
  2. String path = this.getSession().getServletContext().getRealPath("/")+"attachment/";
  3. Parser p = new DocParser();// create a new parser instance
  4. FileInputStream fis = new FileInputStream(path+"/doc/"+ docFileName + ".doc");// creating InputStream for use with parser
  5. DocumentElement mydoc = p.parse(fis,true,false);// parse document from input stream
  6. DocWriter w = new PDFWriter();// create PDF writer
  7. w.writeDocument(mydoc,new FileOutputStream(path+"/pdf/"+docFileName + ".pdf"));// write document as pdf using writer
  8. w = new XHTMLWriter();
  9. w.writeDocument(mydoc,new FileOutputStream(path+"/pdf/"+docFileName + ".html"));// write document as xhtml
  10. }
  11. public String materialUpload(){
  12. try {
  13. doc2pdf("ttt");
  14. } catch (Exception e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. return SUCCESS;
  19. }

方法1转化后pdf截图:(itext转中文需要额外配置,所以。。。一片空白,格式也错位了)
111.png
<br/><br/>
方法2:使用jodconverter来调用openOffice的服务来转换,openOffice有个各个平台的版本,所以这种方法跟方法1一样都是跨平台的。
jodconverter的下载地址:http://www.artofsolving.com/opensource/jodconverter
首先要安装openOffice,下载地址:http://www.openoffice.org/download/index.html
安装完后要启动openOffice的服务,具体启动方法请自行google,

mac下的启动方法为终端输入

  1. /Applications/OpenOffice.org.app/Contents/MacOS/soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless

准备工作完成后在项目里导入下载下来的包,然后加个方法就OK:

  1. public void createPdf(String docFileName) throws IOException{
  2. String path = this.getSession().getServletContext().getRealPath("/")+"attachment/";
  3. File inputFile = new File(path+"/doc/"+ docFileName + ".doc");
  4. File outputFile = new File(path+"/pdf/"+docFileName + ".pdf");
  5. // connect to an OpenOffice.org instance running on port 8100
  6. OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
  7. connection.connect();
  8. // convert
  9. DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
  10. converter.convert(inputFile, outputFile);
  11. // close the connection
  12. connection.disconnect();
  13. }

方法2的截图(格式基本一致,有错位)
22.png

方法3:效果最好的一种方法,但是需要window环境,而且速度是最慢的需要安装msofficeWord以及SaveAsPDFandXPS.exe(word的一个插件,用来把word转化为pdf)
Office版本是2007,因为SaveAsPDFandXPS是微软为office2007及以上版本开发的插件
SaveAsPDFandXPS下载地址:http://www.microsoft.com/zh-cn/download/details.aspx?id=7
jacob 包下载地址:http://sourceforge.net/projects/jacob-project/
我下的是jacob-1.17-M2.zip
下载下来的jacob里的jar包导入到项目里,
jacob的dll文件放到到你的jdk/jre/bin下面(不放会报错:java.lang.NoClassDefFoundError: Could not initialize class com.jacob.com.Dispatch)

网上还有一种是把dll放在放在以下代码输出的路径里的任意一个路径目录

  1. System.getProperty("java.library.path");

这个我没试过,应该也是可以的
然后添加方法:

  1. static final int wdFormatPDF = 17;// PDF 格式
  2. public void wordToPDF(String docFileName){
  3. System.out.println("启动Word...");
  4. long start = System.currentTimeMillis();
  5. ActiveXComponent app = null;
  6. Dispatch doc = null;
  7. try {
  8. app = new ActiveXComponent("Word.Application");
  9. app.setProperty("Visible", new Variant(false));
  10. Dispatch docs = app.getProperty("Documents").toDispatch();
  11. String path = this.getSession().getServletContext().getRealPath("/")+"attachment/";
  12. String sfileName = path+"/doc/"+ docFileName + ".doc";
  13. String toFileName = path+"/pdf/"+ docFileName + ".pdf";
  14. doc = Dispatch.call(docs, "Open" , sfileName).toDispatch();
  15. System.out.println("打开文档..." + sfileName);
  16. System.out.println("转换文档到PDF..." + toFileName);
  17. File tofile = new File(toFileName);
  18. if (tofile.exists()) {
  19. tofile.delete();
  20. }
  21. Dispatch.call(doc,
  22. "SaveAs",
  23. toFileName, // FileName
  24. wdFormatPDF);
  25. long end = System.currentTimeMillis();
  26. System.out.println("转换完成..用时:" + (end - start) + "ms.");
  27. } catch (Exception e) {
  28. System.out.println("========Error:文档转换失败:" + e.getMessage());
  29. } finally {
  30. Dispatch.call(doc,"Close",false);
  31. System.out.println("关闭文档");
  32. if (app != null)
  33. app.invoke("Quit", new Variant[] {});
  34. }
  35. //如果没有这句话,winword.exe进程将不会关闭
  36. ComThread.Release();
  37. }

需要注意的是,如果没有安装SaveAsPDFandXPS.exe的话会提示

  1. ========Error:文档转换失败:Invoke of: SaveAs
  2. Source: Microsoft Word
  3. Description:

方法3pdf最终转换效果(格式完全一致):
33.PNG