將網頁物件輸出至PDF,以下使用Table為例。
1.Download the itextsharp.dll from Internet.
2.Reference of itextsharp.dll
3.use following references of itextsharp.dll
using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html.simpleparser;4.Now the whole code of tsPDF.aspx.cs page will be as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; using System.IO; using System.Web; using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html.simpleparser; public partial class Test_tsPDF : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public override void VerifyRenderingInServerForm(Control control) { //required to avoid the runtime error " //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server." } private void ExportGridToPDF() { try { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=Vithal_Wadje.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); //GridView1.RenderControl(hw); Table1.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); GridView1.AllowPaging = true; GridView1.DataBind(); } catch (Exception) { throw; } } protected void Button1_Click(object sender, EventArgs e) { ExportGridToPDF(); } }5.Now the whole code of tsPDF.aspx page will be as follows:
<body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> <asp:GridView ID="GridView1" runat="server"></asp:GridView> <asp:Table ID="Table1" runat="server"> <asp:TableRow> <asp:TableCell>Cell 1</asp:TableCell> <asp:TableCell>Cell 2</asp:TableCell> <asp:TableCell>Cell 3</asp:TableCell> <asp:TableCell>Cell 4</asp:TableCell> <asp:TableCell>Cell 5</asp:TableCell> <asp:TableCell>Cell 6</asp:TableCell> </asp:TableRow> </asp:Table> </div> </form> </body>
Reference website:
http://www.c-sharpcorner.com/UploadFile/0c1bb2/export-gridview-to-pdf/
http://www.cc.ntu.edu.tw/chinese/epaper/0015/20101220_1509.htm
沒有留言:
張貼留言