打印信息,通过.jasper工具将集合输出到PDF文件 然后利用打印机打印文件

我们上一次成功的利用iReport工具制作了一张报表,并且预览了报表最后的效果,也生成了格式为“jrpxml”、“jrxml”与“jasper”的文件。这次,我们使用jasper提供的java的api去利用在iReport中制作的报表jasper文件来生成真正的报表文件。

本文以生成pdf格式的报表文件为例,该报表文件包含所有男用户的信息。

首先我们打开MyEclipse,在其中创建一个java工程:

新建一个lib文件夹,然后在lib中加入我们准备好的jar包:

然后将这些jar包全部添加到环境中(右键build path)


然后编写获取数据库连接的类,用于连接数据库并获取相应连接对象,以便于后期操作数据库:

[java]  view plain  copy
 
  1. package com.cn.org.ireport.test;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5.   
  6. public class JDBCConnection {  
  7.       
  8.     public static Connection getConnection(){  
  9.         try {  
  10.              String url = "jdbc:mysql://localhost:3306/db_film";  
  11.              Class.forName("org.gjt.mm.mysql.Driver");  
  12.              Connection con = DriverManager.getConnection(url, "root", "1234");  
  13.              return con;  
  14.          }catch(Exception e){  
  15.               e. printStackTrace();  
  16.          }  
  17.          return null;  
  18.     }  
  19. }  


接下来编写dataSource类(也就是数据填充类),实现JRDataSource接口,通过放在list里面的Map对象迭代实现数据对应:

[java]  view plain  copy
 
  1. package com.cn.org.ireport.test;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Iterator;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import net.sf.jasperreports.engine.JRDataSource;  
  9. import net.sf.jasperreports.engine.JRException;  
  10. import net.sf.jasperreports.engine.JRField;  
  11. /** 
  12. *  dataSource类(也就是数据填充类),实现JRDataSource接口 
  13. *  通过放在list里面的Map对象迭代,实现数据对应 
  14. */  
  15. public class ReportDataSource implements JRDataSource{  
  16.   
  17.     private Iterator iter;  
  18.       
  19.     //创建一个,map对象用与数据对应  
  20.     Map map = new HashMap();  
  21.       
  22.     //无参的构造函数  
  23.     public ReportDataSource(){  
  24.           
  25.     }  
  26.       
  27.     //以sex为参数的有参构造函数,用于数据初始化  
  28.     public ReportDataSource(String sex){  
  29.         //通过性别获取相应用户的数据  
  30.         List datas=DateSourceBaseFactory.createBeanCollection(sex);  
  31.         //要将List中的数据迭代,需要使用Iterator迭代对象  
  32.         iter=datas.iterator();  
  33.     }  
  34.       
  35.     //通过key获取value值  
  36.     public Object getFieldValue(JRField arg0) throws JRException {  
  37.         return map.get(arg0.getName());  
  38.     }  
  39.   
  40.     //接口JRDataSource的方法,判断是否有下一个数据  
  41.     public boolean next() throws JRException {  
  42.         if(iter.hasNext()){  
  43.             map=(Map)iter.next();  
  44.             return true;  
  45.         }  
  46.         return false;  
  47.     }  
  48.   
  49. }  


接下来实现上个类中的DateSourceBaseFactory(提供数据的数据源工厂),它是实际从数据库中取出相应数据,然后将其封装在map中,然后又将相应的map装在List容器中。

[java]  view plain  copy
 
  1. package com.cn.org.ireport.test;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.ResultSet;  
  5. import java.sql.SQLException;  
  6. import java.sql.Statement;  
  7. import java.util.ArrayList;  
  8. import java.util.HashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11. /** 
  12.  * Map中的键值要与模板中的file值对应 
  13.  * */  
  14. public class DateSourceBaseFactory {  
  15.   
  16.     public static List createBeanCollection(String sex) {  
  17.           
  18.         int num=0;  
  19.         if(sex.equals("男")){  
  20.             num=1;  
  21.         }else{  
  22.             num=2;  
  23.         }  
  24.           
  25.         ResultSet rs=null;  
  26.         Statement st=null;  
  27.         Connection con=null;  
  28.         List datas=new ArrayList();  
  29.           
  30.         try {  
  31.             con=JDBCConnection.getConnection();  
  32.             st=con.createStatement();  
  33.             rs=st.executeQuery("select name,brithday,province,Email from user where sex="+num);  
  34.             while(rs.next()){  
  35.                 Map attris=new HashMap();  
  36.                 attris.put("name", rs.getString("name"));  
  37.                 attris.put("brithday", rs.getString("brithday"));  
  38.                 attris.put("province", rs.getString("province"));  
  39.                 attris.put("Email", rs.getString("Email"));  
  40.                 datas.add(attris);  
  41.             }  
  42.         } catch (Exception e) {  
  43.             e.printStackTrace();  
  44.         }finally{  
  45.                 try {  
  46.                     if(rs!=null) rs.close();  
  47.                     if(st!=null) st.close();  
  48.                     if(con!=null) con.close();  
  49.                 } catch (SQLException e) {  
  50.                     e.printStackTrace();  
  51.                 }  
  52.         }  
  53.           
  54.         return datas;  
  55.     }  
  56.   
  57. }  


