前几个章节写了基础导出word的一些问题以及注意的坑,本章节记录一下转化为pdf相关内容;
思路还是xml先转化为word,然后word转化为pdf。需要用到jar包(aspose-words-15.8.0-jdk16.jar)。
核心代码如下:getData05就是获取业务数据,自己按照项目实际情况来。
private static void test005() throws Exception{
String word_xml_temp_01="D:\\data\\exportWord1\\tmp205.xml";
String LICENSE_XML="D:\\data\\exportWord1\\license.xml";
Map<String,Object> resultMap=getData05();
String currentTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String filePath = new StringBuilder(currentTime).append(".doc").toString();
FileUtil.mkdir(wordDir);
String docPath=new StringBuilder(wordDir).append("/").append(filePath).toString();
File outFile = new File(docPath);
Configuration configuration = new Configuration(Configuration.VERSION_2_3_20);
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(wordDir));
InputStream inputStream = new FileInputStream(new File(word_xml_temp_01));
String fileXmlPath = new StringBuilder(currentTime).append(".xml").toString();
File xmlFile = new File(new StringBuilder(wordDir).append("/").append(fileXmlPath).toString());
FileUtils.copyInputStreamToFile(inputStream, xmlFile);
Template t = configuration.getTemplate(fileXmlPath, "utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 102400);
t.process(resultMap, out);
out.flush();
out.close();
InputStream lis=new FileInputStream(new File(LICENSE_XML));
License aposeLic = new License();
aposeLic.setLicense(lis);
String pdfPath=new StringBuilder(wordDir).append("/").append(currentTime).append(".pdf").toString();
File pdfFile=new File(pdfPath);
FileOutputStream pdfOs = new FileOutputStream(pdfFile);
Document doc = new Document(docPath); // Address是将要被转化的word文档
doc.save(pdfOs, SaveFormat.PDF);
}