Friday 22 August 2014

How to create PDF document in ASP.NET with C#/VB.NET using iTextSharp

Hi friends,in this article I will explain about How to create PDF document in ASP.NET with C#/VB.NET using iTextSharp.
What is iTextSharp:
iTextSharpopen source Java library for PDF generation and manipulation. It can be used to create PDF documents from scratch, to convert XML to PDF (using the extra XFA Worker DLL), to fill out interactive PDF forms, to stamp new content on existing PDF documents, to split and merge existing PDF documents, and much more.
          Here I’m going to explain how to create PDF document in ASP.NET using iTextSharp. First we have to download iTextSharp.dll class library and include to our project.  
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to create PDF document in ASP.NET with C#/VB.NET using iTextSharp</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h4 style="color: Green">
            How to create PDF document in ASP.NET with C#/VB.NET using iTextSharp</h4>
    </div>
    <div>
        <br />
        <asp:GridView ID="gvDetails" AutoGenerateColumns="false" runat="server" Font-Names="Tahoma"
            Font-Size="13px" Width="350px">
            <Columns>
                <asp:BoundField HeaderText="EMP ID" DataField="Emp ID" />
                <asp:BoundField HeaderText="Emp Name" DataField="Emp Name" />
            </Columns>
            <AlternatingRowStyle BackColor="#E6E6E1" />
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        </asp:GridView>
    </div>
    <div>
        <br />
        <asp:Button ID="btnPDF" runat="server" Text="Export to PDF" OnClick="btnPDF_Click"
            Style="border-style: none; padding: 2px 5px; font-weight: bold; font-size: 11px;
            color: #FFFFFF; font-family: Tahoma, Arial; background-color: #990000; background-repeat: repeat-x;" />
    </div>
    </form>
</body>
</html>

In C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.Data;

public partial class iTextSharpExample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindData();
    }

    protected void BindData()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("EMP ID"), new DataColumn("EMP Name") });
        dt.Rows.Add("1", "Kishore");
        dt.Rows.Add("2", "Venkat");
        dt.Rows.Add("3", "Satyam");
        dt.Rows.Add("4", "Raghava");
        dt.Rows.Add("5", "Nag");
        dt.Rows.Add("6", "Krishna");
        dt.Rows.Add("7", "Purna Anil");
        dt.Rows.Add("8", "Sowji");
        dt.Rows.Add("9", "Abhi");
        dt.Rows.Add("10", "Sreenu");
        dt.Rows.Add("11", "Ashok");
        dt.Rows.Add("12", "Sathish");
        dt.Rows.Add("13", "Purna");
        gvDetails.DataSource = dt;
        gvDetails.DataBind();

    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    protected void btnPDF_Click(object sender, EventArgs e)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        this.Page.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString().Replace("\r", "").Replace("\n", "").Replace("  ", ""));
        // StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0.0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
}

IN VB.NET:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Imports System.IO
Imports System.Data

Partial Public Class iTextSharpExample
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            BindData()
        End If
    End Sub

    Protected Sub BindData()
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(1) {New DataColumn("EMP ID"), New DataColumn("EMP Name")})
        dt.Rows.Add("1", "Kishore")
        dt.Rows.Add("2", "Venkat")
        dt.Rows.Add("3", "Satyam")
        dt.Rows.Add("4", "Raghava")
        dt.Rows.Add("5", "Nag")
        dt.Rows.Add("6", "Krishna")
        dt.Rows.Add("7", "Purna Anil")
        dt.Rows.Add("8", "Sowji")
        dt.Rows.Add("9", "Abhi")
        dt.Rows.Add("10", "Sreenu")
        dt.Rows.Add("11", "Ashok")
        dt.Rows.Add("12", "Sathish")
        dt.Rows.Add("13", "Purna")
        gvDetails.DataSource = dt
        gvDetails.DataBind()

    End Sub
    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    End Sub
    Protected Sub btnPDF_Click(sender As Object, e As EventArgs)
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf")
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
        Me.Page.RenderControl(hw)
        Dim sr As New StringReader(sw.ToString().Replace(vbCr, "").Replace(vbLf, "").Replace("  ", ""))
        ' StringReader sr = new StringReader(sw.ToString());
        Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
        Dim htmlparser As New HTMLWorker(pdfDoc)
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
        pdfDoc.Open()
        htmlparser.Parse(sr)
        pdfDoc.Close()
        Response.Write(pdfDoc)
        Response.[End]()
    End Sub
End Class

If you get RegisterForEventValidation can only be called during Render();To solve this problem I have added EnableEventValidation="false" to @Page directive of aspx page.

The output of the above code as shown in the below figure.

After generating PDF document.The PDF document will be shown as below.

No comments:

Post a Comment

© 2012-2018 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.