Convert save Web Page to PDF in Folder (Directory) and Display in ASP.Net GridView using C# and VB.Net

Last Reply one month ago By pandeyism

Posted one month ago

Hello,

How to Convert the web pages to pdf files, save them in a folder in project solution, then display all converted pdf files in a gridview web control in C# asp.Net

 

Posted one month ago

Hi KatieNgoc,

Refer below sample code.

HTML

<asp:DropDownList ID="FormList" runat="server">
</asp:DropDownList>
<asp:Button ID="Redirect" runat="server" Text="Load  A Form" OnClick="Next_Click" />
<asp:Button ID="Button1" Text="Display" runat="server" OnClick="Download" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Text" HeaderText="File Name" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;
using System.Text;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;

VB.Net

Imports System.Data
Imports System.Text
Imports System.IO
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser

Code

CS.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        if (Session["ListItems"] == null)
        {
            DataTable dt = DropDownItems();
            FormList.DataSource = dt;
            FormList.DataTextField = "Text";
            FormList.DataValueField = "Value";
            FormList.DataBind();
            Session["ListItems"] = dt;
        }
        else
        {
            DataTable dt = (DataTable)Session["ListItems"];
            FormList.DataSource = dt;
            FormList.DataTextField = "Text";
            FormList.DataValueField = "Value";
            FormList.DataBind();
        }
    }
}

private DataTable DropDownItems()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Text");
    dt.Columns.Add("Value");
    dt.Rows.Add("Select one item, click on [Load a Form] button", "0");
    dt.Rows.Add("1.  W-4 IRS Form", "1");
    dt.Rows.Add("2.  Sexual Harassment Policy", "2");
    dt.Rows.Add("3.  Arbitration Agreement", "3");
    dt.Rows.Add("4.  Disciplinary & Attendance Policy", "4");
    dt.Rows.Add("5.  Paid Sick Leave", "5");
    dt.Rows.Add("6.  Authorization for Release of Information", "6");
    dt.Rows.Add("7.  General Code of Safe Practices", "7");
    dt.Rows.Add("8.  A Summary of Your Rights Under the Fair Credit Reporting Act", "8");
    dt.Rows.Add("9.  Meal Period Policy", "9");
    dt.Rows.Add("10. Meal Break Waiver Agreement", "10");
    dt.Rows.Add("11. Rest Period Policy", "11");
    dt.Rows.Add("12. Employee Safety Orientation Sign-Off Sheet", "12");
    dt.Rows.Add("13. Policy Statement Firearms, Weapons-Free Workplace", "13");
    dt.Rows.Add("14. Assignment Abandonment", "14");
    dt.Rows.Add("15. Remedying the Effects of Identity Theft", "15");
    dt.Rows.Add("16. Drug and Alcohol Policy", "16");
    dt.Rows.Add("17. General Safety Video", "17");
    return dt;
}

protected void Next_Click(object sender, EventArgs e)
{
    DataTable newDt = new DataTable();
    newDt.Columns.Add("Text");
    newDt.Columns.Add("Value");
    DataTable dt = (DataTable)Session["ListItems"];
    ListItemCollection liCol = FormList.Items;
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        ListItem li = liCol[i];
        if (li.Selected)
        {
            if (FormList.SelectedItem.Value == "1")
            {
                GetNewDt(newDt, dt, i, "Default.aspx");
            }
            else if (FormList.SelectedItem.Value == "2")
            {
                GetNewDt(newDt, dt, i, "Default.aspx");
            }
            else if (FormList.SelectedItem.Value == "3")
            {
                GetNewDt(newDt, dt, i, "Default.aspx");
            }
        }
    }
}

private void GetNewDt(DataTable newDt, DataTable dt, int i, string url)
{
    dt.Rows[i].Delete();
    newDt.Rows.Add(FormList.SelectedItem.Text, FormList.SelectedItem.Value);
    Session["newdt"] = newDt;
    Response.Redirect(url);
}
protected void Display(object sender, EventArgs e)
{
    string[] filePaths = Directory.GetFiles(Server.MapPath("~/File/"));
    List<System.Web.UI.WebControls.ListItem> files = new List<System.Web.UI.WebControls.ListItem>();
    foreach (string filePath in filePaths)
    {
        files.Add(new System.Web.UI.WebControls.ListItem(Path.GetFileName(filePath), filePath));
    }
    GridView1.DataSource = files;
    GridView1.DataBind();
}

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = Session["newdt"] as DataTable;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.Append("<p>");
            sb.Append(dt.Rows[i]["Text"] + "" + dt.Rows[i]["Value"]);
            sb.Append("</p>");
            File.WriteAllText(Server.MapPath("~/Filehtml/") + dt.Rows[i]["Value"] + ".htm", sb.ToString());
            using (StringWriter sw = new StringWriter(sb))
            {
                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {
                    using (StreamReader sr = new StreamReader(Server.MapPath("~/Filehtml/") + dt.Rows[i]["Value"] + ".htm"))
                    {
                        using (FileStream stream = new FileStream(Server.MapPath("~/File/") + "HTMLExport" + dt.Rows[i]["Value"] + ".pdf", FileMode.Create))
                        {
                            Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                            PdfWriter.GetInstance(pdfDoc, stream);
                            pdfDoc.Open();
                            htmlparser.Parse(sr);
                            pdfDoc.Close();
                            stream.Close();
                        }
                    }
                }
            }
        }
    }
}

