2013-03-23 115 views
2

我無法打開以電子郵件附件形式發送的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);    

回答

1

問題是我設置

os=response.getOutputStream

相反,我擺脫了這一行,創造

byte[] outputBytes = os.toByteArray(); 

這是現在我在我的數據源使用。

0

什麼是「buf」?爲什麼要將它轉換爲一個字符串,然後從字符串中提取字節,假定它是在iso-8859-1中編碼的?

它看起來像PDF正在創建爲「os」,它不保存在任何地方,不用於附件。

+0

我知道我需要在附件中使用os,我只是無法弄清楚。我試圖只使用messageBodyPart.setContent(os,「application/pdf」);而不是使用DataSource;但它會發送一個IOexception,指出「無對象DCH用於MIME類型應用程序/ pdf」 – mjenkins2010 2013-03-25 15:17:54

+0

而不是「字節」,請嘗試在ByteArrayDataSource中使用「os.toByteArray()」。請注意,如果PDF文檔非常大,這將很昂貴。 – 2013-03-25 21:28:09

+0

試過了。它說找不到符號方法toByteArray() – mjenkins2010 2013-03-26 12:33:41