import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;
public class HtmltoPDF {
public static void main( String[] args ) throws Exception{
// htmlToPdf();
// htmlToPdf2();
htmlToPdf3();
}
// 不支持中文
public static void htmlToPdf() throws Exception
{
String inputFile = "D:/Test/flying.html";
String url = new File( inputFile ).toURI().toURL().toString();
String outputFile = "D:/Test/flying.pdf";
OutputStream os = new FileOutputStream( outputFile );
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument( url );
renderer.layout();
renderer.createPDF( os );
os.close();
}
// 支持中文
public static void htmlToPdf2() throws Exception {
String outputFile = "F:/TestDemo/demo_3.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
StringBuffer html = new StringBuffer();
// DOCTYPE 必需写否则类似于 这样的字符解析会出现错误
html.append("");
html.append("").
append("")
.append("")
.append("")
.append("")
.append("");
html.append("
支持中文!
");
html.append("");
renderer.setDocumentFromString(html.toString());
// 解决图片的相对路径问题
// renderer.getSharedContext().setBaseURL("file:/F:/teste/html/");
renderer.layout();
renderer.createPDF(os);
System.out.println("======转换成功!");
os.close();
}
public static void htmlToPdf3() throws Exception{
String inputFile = "F:/TestDemo/test.html";
String outFile = "F:/TestDemo/test.pdf";
OutputStream os = null;
os = new FileOutputStream(outFile);
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
String url = new File( inputFile ).toURI().toURL().toString();
System.out.println("=============url: "+url);
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
System.out.println("======转换成功!");
os.close();
}
}