package htmltopdf;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.itextpdf.text.pdf.BaseFont;
/**
* 将html文件转换成pdf
* @author lvgb
*
*/
public class HtmlToPdf {
public static void main(String[] args) {
try {
//html文件路径
String htmlPath = "E:\\test\\pdf\\fj_entrust_cut_payment_template.html";
//pdf文件路径
String outputFilePath = "E:\\test\\pdf\\lvgb888.pdf";
//字符集文件路径
String fontPath = "E:\\test\\pdf\\simsun.ttc";
htmlToPdfTest(htmlPath,outputFilePath,fontPath);
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
}
}
public static String htmlToPdfTest(String htmlPath, String outputFile,String fontPath) throws Exception {
OutputStream os = new FileOutputStream(outputFile);
FileInputStream fis = new FileInputStream(new File(htmlPath));
StringWriter writers = new StringWriter();
InputStreamReader isr = null;
String string = null;
// 此处将io流转换成String
try {
isr = new InputStreamReader(fis, Charset.forName("UTF-8"));// 包装基础输入流且指定编码方式
// 将输入流写入输出流
char[] buffer = new char[2048];
int n = 0;
while (-1 != (n = isr.read(buffer))) {
writers.write(buffer, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (isr != null)
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writers != null) {
string = writers.toString();
}
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(fontPath,
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.setDocumentFromString(string);
renderer.layout();
renderer.createPDF(os);
os.close();
return outputFile;
}
}