Wednesday 23 October 2013

C#/VB.NET:Save the generated pdf directly to the server directory folder without user prompt in ASP.NET

Hi friends, in this article I will explain about  Save the generated PDF directly to the server directory folder without user prompt in ASP.NET using C#/VB.NET.
In ASP.NET:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>C#/VB.NET:Save the generated pdf directly to the server directory folder without user prompt in ASP.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="Gv_Data" runat="server" AutoGenerateColumns ="false" >
        <Columns>
        <asp:TemplateField HeaderText ="ID">
        <ItemTemplate>
        <asp:Label ID="lblId" Text='<%#Eval("ID")%>' runat ="server">
        </asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
         <asp:TemplateField HeaderText ="FirstName">
        <ItemTemplate>
        <%# Eval("FirstName").ToString() == "Roja" ? "Yes" : "No"%>       
        </ItemTemplate>
        </asp:TemplateField>
         <asp:TemplateField HeaderText ="LastName">
        <ItemTemplate>
        <asp:Label ID="lblLname" Text='<%#Eval("lastname")%>' runat ="server">
        </asp:Label>
        </ItemTemplate>       
        </asp:TemplateField>
        <asp:TemplateField HeaderText ="Address">
        <ItemTemplate>
        <asp:Label ID="lblAddr" Text='<%#Eval("address")%>' runat ="server">
        </asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
        <asp:Button ID="btnPdf" runat="server" Text="Export To PDF" onclick="btnPdf_Click"
            style="height: 26px" />     
    </div>
    </form>
</body>
</html>

In C#:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.Net;
using System.Diagnostics;
public partial class ExportToPdf : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindData();

    }
    protected void BindData()
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand cmd = new SqlCommand("SELECT * FROM STUDENTS ORDER BY Firstname ASC", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        Gv_Data.DataSource = ds.Tables[0];
        Gv_Data.DataBind();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //With out this method,page will not run,raise an error
        // Verifies that the control is rendered
    }
    protected void btnPdf_Click(object sender, EventArgs e)
    {
        StringWriter str_w = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(str_w);
        Gv_Data.AllowPaging = false;
        Gv_Data.DataBind();
        Gv_Data.RenderControl(hw);  
        Document document = new Document();
        string FilePath = Server.MapPath("~") + "/PDF/" + "report_" + DateTime.Now.ToString("ddMMyyyy'_'HHmmss") + ".pdf".ToString();
        PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.Create));
        StringReader str_r = new StringReader(str_w.ToString());
        HTMLWorker obj = new HTMLWorker(document);
        document.Open();
        obj.Parse(str_r);
        document.Close();
        Response.Clear();
        Process.Start(FilePath);
    }
}

In VB.NET:
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Imports System.IO
Imports System.Net
Imports System.Diagnostics
Partial Public Class ExportToPdf
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        BindData()

    End Sub
    Protected Sub BindData()
        Dim con As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("con").ConnectionString)
        Dim cmd As New SqlCommand("SELECT * FROM STUDENTS ORDER BY Firstname ASC", con)
        Dim da As New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        da.Fill(ds)
        Gv_Data.DataSource = ds.Tables(0)
        Gv_Data.DataBind()
    End Sub
    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        'With out this method,page will not run,raise an error
        ' Verifies that the control is rendered
    End Sub
    Protected Sub btnPdf_Click(sender As Object, e As EventArgs)
        Dim str_w As New StringWriter()
        Dim hw As New HtmlTextWriter(str_w)
        Gv_Data.AllowPaging = False
        Gv_Data.DataBind()
        Gv_Data.RenderControl(hw)
        Dim document As New Document()
        Dim FilePath As String = Server.MapPath("~") + "/PDF/" + "report_" + DateTime.Now.ToString("ddMMyyyy'_'HHmmss") + ".pdf".ToString()
        PdfWriter.GetInstance(document, New FileStream(FilePath, FileMode.Create))
        Dim str_r As New StringReader(str_w.ToString())
        Dim obj As New HTMLWorker(document)
        document.Open()
        obj.Parse(str_r)
        document.Close()
        Response.Clear()
        Process.Start(FilePath)
    End Sub
End Class
If we run the above page then it will automatically save the file in your PDF folder of website. 

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.