电子邮件中的Itext PDF附件
问题描述:
我无法打开以电子邮件附件形式发送的PDF。 PDF是使用iText和Flying Saucer创建的,并使用Java中的MimeMessage发送。我非常肯定,在尝试下载附件时存在编码问题,因为当创建PDF时,它看起来很好。只是在作为附件发送时,存在打开它的问题。例如,在Chrome中,它发送“无法加载PDF文档”错误。它在其他浏览器和Adobe Reader中发送类似的错误。谢谢。电子邮件中的Itext PDF附件
//creates the pdf
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
byte[] bytes = buf.toString().getBytes("iso-8859-1");
ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
Document doc = builder.parse(baos);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.layout();
OutputStream os = new ByteArrayOutputStream();
os = response.getOutputStream();
renderer.createPDF(os);
os.close();
//email
MimeMessage msg = new MimeMessage(session);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is a test");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
//construct the pdf body part
DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
messageBodyPart.setDataHandler(new DataHandler(dataSource));
messageBodyPart.setFileName("test.pdf");
multipart.addBodyPart(messageBodyPart);
//construct message
msg.setHeader("Content-Type", "multipart/mixed");
msg.setFrom(new InternetAddress(user));
msg.setReplyTo(InternetAddress.parse(replyEmail,false));
msg.setSubject("Test");
msg.setRecipients(Message.RecipientType.TO, to);
msg.setSentDate(new java.util.Date());
msg.setContent(multipart);
//send email
Transport.send(msg);
答
问题是我设置
os=response.getOutputStream
相反,我摆脱了这一行,创造
byte[] outputBytes = os.toByteArray();
这是现在我在我的数据源使用。
答
什么是“buf”?为什么要将它转换为一个字符串,然后从字符串中提取字节,假定它是在iso-8859-1中编码的?
它看起来像PDF正在创建为“os”,它不保存在任何地方,不用于附件。
我知道我需要在附件中使用os,我只是无法弄清楚。我试图只使用messageBodyPart.setContent(os,“application/pdf”);而不是使用DataSource;但它会发送一个IOexception,指出“无对象DCH用于MIME类型应用程序/ pdf” – mjenkins2010 2013-03-25 15:17:54
而不是“字节”,请尝试在ByteArrayDataSource中使用“os.toByteArray()”。请注意,如果PDF文档非常大,这将很昂贵。 – 2013-03-25 21:28:09
试过了。它说找不到符号方法toByteArray() – mjenkins2010 2013-03-26 12:33:41