JasperReport学习笔记3-在浏览器生成PDF文件

在浏览器生成PDF文件,主要用了JasperRunManager对象面的runReportToPdfStream方法,在WEB里一般都先用iReport生成jasper文件,这样就去解析JRXML文件了

例子如下
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;

public class JasperReportServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获得输出流
		ServletOutputStream outputStream = response.getOutputStream();
		//获得输入流
		InputStream inputStream = getServletConfig().getServletContext().getResourceAsStream("JasperFile//JasperReportFile.jasper");
		try {
			
			//生成网页的PDF文件
			JasperRunManager.runReportToPdfStream(inputStream, outputStream, new HashMap(), new JREmptyDataSource());
			//设置PDF格式
			response.setContentType("application/pdf");
			outputStream.flush();
			outputStream.close();			
		} catch (JRException e) {
			StringWriter stringWriter = new StringWriter();
			PrintWriter printWriter = new PrintWriter(stringWriter);
			e.printStackTrace(printWriter);
			response.setContentType("text/plain");
			response.getOutputStream().print(stringWriter.toString());
		}
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

}

你可能感兴趣的:(java,.net,Web,浏览器,servlet)