J2EE使用iText将数据保存为PDF文档

在B/S结构的项目中,经常需要将一些数据导出为PDF文档,项目中我们使用的就是iText包,该包可以从其官方网上下载: http://www.lowagie.com/iText/  。

下面就来讲一下具体的使用方法。

1、首先我们建一个叫做DbgridColumn的Java类,用来表示标题信息,具体字段如图。

 
java 代码
  1. List columns = new ArrayList();    
  2.   
  3. DbgridColumn column = new DbgridColumn();    
  4. column.setProperty = "DM";   
  5. column.setCaption  = "代码";    
  6. column.setWidth    = 35;    
  7. columns.add(column);    
  8.   
  9. column.setProperty = "MC";    
  10. column.setCaption  = "名称";    
  11. column.setWidth    = 175;    
  12. columns.add(column);  

2、我们需要构建演示数据,数据列表与Java构建函数。

 
java 代码
  1. Collection collection = new ArrayList();       
  2.      
  3. Map map = new HashMap();                                                
  4. map.put("DM",new String("01");    
  5. map.put("MC",new String("设置成功");    
  6. collection.add(map);    
  7.                                                                                      
  8. map.put("DM",new String("02");    
  9. map.put("MC",new String("中继命令没有返回");    
  10. collection.add(map);    
  11.       
  12. map.put("DM",new String("03");    
  13. map.put("MC",new String("设置内容非法");    
  14. collection.add(map); 
  15. map.put("DM",new String("04");    
  16. map.put("MC",new String("密码权限不足");    
  17. collection.add(map);    
  18.         
  19. map.put("DM",new String("05");       
  20. map.put("MC",new String("无此数据项");   
  21. collection.add(map);                     
  22.                                          
  23. map.put("DM",new String("06");    
  24. map.put("MC",new String("命令时间失效");   
  25. collection.add(map);    
  26.                         
  27. map.put("DM",new String("07");   
  28. map.put("MC",new String("目标地址不存在");   
  29. collection.add(map);                         
  30.                                              
  31. map.put("DM",new String("08");    
  32. map.put("MC",new String("发送失败");   
  33. collection.add(map);                   
  34.        
  35. map.put("DM",new String("09");   
  36. map.put("MC",new String("短消息帧太长");   
  37. collection.add(map); 
  

3、将上面格式的数据转换为iText的PdfPTable格式。

java 代码
  1. public class PdfReport extends ReportModal       
  2. {                                                
  3.                                                  
  4.    public PdfReport(OutputStream out,DbgridModal modal)   
  5.    {                                                      
  6.       this.out = out;    
  7. this.modal = modal;        
  8.    }    
  9.   
  10.    public PdfReport()    
  11. { }    
  12.   
  13.    public void out()   
  14.    {   
  15. Document document = new Document();     
  16.       try    
  17. {     
  18.         public class PdfReport extends ReportModal    
  19. {         
  20.            
  21.    public PdfReport(OutputStream out,DbgridModal modal)    
  22.    {         
  23.       this.out = out;    
  24.  this.modal = modal;         
  25.    }    
  26.   
  27.    public PdfReport()    
  28.  {     
  29.    }    
  30. /* 输出 */       
  31.    public void out()       
  32.    {    
  33.      Document document = new Document();     
  34.       try    
  35.      {       
  36.          PdfWriter.getInstance(document, out);           
  37.       document.open();     
  38.      document.add(DbgridToPdfTable(modal.columns,modal.collection));    
  39.  }      
  40.       catch (DocumentException e)    
  41.     {    
  42.        throw new Error(e.getMessage(), e);      
  43.       }    
  44.   catch (IOException e)         
  45.       {     
  46.          throw new Error(e.getMessage(), e);    
  47.     }    
  48.    if(document.isOpen())    
  49.    {         
  50.             document.close();        
  51.       }    
  52.   
  53.       
  54.   public PdfPTable  DbgridToPdfTable(List columns,Collection collection)    
  55.   throws BadElementException,DocumentException,IOException    
  56.  {    
  57.       int columnsCount = columns.size();    
  58.   int rowsCount = collection.size();         
  59.       //创建Pdf Table    
  60.    PdfPTable table = new PdfPTable(columnsCount);    
  61.   //table总宽度    
  62. table.setTotalWidth((float)getTotalWidth(columns));        
  63.       table.setWidths(getWidths(columns));   
  64.       //每列之间的间隔    
  65. table.setSpacingBefore(Float.parseFloat("1.0"));    
  66. //使用中文字符,要支持中文字符,还需要在其官方网站下载iTextAsian.jar和iTextAsianCmaps.jar 两个包     
  67.  BaseFont bfChinese = BaseFont.createFont("STSong-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);         
  68.       com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 9, com.lowagie.text.Font.NORMAL);      
  69.       //开始写标题    
  70.   for (int i=0;i      
  71.       {        
  72.          DbgridColumn dbgridColumn = (DbgridColumn)columns.get(i);         
  73.          //创建单元格    
  74.  PdfPCell cell = new PdfPCell(new Phrase(dbgridColumn.getCaption(), FontChinese ));     
  75.          //标题的背景颜色    
  76.       cell.setBackgroundColor(new Color(212,208,200));         
  77.          //左右对齐方式         
  78.          cell.setHorizontalAlignment(getCellAlign(dbgridColumn.getAlign()));     
  79.          //垂直对齐方式默认为中间对齐    
  80.          cell.setVerticalAlignment(Element.ALIGN_MIDDLE);    
  81.          table.addCell(cell);          
  82.       }         
  83.           
  84.    //写表格数据        
  85.       Object[] objects = (Object[])collection.toArray();    
  86.       for (int j=0;j,@gdE}  {     
  87.          Map map = (Map)objects[j];         
  88.          for (int i=0;i&Uo(}         {         
  89.              String value = "";    
  90. DbgridColumn dbgridColumn = (DbgridColumn)columns.get(i);        
  91.              //根据字段名取数据    
  92.    Object bean = map.get(dbgridColumn.getProperty());          
  93.              //getRealValue函数是对具体的一些数据类型(比如日期、double、integer等)进行格式化处理,如果为null,则返回空字符串           
  94.  value = getRealValue(bean,dbgridColumn);         
  95.   //创建单元格        
  96.  PdfPCell cell = new PdfPCell(new Phrase(value, FontChinese ));    
  97.  //对齐方式       
  98. cell.setHorizontalAlignment(getCellAlign(dbgridColumn.getAlign()));       
  99.   cell.setVerticalAlignment(Element.ALIGN_TOP);    
  100.       table.addCell(cell);        
  101.          }    
  102.    }    
  103.   
  104.       return table;   
  105.    }    
  106.  /* 把字符串型对齐方式 left,right,center 转化为pdf格式的对齐方式 */    
  107.  public int getCellAlign(String align)      
  108.    {       
  109.       if (align==null)       
  110.       {    
  111. return Cell.ALIGN_LEFT;       
  112.       }         
  113.       if (align.toLowerCase().equals("left"))    
  114.  {    
  115. return Cell.ALIGN_LEFT;    
  116.       }          
  117.    if (align.toLowerCase().equals("right"))    
  118. {       
  119.          return Cell.ALIGN_RIGHT;     
  120.       }    
  121.   if (align.toLowerCase().equals("center"))    
  122.   {    
  123. return Cell.ALIGN_CENTER;    
  124.  }    
  125.  return Cell.ALIGN_LEFT;     
  126.   
  127. /* 返回一个int型的数组,存放每列的宽度 */    
  128.    public int[] getWidths(java.util.List cols)    
  129.  {    
  130.   int widths[]=new int[cols.size()];        
  131.       for (int i=0;i       
  132.       {    
  133.     DbgridColumn dbgridColumn = (DbgridColumn)cols.get(i);         
  134.          widths[i] = dbgridColumn.getWidth();        
  135.       }    
  136.     return widths;     
  137.    }       
  138.  /* 返回表格的总宽度 */    
  139. public int getTotalWidth(java.util.List cols)    
  140.   {    
  141. int totalwidth = 0;    
  142.  for (int i=0;i2N    {    
  143.     DbgridColumn dbgridColumn = (DbgridColumn)cols.get(i);       
  144.          totalwidth = totalwidth + dbgridColumn.getWidth();    
  145.      }    
  146.   return totalwidth;          
  147.    }    
  148.  PdfWriter.getInstance(document, out);           
  149.       document.open();     
  150.     document.add(DbgridToPdfTable(modal.columns,modal.collection));    
  151.     }                                                                                    
  152.       catch (DocumentException e)    
  153.      {    
  154.        throw new Error(e.getMessage(), e);                                         
  155.       }    
  156.     catch (IOException e)                                                                         
  157.       {                                                                                   
  158.          throw new Error(e.getMessage(), e);    
  159.      }    
  160.    if(document.isOpen())    
  161.     {                                                                                  
  162.             document.close();                                                                                  
  163.       }    
  164.   
  165.  public PdfPTable  DbgridToPdfTable(List columns,Collection collection)    
  166.      throws BadElementException,DocumentException,IOException    
  167.    {                                                                                  
  168.       int columnsCount = columns.size();    
  169.    int rowsCount = collection.size();  
  170.  //创建Pdf Table    
  171.    PdfPTable table = new PdfPTable(columnsCount);    
  172.     //table总宽度    
  173.   table.setTotalWidth((float)getTotalWidth(columns));      
  174. //每列的宽度  
  175.  table.setWidths(getWidths(columns));     
  176.  //每列之间的间隔    
  177.   table.setSpacingBefore(Float.parseFloat("1.0"));    
  178.     //使用中文字符,要支持中文字符,还需要在其官方网站下载iTextAsian.jar和iTextAsianCmaps.jar 两个包     
  179. BaseFont bfChinese = BaseFont.createFont("STSong-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);     
  180. com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 9, com.lowagie.text.Font.NORMAL);        
  181. //开始写标题    
  182.     for (int i=0;i                                                                               
  183.       {            
  184.  DbgridColumn dbgridColumn = (DbgridColumn)columns.get(i);           
  185. //创建单元格    
  186.      PdfPCell cell = new PdfPCell(new Phrase(dbgridColumn.getCaption(), FontChinese ));      
  187. //标题的背景颜色    
  188.        cell.setBackgroundColor(new Color(212,208,200));       
  189.  //左右对齐方式    
  190. cell.setHorizontalAlignment(getCellAlign(dbgridColumn.getAlign()));         
  191.   //垂直对齐方式默认为中间对齐          
  192.  cell.setVerticalAlignment(Element.ALIGN_MIDDLE);   
  193.  table.addCell(cell); 
  194.  }                                                                                   
  195.           
  196.     //写表格数据    
  197. Object[] objects = (Object[])collection.toArray();          
  198.  for (int j=0;j,@gdE}Guest      {  
  199. Map map = (Map)objects[j];  for (int i=0;      { 
  200. String value = "";    
  201.  DbgridColumn dbgridColumn = (DbgridColumn)columns.get(i);        
  202. //根据字段名取数据    
  203.             Object bean = map.get(dbgridColumn.getProperty());           
  204. //getRealValue函数是对具体的一些数据类型(比如日期、double、integer等)进行格式化处理,如果为null,则返回空字符串      
  205. value = getRealValue(bean,dbgridColumn);                                                                                  
  206.              //创建单元格                                                                                
  207.              PdfPCell cell = new PdfPCell(new Phrase(value, FontChinese ));    
  208.             //对齐方式                                                                                            
  209.              cell.setVerticalAlignment(Element.ALIGN_TOP);    
  210.    table.addCell(cell);                                                                                  
  211.                                                                                        
  212.       return table;                                                                              
  213.    }    
  214.   /* 把字符串型对齐方式 left,right,center 转化为pdf格式的对齐方式 */    
  215.  public int getCellAlign(String align)                                                                                   
  216.    {                                                                             
  217.       if (align==null)                                                                          
  218.       {    
  219.      return Cell.ALIGN_LEFT;                                                                                
  220.       }                                                                              
  221.       if (align.toLowerCase().equals("left"))    
  222.      {    
  223.        return Cell.ALIGN_LEFT;                                                                                    
  224.       }          
  225.      if (align.toLowerCase().equals("right"))    
  226.       {                                                                                   
  227.          return Cell.ALIGN_RIGHT;                                                                                  
  228.       }    
  229.    if (align.toLowerCase().equals("center"))    
  230.      {    
  231.  return Cell.ALIGN_CENTER;    
  232.     }    
  233.     return Cell.ALIGN_LEFT;                                                                                  
  234.    }    
  235.      
  236.   /* 返回一个int型的数组,存放每列的宽度 */  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值