on 11-02-2007 9:25 PM
Hi,
I created a pdf document on fly using itext(open source) and was able to send that pdf document using java mail API.But i am getting a problem while opening that pdf in my mail
Exception i am getting while opening the pdf is
<b>Adobe reader could not open 'Answers.pdf' because it is either not a supported file type or because the file has been damaged(for example ,it was sent as an attachment and was not correctly decoded)</b>
Please understand the exact problem and send me the pointers.
Points will be awarded
Please find the code for the same and let me know where i am doing wrong
package com.psft;
import java.awt.Color;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;
import com.psft.ByteArrayDataSource;
import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
public class Logout extends HttpServlet
{
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
generatePDF(request, response);
}
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//TODO : Implement
}
public void generatePDF(
HttpServletRequest request,
HttpServletResponse response)
{
try
{
//create a document with certain page size
Document document = new Document(PageSize.A4);
//HttpServletResponse res = request.getServletResponse(true);
//set the mimetype
response.setContentType("application/pdf");
PdfWriter.getInstance(document, response.getOutputStream());
//open the document for adding stuff
document.open();
//create a table with 3 columns
PdfPTable table = new PdfPTable(1);
PdfPCell cell;
//add the first row as header
cell = new PdfPCell(new Paragraph("Answers"));
cell.setBackgroundColor(new Color(34, 90, 141));
table.addCell(cell);
HttpSession session = request.getSession();
StringBuffer blankAnswers =
(StringBuffer) session.getAttribute("blankanswers");
String answersCorrect = blankAnswers.toString();
StringTokenizer st =
new StringTokenizer(
answersCorrect.substring(
0,
answersCorrect.lastIndexOf(",")),
",");
int flag = 0;
Color bg;
while (st.hasMoreTokens())
{
if (flag == 0)
{
flag = 1;
bg = new Color(204, 204, 255);
}
else
{
flag = 0;
bg = new Color(255, 255, 255);
}
cell = new PdfPCell(new Paragraph(st.nextToken()));
cell.setBackgroundColor(bg);
table.addCell(cell);
}
//add the data rows.
document.add(table);
document.close();
sendAnswersToAdministrator(response,document);
}
catch (Exception e)
{
}
}
public void sendAnswersToAdministrator(HttpServletResponse response , Document pdf)
{
try
{
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", "edison.Prosofthq.com");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
// Get session
Authenticator loAuthenticator = new MailAuthenticator();
Session session = Session.getInstance(props, loAuthenticator);
String mailfrom = "bala.duvvuri@prosoftcyberworld.com";
String mailto = "bala.duvvuri@prosoftcyberworld.com";
String ccmailid = "bala.duvvuri@prosoftcyberworld.com";
String subject = "hello";
System.setProperty("mail.mime.encodeeol.strict", "true");
MimeMessage mimemessage = new MimeMessage(session);
// set FROM
mimemessage.setFrom(new InternetAddress(mailfrom));
// set DATE
mimemessage.setSentDate(new java.util.Date());
// set SUBJECT
mimemessage.setSubject(subject);
// set TO address
try
{
mimemessage.setRecipients(
javax.mail.Message.RecipientType.TO,
mailto);
}
catch (Exception exception1)
{
System.out.println(
"\tError in setting recipients ......\t"
+ exception1.getMessage());
}
// set message BODY
MimeBodyPart mimebodypart = new MimeBodyPart();
mimebodypart.setText("hello");
// attach message BODY
MimeMultipart mimemultipart = new MimeMultipart();
mimemultipart.addBodyPart(mimebodypart);
// attach FILE
mimebodypart = new MimeBodyPart();
try
{
<b> mimebodypart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdf.toString(), "application/pdf")));</b>
}
catch (Exception exception3)
{
System.out.println(
"\tError in sending file not been able to attach ......\t"
+ exception3.getMessage());
}
mimebodypart.setFileName("Answers.pdf"); // set FILENAME
mimemultipart.addBodyPart(mimebodypart);
mimemessage.setContent(mimemultipart);
String strResult = "";
//set CC MAIL and SEND the mail
if (!mailto.equals(""))
{
// set CC MAIL
try
{
// send MAIL
Transport.send(mimemessage);
System.out.println("\tSent Successfully..........");
strResult = "\tSent Successfully..........";
}
catch (Exception exception4)
{
System.out.println(
"\tError in sending Address Try........."
+ exception4.getMessage());
}
}
else
{
System.out.println("\tMail operation Failed..........\t");
strResult = "\tMail operation Failed..........\t";
}
}
catch (Exception ex)
{
System.out.println("ddd" + ex.getMessage());
}
finally
{
try{
response.sendRedirect("logout.jsp");
}catch(Exception e){
}
}
}
}
Hi Duwuri,
Did you try to create a ByteArrayDataSource using the PDF binary?
I guess it is the problem.
Regards,
Luciano
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
I solved it by myself .
Find the code snippet below
/*
Created on Nov 2, 2007
*
To change the template for this generated file go to
Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.psft;
import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpSession;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
/**
@author BALU
*
To change the template for this generated type comment go to
Window>Preferences>Java>Code Generation>Code and Comments
*/
public class FileWrite implements Serializable
{
public static void main(String[] a)
{
//import needed
String filepath =
"C:
MyFolder
Answers.pdf";
FileWrite fw = new FileWrite();
fw.callMethods(new StringBuffer("1.program,2.langauge"), filepath);
}
public String retString()
{
return "u got it";
}
public void callMethods(StringBuffer blankAnswers, String filepath)
{
WriteFile(blankAnswers, filepath);
sendMail(filepath);
deleteFile(filepath);
}
public void WriteFile(StringBuffer blankAnswers, String filepath)
{
String s = blankAnswers.toString(); /* String to be written */
char s1 = '\n';
try
{
Document doc = new Document(PageSize.A4);
PdfWriter.getInstance(
doc,
new FileOutputStream(filepath));
doc.open();
//create a table with 3 columns
PdfPTable table = new PdfPTable(1);
PdfPCell cell;
//add the first row as header
cell = new PdfPCell(new Paragraph("Answers"));
cell.setBackgroundColor(new Color(34, 90, 141));
table.addCell(cell);
String answersCorrect = blankAnswers.toString();
StringTokenizer st =
new StringTokenizer(
answersCorrect.substring(
0,
answersCorrect.lastIndexOf(",")),
",");
int flag = 0;
Color bg;
while (st.hasMoreTokens())
{
if (flag == 0)
{
flag = 1;
bg = new Color(204, 204, 255);
}
else
{
flag = 0;
bg = new Color(255, 255, 255);
}
cell = new PdfPCell(new Paragraph(st.nextToken()));
cell.setBackgroundColor(bg);
table.addCell(cell);
}
//add the data rows.
doc.add(table);
doc.close();
}
catch (Exception e)
{
System.out.println("Exception :" + e);
}
}
public void sendMail(String filepath)
{
try
{
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", "edison.Prosofthq.com");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
// Get session
Authenticator loAuthenticator = new MailAuthenticator();
Session session = Session.getInstance(props, loAuthenticator);
String mailfrom = "bala.duvvuri@prosoftcyberworld.com";
String mailto = "bala.duvvuri@prosoftcyberworld.com";
String ccmailid = "bala.duvvuri@prosoftcyberworld.com";
String subject = "hello";
System.setProperty("mail.mime.encodeeol.strict", "true");
MimeMessage mimemessage = new MimeMessage(session);
// set FROM
mimemessage.setFrom(new InternetAddress(mailfrom));
// set DATE
mimemessage.setSentDate(new java.util.Date());
// set SUBJECT
mimemessage.setSubject(subject);
// set TO address
try
{
mimemessage.setRecipients(
javax.mail.Message.RecipientType.TO,
mailto);
}
catch (Exception exception1)
{
System.out.println(
"\tError in setting recipients ......\t"
+ exception1.getMessage());
}
// set message BODY
MimeBodyPart mimebodypart = new MimeBodyPart();
mimebodypart.setText("hello");
// attach message BODY
MimeMultipart mimemultipart = new MimeMultipart();
mimemultipart.addBodyPart(mimebodypart);
// attach FILE
mimebodypart = new MimeBodyPart();
try
{
FileDataSource filedatasource = new FileDataSource(filepath);
mimebodypart.setDataHandler(new DataHandler(filedatasource));
}
catch (Exception exception3)
{
System.out.println(
"\tError in sending file not been able to attach ......\t"
+ exception3.getMessage());
}
mimebodypart.setFileName("Answers.pdf"); // set FILENAME
mimemultipart.addBodyPart(mimebodypart);
mimemessage.setContent(mimemultipart);
String strResult = "";
//set CC MAIL and SEND the mail
if (!mailto.equals(""))
{
// set CC MAIL
try
{
// send MAIL
Transport.send(mimemessage);
System.out.println("\tSent Successfully..........");
strResult = "\tSent Successfully..........";
}
catch (Exception exception4)
{
System.out.println(
"\tError in sending Address Try........."
+ exception4.getMessage());
}
}
else
{
System.out.println("\tMail operation Failed..........\t");
strResult = "\tMail operation Failed..........\t";
}
}
catch (Exception ex)
{
System.out.println("ddd" + ex.getMessage());
}
}
public void deleteFile(String filepath)
{
File f = new File(filepath);
// Make sure the file or directory exists and isn't write protected
if (!f.exists())
throw new IllegalArgumentException(
"Delete: no such file or directory: " + filepath);
if (!f.canWrite())
throw new IllegalArgumentException(
"Delete: write protected: " + filepath);
// If it is a directory, make sure it is empty
if (f.isDirectory())
{
String[] files = f.list();
if (files.length > 0)
throw new IllegalArgumentException(
"Delete: directory not empty: " + filepath);
}
// Attempt to delete it
boolean success = f.delete();
if (!success)
throw new IllegalArgumentException("Delete: deletion failed");
}
}
Thanks for you help.points awarded
User | Count |
---|---|
87 | |
10 | |
10 | |
9 | |
7 | |
7 | |
6 | |
5 | |
4 | |
4 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.