接下来编写dataSource的javaBean类。用于创建模板

[java]  view plain  copy
 
  1. package com.cn.org.ireport.test;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class DataSoruceBean implements Serializable{  
  6.   
  7.     private static final long serialVersionUID = 1L;  
  8.       
  9.     private String name;  
  10.     private String brithday;  
  11.     private String province;  
  12.     private String Email;  
  13.     public String getName() {  
  14.         return name;  
  15.     }  
  16.     public void setName(String name) {  
  17.         this.name = name;  
  18.     }  
  19.     public String getBrithday() {  
  20.         return brithday;  
  21.     }  
  22.     public void setBrithday(String brithday) {  
  23.         this.brithday = brithday;  
  24.     }  
  25.     public String getProvince() {  
  26.         return province;  
  27.     }  
  28.     public void setProvince(String province) {  
  29.         this.province = province;  
  30.     }  
  31.     public String getEmail() {  
  32.         return this.Email;  
  33.     }  
  34.     public void setEmail(String email) {  
  35.         this.Email = email;  
  36.     }  
  37. }  


接下来是重头戏,编写测试入口类,生成pdf文件。JasperFillManager中有多个生成文件的方法
,除了可以生成pdf文件外还可以生成ofice文档文件。这里我们就将取出的数据打印到报表中去:

[java]  view plain  copy
 
  1. package com.cn.org.ireport.test;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileOutputStream;  
  6. import java.util.HashMap;  
  7. import java.util.Map;  
  8.   
  9. import net.sf.jasperreports.engine.JRAbstractExporter;  
  10. import net.sf.jasperreports.engine.JRException;  
  11. import net.sf.jasperreports.engine.JRExporterParameter;  
  12. import net.sf.jasperreports.engine.JasperFillManager;  
  13. import net.sf.jasperreports.engine.JasperPrint;  
  14. import net.sf.jasperreports.engine.export.JRPdfExporter;  
  15. import net.sf.jasperreports.engine.export.JRPdfExporterParameter;  
  16.   
  17. public class TestReportHere {  
  18.     public static void main(String[] args) {  
  19.         Map parameters=new HashMap();  
  20.         ByteArrayOutputStream outPut=new ByteArrayOutputStream();  
  21.         FileOutputStream outputStream=null;  
  22.         File file=new File("F:/Temp/report.pdf");  
  23.         String reportModelFile="C:/Users/jack/report2.jasper";  
  24.           
  25.         try {  
  26.             JasperPrint jasperPrint=JasperFillManager.fillReport(reportModelFile,  
  27.                     parameters,new ReportDataSource("男"));  
  28.             JRAbstractExporter exporter=new JRPdfExporter();  
  29.             //创建jasperPrint  
  30.             exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
  31.             //生成输出流  
  32.             exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outPut);  
  33.             //屏蔽copy功能  
  34.             exporter.setParameter(JRPdfExporterParameter.IS_ENCRYPTED,Boolean.TRUE);  
  35.             //加密  
  36.             exporter.setParameter(JRPdfExporterParameter.IS_128_BIT_KEY,Boolean.TRUE);  
  37.             exporter.exportReport();  
  38.             outputStream=new FileOutputStream(file);  
  39.             outputStream.write(outPut.toByteArray());  
  40.         } catch (JRException e) {  
  41.             e.printStackTrace();  
  42.         }catch (Exception e) {  
  43.             e.printStackTrace();  
  44.         }finally{  
  45.             try {  
  46.                 outPut.flush();  
  47.                 outPut.close();  
  48.             } catch (Exception e) {  
  49.                 e.printStackTrace();  
  50.             }  
  51.         }  
  52.     }  
  53. }  


我们点击右键“Run JavaAppliacrion”,来执行我们的报表生成样例。
运行结果,我们在F盘下的Temp下发现了新生成的pdf文件:

