[Java]Word转PDF

  1. maven导包
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
    <version>1.0.6</version>
</dependency>
  1. 工具类
import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.lowagie.text.pdf.BaseFont;

import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import com.lowagie.text.Font;

import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;  
   
/**
 * word 转pdf
 * @author ChenMeng
 *
 */
public class WordToPdfUtil {  
   
    /**
     * word 转pdf
     * @param source	来源流
     * @param target	目标流
     * @param typeFaceUrl	字体路径
     * @throws Exception
     * @author ChenMeng
     */
    public static void wordConverterToPdf(InputStream source, OutputStream target,final String typeFaceUrl) throws Exception {  
        PdfOptions options = PdfOptions.create();
        options.fontProvider(new IFontProvider() {
			
			public Font getFont(String familyName, String encoding, float size, int style, Color color) {
				try {
					BaseFont bfChinese = BaseFont.createFont(typeFaceUrl, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
					Font fontChinese = new Font(bfChinese, size, style, color);
					if (familyName != null)
                        fontChinese.setFamily(familyName);
                    return fontChinese;
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		});
        PdfConverter.getInstance().convert(new XWPFDocument(source), target,options);  
    }   
    
    /**
     * word 转pdf
     * 
     * @param filepath	来源路径
     * @param outpath	目标路径
     * @param typeFaceUrl	字体路径
     * @author ChenMeng
     */
    public static void wordToPdf(String filepath,String outpath,String typeFaceUrl) {
    	InputStream source;
		OutputStream target;
		try {
			source = new FileInputStream(filepath);  
			target = new FileOutputStream(outpath);
	        wordConverterToPdf(source, target,typeFaceUrl);  
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值