将GridView导出为PDF 通过itextsharp

主要介绍将GridView显示的内容转换为PDF文档,当用户访问并想将页面显示(GridView)的内容保存为PDF时即可通过本程序先将转换后的PDF文件保存到服务器中指定的文件夹下,再自动提示用户是否将得到的PDF文档保存到本地。

     转换后的PDF文档每页都会有GridView的表头。

1.      得到itextsharp.dll (从网上可以得到)

2.      将这个dll添加引用

3.      下面介绍转换的类GridViewToPdf.cs 就写了一个转换方法ConvertGridViewToPdf()

         类GridViewToPdf.cs如下:

[csharp] view plaincopy
  1. using System;  
  2. using System.Web;  
  3. using System.Web.UI;  
  4. using System.Web.UI.WebControls;  
  5. //******************************************  
  6. //引入的命名空间  
  7. using System.Text;  
  8. using System.IO;  
  9. using iTextSharp;  
  10. using iTextSharp.text;  
  11. using iTextSharp.text.pdf;  
  12. //******************************************  
  13.   
  14. /// <summary>  
  15. ///GridViewToPdf 的摘要说明  
  16. /// </summary>  
  17. public class GridViewToPdf  
  18. {  
  19.     public GridViewToPdf()  
  20.     {   }  
  21.     #region ConvertGrdiViewToPdf 换GridView为PDF文档,每一页都有表头  
  22.   
  23.     /// <summary>  
  24.     /// 转换GridView为PDF文档  
  25.     /// </summary>  
  26.     /// <param name="pobjGrdv">要转换的GridView</param>  
  27.     /// <param name="PDFFileName">在服务器端保存PDF时的文件名</param>  
  28.     /// <param name="FontPath">PDF甩用字体所在的物理路径</param>  
  29.     /// <param name="FontSize">字体大小</param>  
  30.     /// <returns>返回调用是否成功</returns>  
  31.     public static void ConvertGrdiViewToPdf(GridView pobjGrdv, string PDFFileName, string FontPath, float FontSize)  
  32.     {  
  33.         //在服务器端保存PDF时的文件名  
  34.         string strFileName = PDFFileName + ".pdf";  
  35.         // GridView的所有数据全输出  
  36.         pobjGrdv.AllowPaging = false;  
  37.         //**************************  
  38.         int countColumns = pobjGrdv.Columns.Count;  
  39.         int countRows = pobjGrdv.Rows.Count;  
  40.         if (countColumns != 0 && countRows != 0)  
  41.         {  
  42.             //初始化一个目标文档类          
  43.             //Document document = new Document();  
  44.             //竖排模式,大小为A4,四周边距均为25  
  45.             Document document = new Document(PageSize.A4, 0, 0, 0, 0);  
  46.             //横排模式,大小为A4,四周边距均为50  
  47.             //Document doc = new Document(PageSize.A4.rotate(),50,50,50,50);  
  48.             //调用PDF的写入方法流  
  49.             //注意FileMode-Create表示如果目标文件不存在,则创建,如果已存在,则覆盖。  
  50.             PdfWriter writer = PdfWriter.GetInstance(document,   
  51.                 new FileStream(HttpContext.Current.Server.MapPath(strFileName), FileMode.Create));  
  52.             try  
  53.             {  
  54.                 //创建PDF文档中的字体  
  55.                 BaseFont baseFont = BaseFont.CreateFont(  
  56.                   FontPath,  
  57.                   BaseFont.IDENTITY_H,  
  58.                   BaseFont.NOT_EMBEDDED);  
  59.                 //根据字体路径和字体大小属性创建字体  
  60.                 Font font = new Font(baseFont, FontSize);  
  61.                 // 添加页脚  
  62.                 //HeaderFooter footer = new HeaderFooter(new Phrase(footertxt), true);  
  63.                 HeaderFooter footer = new HeaderFooter(new Phrase("-- ", font), new Phrase(" --", font));  
  64.                 footer.Border = Rectangle.NO_BORDER;        // 不显示两条横线  
  65.                 footer.Alignment = Rectangle.ALIGN_CENTER;  // 让页码居中  
  66.                 document.Footer = footer;  
  67.                 //打开目标文档对象  
  68.                 document.Open();  
  69.                 //**************************  
  70.                 //根据数据表内容创建一个PDF格式的表  
  71.                 PdfPTable table = new PdfPTable(countColumns);  
  72.                 //iTextSharp.text.Table table = new iTextSharp.text.Table(pobjGrdv.Columns.Count);  
  73.                 // 添加表头  
  74.                 // 设置表头背景色   
  75.                 //table.DefaultCell.BackgroundColor = Color.GRAY;  // OK  
  76.                 //table.DefaultCell.BackgroundColor =   
  77.                 //(iTextSharp.text.Color)System.Drawing.Color.FromName("#3399FF"); // NG  
  78.                 table.DefaultCell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY;  
  79.                 //table.DefaultCell.BackgroundColor = System.Drawing.Color.DodgerBlue;    
  80.                 // 添加表头  
  81.                 for (int j = 0; j < countColumns; j++)  
  82.                 {  
  83.                     table.AddCell(new Phrase(pobjGrdv.HeaderRow.Cells[j].Text, font));    // OK  
  84.                 }  
  85.                 // 告诉程序这行是表头,这样页数大于1时程序会自动为你加上表头。  
  86.                 table.HeaderRows = 1;  
  87.                 // 添加数据  
  88.                 // 设置表体背景色  
  89.                 table.DefaultCell.BackgroundColor = Color.WHITE;  
  90.                 //遍历原gridview的数据行  
  91.                 for (int i = 0; i < countRows; i++)  
  92.                 {  
  93.                     for (int j = 0; j < countColumns; j++)  
  94.                     {  
  95.                         table.AddCell(new Phrase(pobjGrdv.Rows[i].Cells[j].Text, font));  
  96.                     }  
  97.                 }  
  98.                 //在目标文档中添加转化后的表数据  
  99.                 document.Add(table);  
  100.             }  
  101.             catch (Exception)  
  102.             {  
  103.                 throw;  
  104.             }  
  105.             finally  
  106.             {  
  107.                 //关闭目标文件  
  108.                 document.Close();  
  109.                 //关闭写入流  
  110.                 writer.Close();  
  111.             }  
  112.             // 弹出提示框,提示用户是否下载保存到本地  
  113.             try  
  114.             {  
  115.                 //这里是你文件在项目中的位置,根目录下就这么写   
  116.                 String FullFileName = System.Web.HttpContext.Current.Server.MapPath(strFileName);  
  117.                 FileInfo DownloadFile = new FileInfo(FullFileName);  
  118.                 System.Web.HttpContext.Current.Response.Clear();  
  119.                 System.Web.HttpContext.Current.Response.ClearHeaders();  
  120.                 System.Web.HttpContext.Current.Response.Buffer = false;  
  121.                 System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";  
  122.                 System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition""attachment;filename="   
  123.                     + System.Web.HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));  
  124.                 System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());  
  125.                 System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);  
  126.             }  
  127.             catch (Exception)  
  128.             {  
  129.                 throw;  
  130.             }  
  131.             finally  
  132.             {  
  133.                 System.Web.HttpContext.Current.Response.Flush();  
  134.                 System.Web.HttpContext.Current.Response.End();  
  135.             }  
  136.         }  
  137.         else  
  138.         {  
  139.             System.Web.HttpContext.Current.Response.Write  
  140.                 ("<script type='text/javascript'>alert('数据为空,不值得导出pdf!');</script>");  
  141.         }  
  142.     }  
  143.     //然后,在要调用转换的按钮的事件代码中调用就可以了  
  144.     //假设传进去的GridView的名字为GridView1  
  145.     //假设要保存的文件名为GridView的ID  
  146.     //假设字体使用simsun (请注意根据你电脑的实际情况来选择目录)  
  147.     //假设字号选择14  
  148.     //GridViewToPdf.ConvertGridViewToPdf(this.GridView1,   
  149.     //this.GridView1.ID.ToString(), "c:\\winnt\\FONTS\\simsun.ttc,1", 14);  
  150.     #endregion  
  151. }  

