我有一个JSP页面,我正在尝试开发新功能,以便从该JSP页面生成PDF,以将其作为附件发送给用户。
我能够将JSP转换为速度模板并将其作为HTML文件发送给用户,但是当我尝试使用fly源lib发送PDF附件时我得到了(无法加载PDF文档)到那个附件。
这就是我想要做的事情,
try {
MimeMessage mm = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mm,true);
helper.setSentDate(new Date());
helper.setSubject(subject);
helper.setFrom(from);
helper.setTo(to.trim());
LOG.debug("**Getting here");
Map<String, Object> model = new HashMap<>();
model.put("date", new DateTool());
//Get the report as html
String xmltoConvert = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
"toConvert.xhtml", StandardCharsets.UTF_8.name(), model);
// tring to convert xhtml to PDF
ByteArrayResource htmlBytes = new ByteArrayResource(xmltoConvert.getBytes(StandardCharsets.UTF_8));
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
org.w3c.dom.Document document = XMLResource.load(new ByteArrayInputStream(xmltoConvert.getBytes())).getDocument();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument( document, null );
renderer.layout();
renderer.createPDF(byteArrayOutputStream);
renderer.finishPDF();
byteArrayOutputStream.close();
helper.addAttachment(subject + ".pdf", htmlBytes);
javaMailSender.send(mm);
}
你能帮忙吗,我错过了什么?
答案 0 :(得分:0)
我必须传递byteArrayOutputStream而不是htmlBytes ..
helper.addAttachment(subject + ".pdf",
new ByteArrayResource(byteArrayOutputStream.toByteArray()));