VB.aspx.vb

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not Me.IsPostBack Then

            If Session("ListItems") Is Nothing Then
                Dim dt As DataTable = DropDownItems()
                FormList.DataSource = dt
                FormList.DataTextField = "Text"
                FormList.DataValueField = "Value"
                FormList.DataBind()
                Session("ListItems") = dt
            Else
                Dim dt As DataTable = CType(Session("ListItems"), DataTable)
                FormList.DataSource = dt
                FormList.DataTextField = "Text"
                FormList.DataValueField = "Value"
                FormList.DataBind()
            End If
        End If
    End Sub

    Private Function DropDownItems() As DataTable
        Dim dt As DataTable = New DataTable()
        dt.Columns.Add("Text")
        dt.Columns.Add("Value")
        dt.Rows.Add("Select one item, click on [Load a Form] button", "0")
        dt.Rows.Add("1.  W-4 IRS Form", "1")
        dt.Rows.Add("2.  Sexual Harassment Policy", "2")
        dt.Rows.Add("3.  Arbitration Agreement", "3")
        dt.Rows.Add("4.  Disciplinary & Attendance Policy", "4")
        dt.Rows.Add("5.  Paid Sick Leave", "5")
        dt.Rows.Add("6.  Authorization for Release of Information", "6")
        dt.Rows.Add("7.  General Code of Safe Practices", "7")
        dt.Rows.Add("8.  A Summary of Your Rights Under the Fair Credit Reporting Act", "8")
        dt.Rows.Add("9.  Meal Period Policy", "9")
        dt.Rows.Add("10. Meal Break Waiver Agreement", "10")
        dt.Rows.Add("11. Rest Period Policy", "11")
        dt.Rows.Add("12. Employee Safety Orientation Sign-Off Sheet", "12")
        dt.Rows.Add("13. Policy Statement Firearms, Weapons-Free Workplace", "13")
        dt.Rows.Add("14. Assignment Abandonment", "14")
        dt.Rows.Add("15. Remedying the Effects of Identity Theft", "15")
        dt.Rows.Add("16. Drug and Alcohol Policy", "16")
        dt.Rows.Add("17. General Safety Video", "17")
        Return dt
    End Function

    Protected Sub Next_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim newDt As DataTable = New DataTable()
        newDt.Columns.Add("Text")
        newDt.Columns.Add("Value")
        Dim dt As DataTable = CType(Session("ListItems"), DataTable)
        Dim liCol As ListItemCollection = FormList.Items

        For i As Integer = 0 To dt.Rows.Count - 1
            Dim li As ListItem = liCol(i)

            If li.Selected Then

                If FormList.SelectedItem.Value = "1" Then
                    GetNewDt(newDt, dt, i, "Default.aspx")
                ElseIf FormList.SelectedItem.Value = "2" Then
                    GetNewDt(newDt, dt, i, "Default.aspx")
                ElseIf FormList.SelectedItem.Value = "3" Then
                    GetNewDt(newDt, dt, i, "Default.aspx")
                End If
            End If
        Next
    End Sub

    Private Sub GetNewDt(ByVal newDt As DataTable, ByVal dt As DataTable, ByVal i As Integer, ByVal url As String)
        dt.Rows(i).Delete()
        newDt.Rows.Add(FormList.SelectedItem.Text, FormList.SelectedItem.Value)
        Session("newdt") = newDt
        Response.Redirect(url)
    End Sub

    Protected Sub Display(ByVal sender As Object, ByVal e As EventArgs)
        Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/File/"))
        Dim files As List(Of System.Web.UI.WebControls.ListItem) = New List(Of System.Web.UI.WebControls.ListItem)()

        For Each filePath As String In filePaths
            files.Add(New System.Web.UI.WebControls.ListItem(Path.GetFileName(filePath), filePath))
        Next

        GridView1.DataSource = files
        GridView1.DataBind()
    End Sub

Default.aspx.vb

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Me.IsPostBack Then
        Dim dt As DataTable = TryCast(Session("newdt"), DataTable)
        Dim sb As StringBuilder = New StringBuilder()

        For i As Integer = 0 To dt.Rows.Count - 1
            sb.Append("<p>")
            sb.Append(dt.Rows(i)("Text") & "" + dt.Rows(i)("Value"))
            sb.Append("</p>")
            File.WriteAllText(Server.MapPath("~/Filehtml/") + dt.Rows(i)("Value") & ".htm", sb.ToString())

            Using sw As StringWriter = New StringWriter(sb)

                Using hw As HtmlTextWriter = New HtmlTextWriter(sw)

                    Using sr As StreamReader = New StreamReader(Server.MapPath("~/Filehtml/") + dt.Rows(i)("Value") & ".htm")

                        Using stream As FileStream = New FileStream(Server.MapPath("~/File/") & "HTMLExport" + dt.Rows(i)("Value") & ".pdf", FileMode.Create)
                            Dim pdfDoc As Document = New Document(PageSize.A2, 10F, 10F, 10F, 0F)
                            Dim htmlparser As HTMLWorker = New HTMLWorker(pdfDoc)
                            PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
                            PdfWriter.GetInstance(pdfDoc, stream)
                            pdfDoc.Open()
                            htmlparser.Parse(sr)
                            pdfDoc.Close()
                            stream.Close()
                        End Using
                    End Using
                End Using
            End Using
        Next
    End If
End Sub