主要介紹將GridView顯示的內容轉換爲PDF文檔,當用戶訪問並想將頁面顯示(GridView)的內容保存爲PDF時即可通過本程序先將轉換後的PDF文件保存到服務器中指定的文件夾下,再自動提示用戶是否將得到的PDF文檔保存到本地。
轉換後的PDF文檔每頁都會有GridView的表頭。
1. 得到itextsharp.dll (從網上可以得到)
2. 將這個dll添加引用
3. 下面介紹轉換的類GridViewToPdf.cs 就寫了一個轉換方法ConvertGridViewToPdf()
類GridViewToPdf.cs如下:
- using System;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- //******************************************
- //引入的命名空間
- using System.Text;
- using System.IO;
- using iTextSharp;
- using iTextSharp.text;
- using iTextSharp.text.pdf;
- //******************************************
- /// <summary>
- ///GridViewToPdf 的摘要說明
- /// </summary>
- public class GridViewToPdf
- {
- public GridViewToPdf()
- { }
- #region ConvertGrdiViewToPdf 換GridView爲PDF文檔,每一頁都有表頭
- /// <summary>
- /// 轉換GridView爲PDF文檔
- /// </summary>
- /// <param name="pobjGrdv">要轉換的GridView</param>
- /// <param name="PDFFileName">在服務器端保存PDF時的文件名</param>
- /// <param name="FontPath">PDF甩用字體所在的物理路徑</param>
- /// <param name="FontSize">字體大小</param>
- /// <returns>返回調用是否成功</returns>
- public static void ConvertGrdiViewToPdf(GridView pobjGrdv, string PDFFileName, string FontPath, float FontSize)
- {
- //在服務器端保存PDF時的文件名
- string strFileName = PDFFileName + ".pdf";
- // GridView的所有數據全輸出
- pobjGrdv.AllowPaging = false;
- //**************************
- int countColumns = pobjGrdv.Columns.Count;
- int countRows = pobjGrdv.Rows.Count;
- if (countColumns != 0 && countRows != 0)
- {
- //初始化一個目標文檔類
- //Document document = new Document();
- //豎排模式,大小爲A4,四周邊距均爲25
- Document document = new Document(PageSize.A4, 0, 0, 0, 0);
- //橫排模式,大小爲A4,四周邊距均爲50
- //Document doc = new Document(PageSize.A4.rotate(),50,50,50,50);
- //調用PDF的寫入方法流
- //注意FileMode-Create表示如果目標文件不存在,則創建,如果已存在,則覆蓋。
- PdfWriter writer = PdfWriter.GetInstance(document,
- new FileStream(HttpContext.Current.Server.MapPath(strFileName), FileMode.Create));
- try
- {
- //創建PDF文檔中的字體
- BaseFont baseFont = BaseFont.CreateFont(
- FontPath,
- BaseFont.IDENTITY_H,
- BaseFont.NOT_EMBEDDED);
- //根據字體路徑和字體大小屬性創建字體
- Font font = new Font(baseFont, FontSize);
- // 添加頁腳
- //HeaderFooter footer = new HeaderFooter(new Phrase(footertxt), true);
- HeaderFooter footer = new HeaderFooter(new Phrase("-- ", font), new Phrase(" --", font));
- footer.Border = Rectangle.NO_BORDER; // 不顯示兩條橫線
- footer.Alignment = Rectangle.ALIGN_CENTER; // 讓頁碼居中
- document.Footer = footer;
- //打開目標文檔對象
- document.Open();
- //**************************
- //根據數據表內容創建一個PDF格式的表
- PdfPTable table = new PdfPTable(countColumns);
- //iTextSharp.text.Table table = new iTextSharp.text.Table(pobjGrdv.Columns.Count);
- // 添加表頭
- // 設置表頭背景色
- //table.DefaultCell.BackgroundColor = Color.GRAY; // OK
- //table.DefaultCell.BackgroundColor =
- //(iTextSharp.text.Color)System.Drawing.Color.FromName("#3399FF"); // NG
- table.DefaultCell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY;
- //table.DefaultCell.BackgroundColor = System.Drawing.Color.DodgerBlue;
- // 添加表頭
- for (int j = 0; j < countColumns; j++)
- {
- table.AddCell(new Phrase(pobjGrdv.HeaderRow.Cells[j].Text, font)); // OK
- }
- // 告訴程序這行是表頭,這樣頁數大於1時程序會自動爲你加上表頭。
- table.HeaderRows = 1;
- // 添加數據
- // 設置表體背景色
- table.DefaultCell.BackgroundColor = Color.WHITE;
- //遍歷原gridview的數據行
- for (int i = 0; i < countRows; i++)
- {
- for (int j = 0; j < countColumns; j++)
- {
- table.AddCell(new Phrase(pobjGrdv.Rows[i].Cells[j].Text, font));
- }
- }
- //在目標文檔中添加轉化後的表數據
- document.Add(table);
- }
- catch (Exception)
- {
- throw;
- }
- finally
- {
- //關閉目標文件
- document.Close();
- //關閉寫入流
- writer.Close();
- }
- // 彈出提示框,提示用戶是否下載保存到本地
- try
- {
- //這裏是你文件在項目中的位置,根目錄下就這麼寫
- String FullFileName = System.Web.HttpContext.Current.Server.MapPath(strFileName);
- FileInfo DownloadFile = new FileInfo(FullFileName);
- System.Web.HttpContext.Current.Response.Clear();
- System.Web.HttpContext.Current.Response.ClearHeaders();
- System.Web.HttpContext.Current.Response.Buffer = false;
- System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
- System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename="
- + System.Web.HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
- System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
- System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
- }
- catch (Exception)
- {
- throw;
- }
- finally
- {
- System.Web.HttpContext.Current.Response.Flush();
- System.Web.HttpContext.Current.Response.End();
- }
- }
- else
- {
- System.Web.HttpContext.Current.Response.Write
- ("<script type='text/javascript'>alert('數據爲空,不值得導出pdf!');</script>");
- }
- }
- //然後,在要調用轉換的按鈕的事件代碼中調用就可以了
- //假設傳進去的GridView的名字爲GridView1
- //假設要保存的文件名爲GridView的ID
- //假設字體使用simsun (請注意根據你電腦的實際情況來選擇目錄)
- //假設字號選擇14
- //GridViewToPdf.ConvertGridViewToPdf(this.GridView1,
- //this.GridView1.ID.ToString(), "c:\\winnt\\FONTS\\simsun.ttc,1", 14);
- #endregion
- }
4. 外部使用時調用方法:
- using System.IO;
- using iTextSharp.text;
- /// <summary>
- /// 導出爲pdf
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void Button_ExportPdf_Click(object sender, EventArgs e)
- {
- try
- {
- //假定GridView的ID爲GridView_CheckStat
- GridView_CheckStat.AllowPaging = false;
- GridView_CheckStat.AllowSorting = false;
- //從頁面取到查詢條件
- string materialType = this.txtMaterialType.Text;
- string depotType = this.DropDownList_DepotType.SelectedValue;
- string depotId = this.DropDownList_Depot.SelectedValue;
- string goodsName = this.txtGoodsName.Text.Trim();
- //填充數據源
- GridView_CheckStat.DataSource = CheckStatBll.getCheckStatByCondition(materialType, depotId, depotType,goodsName);
- //綁定數據源
- GridView_CheckStat.DataBind();
- //調用上面寫好的轉換方法
- //將綁定好的GridView傳入下面方法
- GridViewToPdf.ConvertGridViewToPdf(this.GridView_CheckStat, this.GridView_CheckStat.ID.ToString(), @"c:\WINDOWS\Fonts\msyh.ttf", 8);
- }
- catch (DocumentException de)
- {
- Response.Write(de.ToString());
- }
- }
轉載:http://blog.csdn.net/lai123wei/article/details/8292937
- 頂
- 0
- 踩