最近在討論區看到有人說itextsharp可以把網頁變成PDF
小弟就去抓一下itextsharp來玩玩,先教大家最實用的,就是把GridView匯出成PDF檔
asp.net(c#)
GridViewToPDF.aspx
01 |
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewToPDF.aspx.cs" Inherits="GridViewToPDF" |
02 |
EnableEventValidation="false" %> |
07 |
< title >GridViewToPDF</ title > |
10 |
< form id = "form1" runat = "server" > |
12 |
< asp:Button ID = "Button1" runat = "server" OnClick = "Button1_Click" Text = "匯出至PDF檔" /> |
13 |
< asp:GridView ID = "GridView1" runat = "server" > |
GridViewToPDF.aspx.cs
02 |
using iTextSharp.text; |
03 |
using iTextSharp.text.pdf; |
04 |
using iTextSharp.text.html.simpleparser; |
08 |
using System.Web.UI.HtmlControls; |
09 |
using System.Collections.Generic; |
11 |
public partial class GridViewToPDF : System.Web.UI.Page |
13 |
protected void Page_Load( object sender, EventArgs e) |
17 |
List<member> mem = new List<member>(); |
18 |
mem.Add( new member( "1" , "Puma" )); |
19 |
mem.Add( new member( "2" , "F6 Team" )); |
20 |
this .GridView1.DataSource = mem; |
21 |
this .GridView1.DataBind(); |
25 |
protected void Button1_Click( object sender, EventArgs e) |
27 |
Response.ContentType = "application/pdf" ; |
28 |
Response.ContentEncoding = System.Text.Encoding.UTF8; |
29 |
Response.AddHeader( "content-disposition" , "attachment;filename=test.pdf" ); |
30 |
Response.Cache.SetCacheability(HttpCacheability.NoCache); |
31 |
System.IO.StringWriter stringWrite = new StringWriter(); |
32 |
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); |
34 |
HtmlForm form = new HtmlForm(); |
35 |
form.Controls.Add(GridView1); |
36 |
form.Controls[0].RenderControl(htmlWrite); |
37 |
StringReader reader = new StringReader(stringWrite.ToString()); |
38 |
Document doc = new Document(PageSize.A4); |
39 |
HTMLWorker parser = new HTMLWorker(doc); |
40 |
PdfWriter.GetInstance(doc, Response.OutputStream); |
52 |
public member( string ID, string Name) |
66 |
set { _name = value; } |
執行結果:
參考網址:
http://csharpdotnetfreak.blogspot.com/2008/12/export-gridview-to-pdf-using-itextsharp.html
http://blog.rubypdf.com/2007/10/10/using-htmlworker-to-parse-html-snippets-and-convert-to-pdf/
http://stackoverflow.com/questions/1322303/html-to-pdf-some-characters-are-missing-itextsharp
http://coolwebdeveloper.com/2008/10/using-open-source-itextsharp-net-pdf-library-to-generate-pdf-on-the-fly/
http://forums.asp.net/t/1199774.aspx