1.1、環境說明
當前實例運行環境為JDK1.8,其他版本略有不同。
1.2、pom.xml中引入相關依賴包
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-Internal</artifactId>
<version>8.2.4</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>8.2.4</version>
</dependency>
1.3、Java部分代碼
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.docx4j.Docx4J;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
public class App {
public static void main(String[] args) {
try {
WordprocessingMLPackage pkg = Docx4J.load(new File("E:\\試題.docx"));
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("FangSong"));
fontMapper.put("幼圓", PhysicalFonts.get("YouYuan"));
fontMapper.put("華文宋體", PhysicalFonts.get("STSong"));
fontMapper.put("華文中宋", PhysicalFonts.get("STZhongsong"));
fontMapper.put("等線", PhysicalFonts.get("SimSun"));
fontMapper.put("等線 Light", PhysicalFonts.get("SimSun"));
fontMapper.put("華文琥珀", PhysicalFonts.get("STHupo"));
fontMapper.put("華文隸書", PhysicalFonts.get("STLiti"));
fontMapper.put("華文新魏", PhysicalFonts.get("STXinwei"));
fontMapper.put("華文彩雲", PhysicalFonts.get("STCaiyun"));
fontMapper.put("方正姚體", PhysicalFonts.get("FZYaoti"));
fontMapper.put("方正舒體", PhysicalFonts.get("FZShuTi"));
fontMapper.put("華文細黑", PhysicalFonts.get("STXihei"));
fontMapper.put("宋體擴展", PhysicalFonts.get("simsun-extB"));
fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312"));
fontMapper.put("新細明體", PhysicalFonts.get("SimSun"));
pkg.setFontMapper(fontMapper);
Docx4J.toPDF(pkg, new FileOutputStream("E:\\試題.pdf"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Docx4JException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}