2
votes

I am having trouble opening a PDF sent as an email attachment. The PDF is created using iText and Flying Saucer and sent using MimeMessage in Java. I'm pretty sure that there is an encoding issue when trying to download the attachment, because when the PDF is created it looks fine. It's just when sent as an attachment there is an issue opening it. For example, in Chrome it sends the "Failed to load PDF document" error. It sends similar errors in other browsers and in Adobe Reader. Thanks.

//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);            
2

2 Answers

1
votes

The problem was I was setting

os=response.getOutputStream

Instead, I got rid of this line and created

byte[] outputBytes = os.toByteArray();

which is now what I used in my dataSource.

0
votes

What is "buf"? Why are you converting it to a string and then extracting the bytes from the string assuming it's encoded in iso-8859-1?

It looks like th PDF is being created to "os" ,which isn't saved anywhere and isn't used for the attachment.