html页面转换成PDF文件
发布时间:-06-14 05:24:50
来源:51CTO
阅读:523
作者:robinmars
packagepdftest;
importjava.io.BufferedReader;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
.MalformedURLException;
.URL;
importorg.xhtmlrenderer.pdf.ITextFontResolver;
importorg.xhtmlrenderer.pdf.ITextRenderer;
importcom.lowagie.text.pdf.BaseFont;
/**
*将html页面转换成PDF文件
*应用包itext-2.0.8.jarcore-renderer-R8.jar
*不支持中文,若支持中文需对内容进行改动
*
*/
publicclassRendererTest{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
try{
ITextRendererrenderer=newITextRenderer();
//StringblogURL="http://;
StringblogURL="http://";
//指定模板地址
//renderer.setDocument("http://");
//根据网址,获取网页内容
StringhtmlBody=getHtmlContent(blogURL);
//将网页内容进行格式校验及调整,以便于renderer能够解析,根据内容调整
htmlBody=htmlBody.replaceAll("
","
");
htmlBody="
"+htmlBody.substring(htmlBody.indexOf("-->")+3);
htmlBody=htmlBody.substring(0,htmlBody.indexOf("")+7);
htmlBody="htmlPUBLIC\"-//W3C//DTDXHTML1.0Transitional//EN\"\"/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"+htmlBody;
System.out.println(htmlBody);
//将调整完内容设置到renderer中
renderer.setDocumentFromString(htmlBody);
//字符处理,本处需要处理中文
ITextFontResolverfontResolver=renderer.getFontResolver();
//if(StringUtils.isOSWindow())
//fontResolver.addFont("C:/Windows/Fonts/ARIALUNI.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
//else
fontResolver.addFont("/leo-work/workspace/mytest/lib/msyh.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
renderer.layout();
StringpdfFile2="/Users/leo/Desktop/a6.pdf";
//OutputStreamos=response.getOutputStream();//输出到网页
OutputStreamos=newFileOutputStream(pdfFile2);//输出到文件
//根据renderer内容,创建PDF文件
renderer.createPDF(os);
//关闭输出柳
os.close();
}catch(Exceptione){
System.out.println(e.getMessage());
}
}
/**
*通过网址获取网页内容
*@paramhtmlurl
*@return
*/
publicstaticStringgetHtmlContent(Stringhtmlurl){
URLurl;
Stringtemp;
StringBuffersb=newStringBuffer();
try{
url=newURL(htmlurl);
BufferedReaderin=newBufferedReader(newInputStreamReader(url.openStream(),"utf-8"));//读取网页全部内容
while((temp=in.readLine())!=null){
sb.append(temp);
}
in.close();
}catch(finalMalformedURLExceptionme){
System.out.println("你输入的URL格式有问题!");
me.getMessage();
}catch(finalIOExceptione){
e.printStackTrace();
}
returnsb.toString();
}
}