1、首先需要引入
core-renderer.jar
iText-2.0.8.jar
2一部分代码如下:
core-renderer.jar
iText-2.0.8.jar
2一部分代码如下:
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.cpt.ygc.entity.ClassviewJiegou;
import com.lowagie.text.pdf.BaseFont;
/**
*
* @author 赵永恩
*
*/
public class ZykHtmlPdf {
/**
*
* 不支持中文
*
* @param htmlPath eg:c:\\zyk.html
* @param pdfPath eg:c:\\test.pdf
* @throws Exception
*/
public static void creatPdf_CH(String htmlPath,String pdfPath) throws Exception {
String inputFile = htmlPath;
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = pdfPath;
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
}
/**
*
* 支持中文
*
* @param list_onedate
* @param l_v_jiegou
* @param path
* @param pdfname
* @return
* @throws Exception
*/
public String creatPdf_CH(ArrayList list_onedate,List l_v_jiegou,String path,String pdfname) throws Exception {
ResourceBundle bundle = ResourceBundle.getBundle("FilePathConfig");//FilePathConfig.properties配置文件的获取路径
String qikan_configpath = bundle.getString("qikan_configpath");
String pdfFile=path+qikan_configpath+pdfname;
String s="fail";
String outputFile = pdfFile;
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("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
html.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">").
append("<head>")
.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
.append("<style type=\"text/css\" mce_bogus=\"1\">body {font-family: SimSun;}</style>")
.append("</head>")
.append("<body>");
//-------------自定义内容---start-------------------------
html.append("<div>标 题:"+list_onedate.get(0)+"</div>");
html.append("<div>内容:"+list_onedate.get(1)+"</div>");
//----------------end-----------------------------
html.append("</body></html>");
renderer.setDocumentFromString(html.toString());
// 解决图片的相对路径问题
// renderer.getSharedContext().setBaseURL("file:/F:/teste/html/");
renderer.layout();
renderer.createPDF(os);
os.close();
s="success";
return s;
}
}