java8通过poi+text将word转为pdf
1、jar包
<dependency>
<groupid>fr.opensagres.xdocreport</groupid>
<artifactid>org.apache.poi.xwpf.converter.pdf</artifactid>
<version>1.0.6</version>
</dependency>2、代码util类
(部分文档转换后会有格式问题,暂未解决)
package com.zjjw.jxtest.util.util;
import com.lowagie.text.font;
import com.lowagie.text.pdf.basefont;
import fr.opensagres.xdocreport.itext.extension.font.ifontprovider;
import org.apache.poi.xwpf.converter.pdf.pdfconverter;
import org.apache.poi.xwpf.converter.pdf.pdfoptions;
import org.apache.poi.xwpf.usermodel.xwpfdocument;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.nio.file.files;
import java.nio.file.paths;
/**
* @author: chenjiaxiang
* @create: 2022/11/22 14:40
**/
public class wordtopdfutils {
private static final string fonts1 = "/users/chenjx/library/fonts/simsun.ttc,1";
private static final string fonts2 = "/users/chenjx/library/fonts/simfang.ttf";
private static final string fonts_name = "仿宋";
public static void main(string[] args) throws exception {
string filepath = "/users/chenjx/downloads/zipceshi/createyuword.docx";
string outpath = "/users/chenjx/downloads/zipceshi/pdf/a.pdf";
wordtopdfutils wordpdfutils = new wordtopdfutils();
wordpdfutils.wordtopdf(filepath, outpath);
}
public void wordtopdf(string wordpath, string pdfpath) {
inputstream in = null;
outputstream outpdf = null;
xwpfdocument document;
try {
in = files.newinputstream(paths.get(wordpath));
document = new xwpfdocument(in);
// 将word转成pdf
pdfoptions options = pdfoptions.create();
outpdf = files.newoutputstream(paths.get(pdfpath));
options.fontprovider(new ifontprovider() {
@override
public font getfont(string familyname, string encoding, float size, int style, java.awt.color color) {
try {
string prefixfont;
string os = system.getproperties().getproperty("os.name");
if (os.startswith("win") || os.startswith("win")) {
/*windows字体*/
prefixfont = "c:\\windows\\fonts\\simsun.ttc,0";
} else {
/*linux字体*/
prefixfont = fonts1;
}
basefont stchinese = basefont.createfont(prefixfont, basefont.identity_h, basefont.not_embedded);
basefont fschinese = basefont.createfont(fonts2, basefont.identity_h, basefont.not_embedded);
font stfontchinese = new font(stchinese, size, style, color);
font fsfontchinese = new font(fschinese, size, style, color);
if (familyname != null) {
if (fonts_name.equals(familyname)) {
fsfontchinese.setfamily(familyname);
return fsfontchinese;
} else {
stfontchinese.setfamily(familyname);
}
}
return stfontchinese;
} catch (exception e) {
e.printstacktrace();
return null;
}
}
});
pdfconverter.getinstance().convert(document, outpdf, options);
} catch (ioexception e) {
e.printstacktrace();
} finally {
try {
if (in != null) {
in.close();
}
if (outpdf != null) {
outpdf.close();
}
} catch (ioexception e) {
e.printstacktrace();
}
}
}
}3、word格式

4、导出pdf样式

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论