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

例子如下 
Java代码  收藏代码
  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.io.PrintWriter;  
  4. import java.io.StringWriter;  
  5. import java.util.HashMap;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.ServletOutputStream;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. import net.sf.jasperreports.engine.JREmptyDataSource;  
  14. import net.sf.jasperreports.engine.JRException;  
  15. import net.sf.jasperreports.engine.JasperRunManager;  
  16.   
  17. public class JasperReportServlet extends HttpServlet {  
  18.   
  19.     private static final long serialVersionUID = 1L;  
  20.   
  21.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  22.             throws ServletException, IOException {  
  23.         //获得输出流  
  24.         ServletOutputStream outputStream = response.getOutputStream();  
  25.         //获得输入流  
  26.         InputStream inputStream = getServletConfig().getServletContext().getResourceAsStream("JasperFile//JasperReportFile.jasper");  
  27.         try {  
  28.               
  29.             //生成网页的PDF文件  
  30.             JasperRunManager.runReportToPdfStream(inputStream, outputStream, new HashMap(), new JREmptyDataSource());  
  31.             //设置PDF格式  
  32.             response.setContentType("application/pdf");  
  33.             outputStream.flush();  
  34.             outputStream.close();             
  35.         } catch (JRException e) {  
  36.             StringWriter stringWriter = new StringWriter();  
  37.             PrintWriter printWriter = new PrintWriter(stringWriter);  
  38.             e.printStackTrace(printWriter);  
  39.             response.setContentType("text/plain");  
  40.             response.getOutputStream().print(stringWriter.toString());  
  41.         }  
  42.     }  
  43.   
  44.       
  45.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  46.             throws ServletException, IOException {  
  47.         this.doPost(request, response);  
  48.     }  
  49. }  

posted on 2012-07-17 16:26  星^_^風  阅读(250)  评论(0编辑  收藏  举报