java实现word转pdf

来源:互联网 发布:淘宝商品详情页图片 编辑:程序博客网 时间:2024/06/05 17:58

网上有很多word转pdf的工具和代码,比如:poi, itext, jacob, openoffice, xdocreport等等 我记得还有日本一个开源工具word转pdf。


今天说说我自己项目中使用的是xdocreport真正的核心代码比较简单。先上核心代码吧。

package com.icitic.jd.common.convert;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class DocxToPdf {

public static void convertPdf(String docxFilePath,String pdfFilePath) throws Exception{
File docxFile=new File(docxFilePath);
File pdfFile=new File(pdfFilePath);

//转换pdf文件
if(docxFile.exists()){
if(!pdfFile.exists()){
    InputStream inStream=new  FileInputStream(docxFilePath);
       XWPFDocument document = new XWPFDocument(inStream);
    //HWPFDocument document = new HWPFDocument(inStream);
    OutputStream out = new FileOutputStream(pdfFilePath); 
           PdfOptions options = PdfOptions.create();           
           ExtITextFontRegistry fontProvider=ExtITextFontRegistry.getRegistry();
           options.fontProvider(fontProvider);
           PdfConverter.getInstance().convert(document, out, options);
}else{
System.out.println("PDF文件已存在,无需再次转换");
}
}else{
}
}

}


因为使用了XWPFDocument 这个 只能支持docx转pdf 不支持doc转 我改成HWPFDocument好像也不行哦

maven中引用jar  其实只有后面两个jar包 不过有一些依赖的jar哦 记得下载 第一个模板引擎引用的jar的使用freemarker技术生产动态word才使用的。

<!-- 模版引擎用到的jar包 -->  
<dependency>  
     <groupId>org.freemarker</groupId>  
     <artifactId>freemarker</artifactId>  
     <version>2.3.25-incubating</version>  
 </dependency>


<dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
            <type>jar</type>
        </dependency>


        <dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.4</version>
</dependency>

0 0
原创粉丝点击