1.需求:将一个html页面转成pdf格式。
2.方法:在实现之前先考虑一个问题,pdf是前端生成还是后端生成。这里采用pdfbox+itext(PDF文件名可自定义)技术在服务端生成。
优点:免费,不需要安转软件,速度快,对于开发者而言,开发中仅需导入相应jar,且易部署。
缺点:对于html标签比较严格。
3.实现:
3.1 需要的jar
itext-2.0.8.jar+pdfbox-2.0.19.jar
3.2 准备好html页面代码(注意:这里需要手动指定字体):
sHtml += "<!DOCTYPE html[<!ENTITY nbsp ' '>]>";
sHtml += "<html>";
sHtml += "<head>";
sHtml += "</head>";
sHtml += "<body style='font-family:SimSun !important;'>";
sHtml += "<h1>这里是测试PDF代码部分</h1>";
sHtml += "</body>";
sHtml += "</html>";
3.3 服务端开始生成PDF文件:
public static void toPdf(String sHtml) {
try {
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/WINDOWS/Fonts/SimSun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
fontResolver.addFont("C:/WINDOWS/Fonts/Arial.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
String sDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
String sTime = new SimpleDateFormat("HHmmssSSS").format(new Date());
URL sUrlPath = 当前类名.class.getResource("/");
String sPath = sUrlPath.toURI().getPath();
sPath1 = sPath.replace("WEB-INF/classes/", "");
String sPathFolder = sPath+sDate+"\\";
File filePath = new File(sPathFolder);
if(!filePath.exists() && !filePath.isDirectory()){
filePath.mkdirs();
}
String sFileName = sDate+sTime+".pdf";
String sPathSave = sPathFolder+sFileName;
OutputStream os = new FileOutputStream(sPathSave);
renderer.setDocumentFromString(sHtml);
renderer.layout();
renderer.createPDF(os);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3.4 前端页面发起请求,服务端将生成的PDF文件返回。
String sTitle = "测试PDF文件名";
File file = new File(sFileUrl);
try {
OutputStream outputStream = response.getOutputStream();
PDDocument document = PDDocument.load(new FileInputStream(file));
response.reset();
response.setContentType("application/pdf;charset=UTF-8");
response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(sTitle, "UTF-8"));
response.setContentType("application/pdf;charset=UTF-8");
PDDocumentInformation info = document.getDocumentInformation();
info.setTitle(sTitle);
document.setDocumentInformation(info);
document.save(outputStream);
outputStream.close();
document.close();
out.clear();
out = pageContext.pushBody();
} catch (Exception e) {
}
完成!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)