I've found a better solution to the one I posted before. saving the email to html, then use jtidy to clean it up to xhtml. and lastly use flying saucer html renderer to save it into pdf.
Here is an example I wrote:
import com.lowagie.text.DocumentException;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
import java.util.*;
import javax.mail.*;
public class Email2PDF {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
//read your latest email
store.connect("imap.gmail.com", "youremail@gmail.com", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
String filename = msg.getSubject();
FileOutputStream os = new FileOutputStream(filename + ".html");
msg.writeTo(os);
//use jtidy to clean up the html
cleanHtml(filename);
//save it into pdf
createPdf(filename);
} catch (Exception mex) {
mex.printStackTrace();
}
}
public static void cleanHtml(String filename) {
File file = new File(filename + ".html");
InputStream in = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStream out = null;
try {
out = new FileOutputStream(filename + ".xhtml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final Tidy tidy = new Tidy();
tidy.setQuiet(false);
tidy.setShowWarnings(true);
tidy.setShowErrors(0);
tidy.setMakeClean(true);
tidy.setForceOutput(true);
org.w3c.dom.Document document = tidy.parseDOM(in, out);
}
public static void createPdf(String filename)
throws IOException, DocumentException {
OutputStream os = new FileOutputStream(filename + ".pdf");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new File(filename + ".xhtml"));
renderer.layout();
renderer.createPDF(os) ;
os.close();
}
}
Enjoy!