您的位置:首页 > Web前端 > HTML

IText实现Html转PDF itextpdf-5.5.5.jar

2015-04-21 19:41 519 查看
环境:itextpdf-5.5.5.jar   xmlworker-5.5.5.jar

尝试做个csdn博文下载器,首要解决的任务是html转pdf,百度到IText,查了很多教程Itext版本都比较老,我下的5.5.5的。

代码不复杂,

public static void main(String[] args) throws FileNotFoundException,
Exception {
String htmlFile = "C:\\Users\\Administrator\\Desktop\\test.htm";

String pdfFile = "C:\\Users\\Administrator\\Desktop\\test.pdf";
// PdfUtils.parseHTML2PDFFile(pdfFile, new FileInputStream(htmlFile));
String ss = "";
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(htmlFile), "UTF-8"));
String t = "";
while ((t = br.readLine()) != null) {
// System.out.println(t);
ss += t;
}
PdfUtils.parseHTML2PDFFile2(pdfFile, ss);
}

public static void parseHTML2PDFFile2(String pdfFile, String html)
throws DocumentException, IOException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(pdfFile));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream(html.getBytes("Utf-8")),
Charset.forName("UTF-8"));
document.close();
}


遇到的问题:中文显示不了,百度了好久没解决,后来尝试写了一个简单的html页面,能显示中文,查了下原因,html要设置字体,在body加<body style="font-size:12.0pt; font-family:微软雅黑">  字体可以换,然后输出就能显示中文了。

复制去Google翻译翻译结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: