Issue
hey i'm working on a web application and i have problems to combine 2 features (build a pdf and send it as attachment with a email). Both parts are working separately, but i don't know how to get the file path of the creaded PDF to add it to the mail attachment.
The following are the importent codesnippets:
- I create a new PDF file (with itext 5) with the java servlet CreatePDF and show it in a new tab:
CreatePDF Servlet:
//initial new ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//get absolute path of the logo
String relativeLogoWebPath = "/logo.jpg";
String absoluteLogoDiskPath = getServletContext().getRealPath(relativeLogoWebPath);
//build PDF with itextpdf
new BuildPDF(baos, acc, absoluteLogoDiskPath, header, body, footer, vat);
// setting the content type
response.setHeader("Expires", "0");
response.setHeader("Cache-Control","must-revalidate, post-check=0,precheck=0");
response.setHeader("Pragma", "public");
response.setContentType("application/pdf");
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
BuildPDF Class:
public BuildPDF(ByteArrayOutputStream baos, Accounting acc, String absolutLogoPath,
Collection<String> header, Collection<String> body, Collection<String> footer, Double vat){
//init document
Document document = new Document(PageSize.A4, 60, 30, 140, 90);
document.setMarginMirroring(false);
//init pdf writer
PdfWriter writer = PdfWriter.getInstance(document, baos);
writer.setBoxSize("art", new com.itextpdf.text.Rectangle(36, 54, 559, 788));
//add header and footer
HeaderFooter event = new HeaderFooter(header, footer, absolutLogoPath);
writer.setPageEvent(event);
//open the document
document.open();
//add title and body
addTitle(document, acc)
addBody(document, acc, body, vat, writer);
//close document and pdf writer
document.close();
writer.close();
}
- In the other tab I go to the next jsp page and after a button click (to open the servlet SendAccouningPage) it should be possible to send this creaded pdf with a email (with java mail):
SendAccountingPage Servlet:
//TODO: get path of created PDF
String[] attachFiles = new String[1];
//attachFiles[0] = (String) request.getSession().getAttribute("pdfPath");
//request.getSession().removeAttribute("pdfPath");
EmailUtility.sendEmailWithAttachments(host, port, fromMail, passwort,
mail, subject, message, attachFiles);
EmailUtility Class:
public static void sendEmailWithAttachments(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message, String[] attachFiles)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null && attachFiles.length > 0) {
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
So is there a way to get the file path of the creaded pdf and store it e.g. into the session? (and if yes: How resistant is this path? Is it lost if I close the tab with the created pdf?)
If not:
How can I combine it otherwise?
Do i have to save the pdf (if yes: Which chances do I have to do and is it possible to save it only temporary?)
Solution
You are creating the PDF in memory using a ByteArrayOutputStream
(named baos
), and then you write this file to the output stream of the servlet:
OutputStream os = response.getOutputStream();
baos.writeTo(os);
That is good practice, but there's also an alternative way.
The ByteArrayOutputStream
has a method called toByteArray()
, so you could also do it like this:
OutputStream os = response.getOutputStream();
byte[] bytes = baos.toByteArray();
os.write(bytes, 0, bytes.length);
os.flush();
os.close();
Now you have the complete file in the byte[]
named bytes
, you need to adapt your EmailUtility
class so that it accepts a byte array instead of the path to a file. That's explained in the answer to the following question: Mail Attachments with byte array:
MimeBodyPart att = new MimeBodyPart();
ByteArrayDataSource bds = new ByteArrayDataSource(byte, "application/pdf");
att.setDataHandler(new DataHandler(bds));
att.setFileName(bds.getName());
And that's how you send a mail with an attachment of a file that is created in memory and never stored as a file on disk on the server.
Answered By - Bruno Lowagie