java调用Aspose使用线程异步实现word文档转pdf

1.Word转pdf方法

使用aspose-words.jar,实现word转pdf完美无水印

/**
 * (doc与docx格式)转pdf
 * @param officePath 将要被转化的word文档 文件路径
 * @param pdfPath 生成pdf文件路径
 */
public static void wordToPdf(String officePath,String pdfPath) {
     
    if (!getLicense()) {
      // 验证License 若不验证则转化出的pdf文档会有水印产生
        return;
    }
    try {
     
    	String fileName = officePath.substring(officePath.lastIndexOf(File.separator)+1);
    	System.out.println("开始转换:"+fileName);
        long old = System.currentTimeMillis();
        File file = new File(pdfPath);  //新建一个空白pdf文档
    	if (!file.getParentFile().exists()) {
     
    		file.getParentFile().mkdirs();
    	}
        FileOutputStream os = new FileOutputStream(file);
        Document doc = new Document(officePath); 
        doc.save(os, SaveFormat.PDF);
        os.flush();
        os.close();
        long now = System.currentTimeMillis();
        System.out.println("转换成功:共耗时" + ((now - old) / 1000.0) + "秒");  //转化用时
    } catch (Exception e) {
     
        e.printStackTrace();
        System.out.println("转换失败!");  
    }
}

2.License.xml验证方法

必须加上此方法验证,不然生成pdf会有水印

public static boolean getLicense() {
     
    boolean result = false;
    try {
     
    	//license.xml存放目录(此路径用于OfficeToPdfUtil类与license.xml在同级路径)
    	String path = new OfficeToPdfUtil().getClass().getResource("").getPath();
        String licensePath = path + File.separator+"license.xml";
        InputStream is = new FileInputStream(new File(licensePath));
        License aposeLic = new License();
        aposeLic.setLicense(is);
        result = true;
        is.close();
    } catch (Exception e) {
     
        e.printStackTrace();
    }
    return result;
}

3.使用OfficeToPdfThread线程类

用于异步转换,不影响后续操作

package com.demo;

public class OfficeToPdfThread implements Runnable{
     
	private String officePath; 
	private String pdfPath;
	public OfficeToPdfThread() {
     
	}
	public OfficeToPdfThread(String officePath,String pdfPath) {
     
		this.officePath = officePath;
		this.pdfPath = pdfPath;
	}
	
	@Override
	public void run() {
     
		OfficeToPdfUtil.wordToPdf(officePath, pdfPath);
	}

}

4.测试

public static void main(String[] args) {
     
		String officePath = "D:\\test\\test.doc";
		String pdfPath = "D:\\test\\test.pdf";
		Thread t = new Thread(new OfficeToPdfThread(officePath, pdfPath));
		t.start();
	}

5.项目链接:

完整项目

你可能感兴趣的:(office,pdf,java)