Itext将HTML文件转换成PDF
1.需要下载 itext.jar包,xmlworker-5.5.4.zip,这些包都能在sourceforge中找到!
效果图:
package com.pdfbox.pdf;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
/**
* HTML转换PDF
* @author LGF 2015-01-04
*
*/
public class HTMLToPDF {
public static void main(String[] args) throws Exception {
//创建文档对象
Document doc = new Document();
//创建输出流
OutputStream out = new FileOutputStream("src/html.pdf");
//获取PdfWriter实例
PdfWriter writer = PdfWriter.getInstance(doc, out);
//打开文档
doc.open();
//获取 XMLWorkerHelper实例
XMLWorkerHelper work = XMLWorkerHelper.getInstance();
//解析html文件,创建pdf文档
work.parseXHtml(writer, doc, getInputStream("pdf.html"));
//释放资源
doc.close();
writer.close();
out.close();
System.out.println("success");
}
/**
* 获取 class path 中的文件流
* @param name 名称
* @return InputStream
*/
public static InputStream getInputStream(String name){
return Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>HTML to PDF</title>
<style type="text/css">
h1 {
color:#ccc;
}
table tr td{
text-align:center;
border:1px solid gray;
padding:4px;
}
table tr th{
background-color:#84C7FD;
color:#fff;
width: 100px;
}
.itext{
color:#84C7FD;
font-weight:bold;
}
.description{
color:gray;
}
</style>
</head>
<body>
<h1>HTML to PDF</h1>
<p>
<span class="itext">itext 5.4.2</span>
<span class="description">converting HTML to PDF</span>
</p>
<table>
<tr>
<th class="label">Title</th>
<td>iText - Java HTML to PDF</td>
</tr>
<tr>
<th>URL</th>
<td>http://hmkcode.com/itext-html-to-pdf-using-java</td>
</tr>
</table>
<img src="http://dl2.iteye.com/upload/attachment/0083/2873/9d920e8c-8f09-395a-986a-e7a49911676c.png"/>
</body>
</html>