將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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章