上篇文章说到导出word报表,但是因为各种原因可能最后下载下来的word有内容格式的缺失,打开文件格式可能各不相同,所以需要将word转换为pdf下载展示。
1.pom文件的导入
<!--word2pdf-->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
2.在之前的工具类升级
public class WordUtils {
//临时文件存储路径
public static String path = Thread.currentThread().getContextClassLoader()
.getResource("").getPath();
public static String docxpath = path + "temporary.docx";
public static String pdfpath = path + "temporary.pdf";
/**
* word文档文件导出
*
* @param response HttpServletResponse对象
* @param fileName 导出word文档文件的文件名
* @param fileName 导出word文档文件的文件名
*/
public static void exportWord(HttpServletResponse response,
Map<String,Object> map,
String fileName) throws Exception {
//八进制输出流
response.setContentType("application/octet-stream");
//设置导出word的名称
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
//刷新缓冲
response.flushBuffer();
//workbook将Excel写入到response的输出流中,供页面下载该Excel文件
XWPFDocument xwpfDocument = WordExportUtil.exportWord07("template/report.docx", map);
//将word生成 然后转pdf
FileOutputStream docxFile = new FileOutputStream(docxpath);
xwpfDocument.write(docxFile); //将模板填充后输出到临时文件
//word转pdf防止格式变形
word2Pdf();
// xwpfDocument.write(response.getOutputStream()); //直接输入word文档
// 实现文件下载 将生成的pdf临时文件遍历写入response
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream outputStream = response.getOutputStream();
File outputFile = new File(pdfpath);
fis = new FileInputStream(outputFile);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bis.read(buffer);
}
//关闭workbook bis
xwpfDocument.close();
bis.close();
}
/**
*
*/
private static void word2Pdf() {
try {
File inputWord = new File(docxpath);
File outputFile = new File(pdfpath);
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
和之前的区别就是之前直接导出文件流,现在需要将word首先存储在临时文件中,然后将word转化成pdf。再循环读取写入文件流。