4.      外部使用时调用方法:

[csharp] view plaincopy
  1. using System.IO;  
  2. using iTextSharp.text;  
  3.   
  4.     /// <summary>  
  5.     /// 导出为pdf  
  6.     /// </summary>  
  7.     /// <param name="sender"></param>  
  8.     /// <param name="e"></param>  
  9.     protected void Button_ExportPdf_Click(object sender, EventArgs e)  
  10.     {  
  11.         try  
  12.         {  
  13.         //假定GridView的ID为GridView_CheckStat  
  14.             GridView_CheckStat.AllowPaging = false;  
  15.             GridView_CheckStat.AllowSorting = false;  
  16.             //从页面取到查询条件  
  17.             string materialType = this.txtMaterialType.Text;  
  18.             string depotType = this.DropDownList_DepotType.SelectedValue;  
  19.             string depotId = this.DropDownList_Depot.SelectedValue;  
  20.             string goodsName = this.txtGoodsName.Text.Trim();  
  21.             //填充数据源  
  22.             GridView_CheckStat.DataSource = CheckStatBll.getCheckStatByCondition(materialType, depotId, depotType,goodsName);  
  23.             //绑定数据源  
  24.             GridView_CheckStat.DataBind();  
  25.             //调用上面写好的转换方法  
  26.             //将绑定好的GridView传入下面方法  
  27. GridViewToPdf.ConvertGridViewToPdf(this.GridView_CheckStat, this.GridView_CheckStat.ID.ToString(), @"c:\WINDOWS\Fonts\msyh.ttf", 8);  
  28.         }  
  29.         catch (DocumentException de)  
  30.         {  
  31.             Response.Write(de.ToString());  
  32.         }  
  33.     }  


转载:http://blog.csdn.net/lai123wei/article/details/8292937
0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章