我无法打开作为电子邮件附件发送的 PDF。PDF 是使用 iText 和 Flying Saucer 创建的,并使用 Java 中的 MimeMessage 发送。我很确定在尝试下载附件时存在编码问题,因为创建 PDF 时它看起来很好。只是当作为附件发送时,打开它时出现问题。例如,在 Chrome 中,它会发送“无法加载 PDF 文档”错误。它会在其他浏览器和 Adobe Reader 中发送类似的错误。谢谢。
//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);