java word转pdf dox4j_java将word转成pdf--之docx4j的export pdf组件

本文介绍了如何使用docx4j库将Word文档(docx)转换为PDF。通过集成相关依赖,如poi、xmlbeans等,并创建转换工具类Word2PdfUtils,实现了从docx到pdf的转换。转换过程中还设置了字体映射以确保正确显示各种中文字体。
摘要由CSDN通过智能技术生成

1. 集成步骤

引入相关依赖 args4j

args4j

2.32

org.docx4j

docx4j

3.2.1

fr.opensagres.xdocreport

org.apache.poi.xwpf.converter.pdf

1.0.6

fr.opensagres.xdocreport

org.odftoolkit.odfdom.converter.pdf

1.0.6

com.googlecode.jaxb-namespaceprefixmapper-interfaces

JAXBNamespacePrefixMapper

2.2.4

runtime

com.sun.xml.bind

jaxb-impl

2.2.11

com.sun.xml.bind

jaxb-core

2.2.11

org.apache.xmlbeans

xmlbeans

2.6.0

org.apache.poi

poi

3.14

org.apache.poi

poi-scratchpad

3.14

org.apache.poi

poi-ooxml

3.14

转换工具类

``` public class Word2PdfUtils {

/**

* docx文档转换为PDF

*

* @param pdfPath PDF文档存储路径

* @throws Exception 可能为Docx4JException, FileNotFoundException, IOException等

*/

public void convertDocxToPdf(String docxPath, String pdfPath) throws Exception {

FileOutputStream fileOutputStream = null;

try {

File file = new File(docxPath);

fileOutputStream = new FileOutputStream(new File(pdfPath));

WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(file);

setFontMapper(mlPackage);

Docx4J.toPDF(mlPackage, new FileOutputStream(new File(pdfPath)));

}catch (Exception e){

e.printStackTrace();

// log.error("docx文档转换为PDF失败"); }finally { IOUtils.closeQuietly(fileOutputStream); } }

private static void setFontMapper(WordprocessingMLPackage mlPackage) throws Exception {

Mapper fontMapper = new IdentityPlusMapper();

fontMapper.put("隶书", PhysicalFonts.get("LiSu"));

fontMapper.put("宋体", PhysicalFonts.get("SimSun"));

fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei"));

fontMapper.put("黑体", PhysicalFonts.get("SimHei"));

fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));

fontMapper.put("新宋体", PhysicalFonts.get("NSimSun"));

fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));

fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));

fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB"));

fontMapper.put("仿宋", PhysicalFonts.get("FangSong"));

fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312"));

fontMapper.put("幼圆", PhysicalFonts.get("YouYuan"));

fontMapper.put("华文宋体", PhysicalFonts.get("STSong"));

fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong"));

mlPackage.setFontMapper(fontMapper);

}

}

3. 测试

@Test

void convertDocxToPdf() throws Exception {

String docxPath = "/Users/zsz/Project/demo/2020year/4yue/word2pdf/mytest.docx";

String pdfPath = "/Users/zsz/Project/demo/2020year/4yue/word2pdf/word2pdf.pdf";

Word2PdfUtils word2PdfUtils = new Word2PdfUtils();

word2PdfUtils.convertDocxToPdf(docxPath,pdfPath);

}

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值