java jsp 生成 pdf flyingsaucer

jsp 要生成pdf 首先要将jsp转成html ,然后将html生成pdf
1.将jsp转成html
在jsp页面上要做如下修改
[color=blue] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">[/color]
jsp 中的所有的标签都要闭合,在页面的css 中指定
body {font-family: SimSun;} }
@page{size:210mm,297mm}
其中@page指定的是生成pdf的文档大小,这个尺寸表示A4(不指定默认是A4),要生成pdf的jsp页面不要出现java代码,从后台向前台传值尽量用jstl ,如果一定要有java代码,可以吧java代码写在其他页面,然后用 [color=blue]<jsp:include page="/student.jsp"></jsp:include>[/color]将这个页面包含进来。

以上就是前台jsp页面的准备。
在后台掉一个方法:

[color=blue]public void createHtmlByJsp(String htmlPath,String url, ServletContext sc,
HttpServletRequest request, HttpServletResponse response) {
try {
RequestDispatcher rd = sc.getRequestDispatcher(url);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final ServletOutputStream stream = new ServletOutputStream() {
public void write(byte[] data, int offset, int length) {
os.write(data, offset, length);
}
public void write(int b) throws IOException {
os.write(b);
}
};
final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));;
HttpServletResponse rep = new HttpServletResponseWrapper(response) {
public ServletOutputStream getOutputStream() {
return stream;
}
public PrintWriter getWriter() {
return pw;
}
};
rd.include(request, rep);
pw.flush();
FileOutputStream fos = new FileOutputStream(htmlPath); // 把jsp输出的内容写到d:\test.htm
os.writeTo(fos);
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}[/color]


其中htmlPath 是存放生成html的路径,URL 是要转成html的jsp的路径。
这样jsp就转成html了。
2.将html转成pdf
[color=blue]public void parseHtmlToPdf(String inputFile ,String outFile)
{
try{
//String inputFile = "D:/student.html";
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();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
System.out.println("======转换成功!");
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}[/color]

inputFile 是html的路径 outFile 是输出pdf的路径
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值