Nic*_*ler 6 java pdf email thunderbird
我想从“原始”电子邮件生成 PDF 文档。该电子邮件可以包含 html 或仅包含文本。我不关心附件。
生成的 pdf 应包含正确的格式(来自 css 和 html)以及嵌入的图像。
我的第一个想法是使用 Thunderbird 等电子邮件客户端呈现电子邮件,然后将其打印为 pdf。Thunderbird 是否提供这样的 API 或者是否有 Java 库可用于将电子邮件打印为 pdf?
我找到了比之前发布的更好的解决方案。将电子邮件保存为 html,然后使用jtidy将其清理为 xhtml。最后使用飞碟html渲染器将其保存为pdf。
这是我写的一个例子:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
享受!
| 归档时间: |
|
| 查看次数: |
16346 次 |
| 最近记录: |