java word转pdf

1、word文档转pdf

参考文章:https://www.cnblogs.com/luxiaoxun/p/16506045.html

1)maven依赖

<dependency>
	<groupId>fr.opensagres.xdocreport</groupId>
	<artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
	<version>2.0.1</version>
</dependency>

 2)测试代码
 

package com.obs.obsintf.yyxt.utils;

import com.google.code.appengine.awt.Color;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;
@Slf4j
public class WordToPDF {

    public static void main(String[] args) {
        WordToPDF.toPDF();
    }

    public static void toPDF(){

        InputStream ins = null;
        XWPFDocument xdoc = null;
        OutputStream outs = null;

        try  {
            ins = new FileInputStream("D:\\pdf测试_20220906170705.docx");//
            xdoc = new XWPFDocument(ins);

            PdfOptions options =  PdfOptions.create();
            //支持中文 无此代码 不显示中文
            options.fontProvider(new IFontProvider() {
                @Override
                public Font getFont(String familyName, String encoding, float size, int style, Color color) {
                    try {
                        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                        Font fontChinese = new Font(bfChinese, size, style, color);
                        if (familyName != null) {
                            fontChinese.setFamily(familyName);
                        }
                        return fontChinese;
                    } catch (Exception e) {
                        return null;
                    }
                }
            });

            outs = new FileOutputStream("D:\\pdf文件.pdf");//

            PdfConverter.getInstance().convert(xdoc, outs, options);

        } catch (Exception e) {

            e.printStackTrace();

        }finally {
            if(outs!=null){
                try {outs.close();} catch (IOException e) {e.printStackTrace();}
            }
            if(xdoc!=null){
                try {xdoc.close();} catch (IOException e) {e.printStackTrace();}
            }
            if(ins!=null){
                try {ins.close();} catch (IOException e) {e.printStackTrace();}
            }
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值