1、index.html文件内容如下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>HTML to PDF</title>
<link href="_css/index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>HTML to PDF</h1>
<p>
<span class="itext">itext</span> 2.0.8 <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>
</body>
</html>
index.css内容如下
@CHARSET "UTF-8";
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;
}
2、java代码
package com.yfli.iText;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.itextpdf.text.pdf.BaseFont;
public class HtmlToPDFTest {
public static void main(String[] args) throws Exception {
parseHtmlToPdf();
}
/**
* 使用的jar包:itext-2.0.8.jar core-render.jar
*
* @throws Exception
*/
public static void parseHtmlToPdf() throws Exception {
// step 1
String outputFile = "F:/iText/htmlToPdf2.pdf";
String inputFile = "F:/iText/index.html";
String url = new File(inputFile).toURI().toURL().toString();
// step 2
OutputStream os = new FileOutputStream(outputFile);
org.xhtmlrenderer.pdf.ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
// step 3 解决中文支持
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("c:/Windows/Fonts/simsun.ttc",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 解决图片的相对路径问题
// renderer.getSharedContext().setBaseURL("file:/F:/teste/html/");
renderer.layout();
renderer.createPDF(os);
os.close();
}
}
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/16343.html