摘要:ASP.NET 輕鬆轉 GridView 資料轉檔到 PDF - 使用 iTextSharp
之前介紹過怎麼在 ASP.NET 環境對資料作轉檔匯出到「Excel」,而這次要說的是另一個大家常用的需求就是轉匯到 PDF 檔案,下一次可以來說說轉匯成圖片檔。先不說還沒做的事,一起來看看怎麼轉匯到 PDF 檔案吧!
轉匯 PDF 檔案有幾種方式,我所用的方式是利用「iTextSharp」函示庫
Step 01:下載外掛參考函示庫
iTextSharp 下載「點」
官方說明:iText is an ideal library for developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation.
Step 02:將「itextsharp-5.0.4-dll.zip」解壓縮後的「itextsharp.dll」動態函示庫複製到你的專案裡,然後再到 Visual Studio 裡去加入參考
加入參考 (reference)
到剛剛複製的路徑去選擇 itextsharp.dll 加入參考
Step 03:後續的動作就是設定畫面與編寫程式碼了
在IDE環境裡,依序拉入 Gridview、SqlDataSource 與 Button 並設定相對應的關連。
Step 04:雙按 button 開始編寫轉匯PDF的程式
-- 利用 Imports 載入必要資源
Imports iTextSharp.text ' Document 必要呼叫
Imports iTextSharp.text.pdf ' PdfWriter 必要呼叫
Imports iTextSharp.text.html.simpleparser ' HTMLWorker 必要呼叫
Imports System.IO ' StringReader 與 StringWrite 必要呼叫
-- 插入下面這段程式碼
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Response.ContentType = "application/pdf"
Response.ContentEncoding = System.Text.Encoding.UTF8
Response.AddHeader("content-disposition", "attachment;filename=test.pdf") ' test.pdf 為轉匯的檔名,請自行修改囉
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim stringWrite As System.IO.StringWriter = New StringWriter
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New tmlTextWriter(stringWrite)
Dim form As HtmlForm = New HtmlForm
'form.Controls.Add(GridView1) ' 有加這一行就不用寫下面的 VerifyRenderingInServerForm 宣告
GridView1.RenderControl(htmlWrite)
Dim reader As StringReader = New StringReader(stringWrite.ToString())
Dim doc As Document = New Document(PageSize.A4)
Dim parser As HTMLWorker = New HTMLWorker(doc)
PdfWriter.GetInstance(doc, Response.OutputStream)
doc.Open()
parser.Parse(reader)
doc.Close()
End Sub
-- 再插入必要宣告
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
'處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中
End Sub
-- 執行畫面
-- 另存新檔
-- 轉匯PDF的效果
QQ:如果有2個以上的 Gridview 要一起轉到 PDF 呢?
A:只需要增加 GridView1.RenderControl(htmlWrite) 要加幾個,都寫進來一次搞定。
Reference
ASP.NET Excel 轉檔參考資料
- ASP.NET 簡單五步驟將 GridView 資料轉檔到 Excel
- ASP.NET 轉匯 Excel - 趴兔
- ASP.NET 匯出 Excel - 只能在 Render 期間呼叫 錯誤
- ASP.NET - NPOI Excel 匯出 - 多工作表 Sheets
- ASP.NET 匯出 Excel 檔案 - 趴速力