package com.utils.msgsdk;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;
/***根据HTML生成PDF文档
* Title:ItextUtil
* Description: 2018-8-1 11:04:54
* @author puwj
* @date
*/
public class ItextUtil
{
public static String getConversionHtmlCode(String linkcss,String htmlCode,String title){
String css = "";
css +="<style>";
css +="table{";
css +=" border-collapse: collapse;";
css +=" font-size: 15px;";
css +=" width: 98%;";
css +="}";
css +="";
css +="td{";
css +=" border: 1px solid #ddd;";
css +=" text-align: left;";
css +=" white-space: nowrap";
css +="}";
css +="th{";
css +=" border: 1px solid #ddd;";
css +=" text-align: left;";
css +="}";
css +="</style>";
String html = "<html><head>"+css+"</head><body style = \"padding:0; margin:0;margin-top: 15px;margin-bottom: 15px; text-align: center; font-family:SimSun;\" >"+ title+"<br></br><br></br>"+ htmlCode + "</body></html>";
System.out.println("html:"+html);
return html;
}
public static void htmlCodeComeString(String linkcss,String htmlCode, String outputFile,String title) throws Exception {
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(getConversionHtmlCode(linkcss,htmlCode,title));
ITextFontResolver fontResolver = renderer.getFontResolver();
URL fontPath = ItextUtil.class.getResource("simsun.ttc");
fontResolver.addFont(fontPath.toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 解决图片的相对路径问题
// renderer.getSharedContext().setBaseURL("file:/F:/teste/html/");
renderer.layout();
renderer.createPDF(os);
System.out.println("======转换成功!");
os.close();
os.flush();
}
public static void main(String[] args)
{
ItextUtil itextUtil = new ItextUtil();
String html = "";
html += "<table>";
html += "<caption align=\"center\">企业信息</caption>";
html += " <tbody>";
html += " <tr>";
html += " <th>登记日期</th>";
html += " <td>2006-04-28</td>";
html += " </tr>";
html += " <tr>";
html += " <th>纳税人编号</th>";
html += " <td>HSJIHKS002</td>";
html += " </tr>";
html += " <tr>";
html += " <th>有效标志</th>";
html += " <td>Y</td>";
html += " </tr>";
html += " <tr>";
html += " <th>社会信用代码</th>";
html += " <td>916101317H</td>";
html += " </tr>";
html += " <tr>";
html += " <th>评估机关代码</th>";
html += " <td>盛世</td>";
html += " </tr>";
html += " <tr>";
html += " <th>工商注销日期</th>";
html += " <td>2006-04-28</td>";
html += " </tr>";
html += " </tbody>";
html += "</table>";
String outputFile = "D:\\pdf\\aa.pdf";
try
{
itextUtil.htmlCodeComeString("",html,outputFile,"");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("生成结束!!!");
}
}