首先下载aspose-words-15.8.0-jdk16.jar包
http://pan.baidu.com/s/1nvbJwnv
引入jar包,编写Java代码
1 package doc; 2 3 import java.io.*; 4 import com.aspose.words.*; //引入aspose-words-15.8.0-jdk16.jar包 5 6 public class Doc2Pdf { 7 public static boolean getLicense() { 8 boolean result = false; 9 try { 10 InputStream is = Test.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下 11 License aposeLic = new License(); 12 aposeLic.setLicense(is); 13 result = true; 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } 17 return result; 18 } 19 20 public static void doc2pdf(String Address) { 21 22 if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生 23 return; 24 } 25 try { 26 long old = System.currentTimeMillis(); 27 File file = new File("C:/Program Files (x86)/Apache Software Foundation/Tomcat 7.0/webapps/generic/web/file/pdf1.pdf"); //新建一个空白pdf文档 28 FileOutputStream os = new FileOutputStream(file); 29 Document doc = new Document(Address); //Address是将要被转化的word文档 30 doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换 31 long now = System.currentTimeMillis(); 32 System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时 33 } catch (Exception e) { 34 e.printStackTrace(); 35 } 36 } 37 }
调用以上方法
1 package doc; 2 public class Test { 3 public static void main(String[] args){ 4 Doc2Pdf.doc2pdf("C:/Program Files (x86)/Apache Software Foundation/Tomcat 7.0/webapps/generic/web/file/4.docx"); 5 } 6 }
结果生成pdf文件
OK!