双击打开,就是我们之前需要的数据的报表信息。

注意:报表Pdf时,会出现中文无法显示问题,可以设置相关组件的以下属性。需同时设置,其他字体,可自行尝试。
1、Font name :宋体
2、pdf Font name is now deprecated:STSong-Light
3、pdf Encoding : UniGB-UCS2-H(China Simplified)

至此我们实现了使用jasper提供的java的api来实现封装数据打印报表的功能。

直接在网页上下载这个PDF格式文件

/**
* 输出jasper 报表
*
* @param reportHanderImpi
* @throws AppException
*/
public void exportReport(ReportHanderImpl reportHanderImpl)
throws AppException {
this.getRequest().setAttribute(ReportConstants.REPORT_FLAG, "0");
this.getRequest().setAttribute(ReportConstants.REPORT_PATH_SYMBOL,
reportHanderImpl.getReportFile());
if(reportHanderImpl instanceof CommonReportHandler){
// 报表文件的输入流
this.getRequest().setAttribute(ReportConstants.REPORT_INPUTSTREAM,
((CommonReportHandler)reportHanderImpl).getReportInputStream());
}

List datalist = reportHanderImpl.getDataList();
JRDataSource dataSource = null;
if (datalist != null && datalist.size()>0) {
dataSource = new JRBeanCollectionDataSource(datalist);// 获取数据集
} else {
dataSource = new JREmptyDataSource();
}

this.getRequest().setAttribute(
ReportConstants.REPORT_DATASOURCE_SYMBOL, dataSource);
this.getRequest().setAttribute(ReportConstants.DISPLAY_FIELDS_SYMBOL,
reportHanderImpl.getDisplayStr());
//获取报表类型(表格 or 图形)
this.getRequest().setAttribute( ReportConstants.REPORT_TYPE_SYMBOL, reportHanderImpl.getReportType());
//报表输出格式类型(PDF or EXCEL ,HTML)
this.getRequest().setAttribute( ReportConstants.REPORT_OUT_FORMAT_SYMBOL, reportHanderImpl.getFormatType());
this.getRequest().setAttribute(ReportConstants.REPORT_PARAMETER_SYMBOL,
reportHanderImpl.getParamMap());
try {
this.getRequest().getRequestDispatcher("/JReportServlet").forward(
ServletActionContext.getRequest(),
ServletActionContext.getResponse());
} catch (ServletException e) {
new AppException(e);
} catch (IOException e) {
new AppException(e);
}
}

EG2:

@SuppressWarnings("rawtypes")
public void exportReportList1(CommonReportHandler commonReportHandler)
throws AppException {

List lst = commonReportHandler.getDataSourceList();
List<Object> dataSourceList = null;
try {
if (lst != null && lst.size() > 0) {
dataSourceList = new ArrayList<Object>();
JRDataSource dataSource = null;
for (int i = 0; i < lst.size(); i++) {
List datalist = (List) lst.get(i);
if (datalist != null && datalist.size() > 0) {
dataSource = new JRBeanCollectionDataSource(datalist);// 获取数据集
} else {
dataSource = new JREmptyDataSource();
}
dataSourceList.add(dataSource);// 组装数据源集合

}
}
this.getRequest().setAttribute(ReportConstants.REPORT_FLAG, "1");
// 设置路径
this.getRequest().setAttribute(
ReportConstants.REPORT_PATHLIST_SYMBOL,
commonReportHandler.getReportFiles());
// 获取报表类型(表格 or 图形)
this.getRequest().setAttribute("ReportType", "GraphicsReport");
// 报表输出格式类型(PDF or EXCEL ,HTML)
this.getRequest().setAttribute(
ReportConstants.REPORT_OUT_FORMAT_SYMBOL,
commonReportHandler.getFormatType());
// 设置数据源LIST
this.getRequest().setAttribute(
ReportConstants.REPORT_DATASOURCELIST_SYMBOL,
dataSourceList);
// 设置MAP参数
this.getRequest().setAttribute(
ReportConstants.REPORT_PARAMETER_SYMBOL,
commonReportHandler.getParamMap());
this.getRequest()
.getRequestDispatcher("/JReportServlet")
.forward(ServletActionContext.getRequest(),
ServletActionContext.getResponse());
} catch (ServletException e) {
throw new AppException(e);
} catch (IOException e) {
throw new AppException(e);
}
}

猜你喜欢

转载自www.cnblogs.com/UUUz/p/9167565.html