项目中有一需求,原先在超市小程序中购物完成之后,需要在核验机器上进行核验操作,才能完成整个购物流程。但是核验机器有时候有问题,无法进行核验操作,所以需要在商户后台页面中将订单明细导出pdf文件。
在这个需求中:导出pdf文件需要读取设置的pdf模板和中文字体。
代码在本地测试的时候,通过如下代码进行读取文件:
File file = ResourceUtils.getFile(path+fileName);
但是项目在发布到服务器上之后,却总是报空指针异常,经过日志定位发现,问题在于项目打包成jar文件之后,无法读取模板和中文字体。
必须以流的方式读取这两个文件。
代码如下:
//读取pdf的模板
ClassPathResource tempResource = new ClassPathResource("template.html");
ClassPathResource simResource = new ClassPathResource("simsun.ttc");
File tempFile = writeFile("", "template.html", tempResource);
File simFile = writeFile("", "simsun.ttc", simResource);
private File writeFile(String filePath, String fileName, ClassPathResource resource) throws IOException {
InputStream in = null;
FileOutputStream out = null;
File newFile = new File(filePath + fileName);
try {
in = resource.getInputStream();
//循环存放临时数据
byte[] buff = new byte[1024];
out = new FileOutputStream(newFile);
int length = 0;
while ((length = in.read(buff, 0, 100)) > 0) {
out.write(buff, 0, length);
}
in.close();
out.close();
} catch (Exception e) {
logger.error("writeFile failed.", e);
}
return newFile;
}
以留的方式读取文件。