Convert Web Page to PDF and download as Zip file using C# in ASP.Net

Last Reply one month ago By pandeyism

Posted one month ago

Hello,

How to implement as below:

In a drop down list box has 17 list items, after I select 1 item in the list, click on [Load a form] button, it shows text info after redirect to other webpage

After click [Load a Form] button, it will eleminated itsef AND convert after redirect its page from the web browser into html format file.

Convert its html file into PDF file.

Put 17 list items (PDF file) save in a zip foder.

You are viewing reply posted by: pandeyism one month ago.
Posted one month ago

Hi KatieNgoc,

Refer below sample code.

HTML

CS.aspx

<div>
    <h50 style="float: left"><font color="black" size="5"><b>DASHBOARD</b></font></h50>
    <br />
    <br />
    <table id="Table1" runat="server" style="float: left">
        <tr>
            <td>
                <img src="Images/FeedBack.jpg" />
            </td>
            <td>
                <a href="LiveChat.aspx">
                    <h51 style="float: left"><font color="green" size="4"><b>Live Chat</b></font></h51>
            </td>
        </tr>
        <tr>
            <td>
                <img src="Images/icon2.jpg" />
            </td>
            <td>
                <a href="Disagree.aspx">
                    <h51 style="float: left"><font color="blue" size="4"><b>Feed Back</b></font></h51>
                </a>
            </td>
        </tr>
        <tr>
            <td>
                <img src="Images/logout.jpg" />
            </td>
            <td>
                <a href="Default.aspx">
                    <h51 style="float: left"><font color="navy" size="4"><b>LogOut</b></font></h51>
                </a>
            </td>
        </tr>
    </table>
    <br />
    <br />
    <br />
    <center>
        <asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="Blue" Font-Size="Medium"></asp:Label>
        <br />
        <br />
        <br />
        <h1>
            <font color="black"><b>FORMS</b></font></h1>
        <hr />
        <br />
        <table>
            <tr>
                <td>
                    <img src="/Images/icon.jpg" />
                </td>
                <td>
                    <h5>
                        You have completed 75% the progress of the online employment application systems.
                    </h5>
                </td>
            </tr>
        </table>
    </center>
    <br />
    <br />
    <div class="container">
        <div class="progress">
            <div class="progress-bar progress-bar-striped
                progress-bar-animated" style="width: 75%;">
                75%</div>
        </div>
        <br>
        <br />
        <center>
            <table>
                <tr>
                    <td>
                        <img src="/Images/icon.jpg" />
                    </td>
                    <td>
                        <h4>
                            <font color="white">Note:&nbsp; At the bottom of each form, it will be displayed your
                                digital signature image came from your job application form.</font></h4>
                    </td>
                </tr>
            </table>
            <br />
            <br />
            <h4>
                <font color="black">Select a form, read and click on [I agree] check box (if you agree
                    so) for all required employment forms as below:</font></h4>
            <p>
                &nbsp;</p>
            <br />
            <br />
            <asp:DropDownList ID="FormList" runat="server" Font-Bold="True" Font-Names="Arial Black"
                Font-Size="Medium" ForeColor="Maroon">
            </asp:DropDownList>
            <br />
            <br />
            <br />
            <asp:Button ID="HRForm" runat="server" CssClass="Button" Font-Size="Medium" ForeColor="Blue"
                Text="Load  A Form" OnClick="Button4_Click" Font-Bold="True" />
            <br />
            <hr />
            <table>
                <tr>
                    <td>
                        <img src="/Images/icon.jpg" />
                    </td>
                    <td>
                        <h4>
                            <font color="#542906">After finished to read all required forms as the list as the above,
                                please click on [Watch Video] button to complete the last step of the online employment
                                application systems.</font></h4>
                        </p>
                    </td>
                    <br />
                </tr>
            </table>
            <br />
            <br />
            <br />
            <asp:Button ID="Add" CssClass="Button" Font-Size="Medium" runat="server" ForeColor="Blue"
                Text="Add To Templus" OnClick="Button1_Click" Font-Bold="True" />
            <asp:Button ID="WatchVideo" CssClass="Button" Font-Size="Medium" runat="server" ForeColor="Blue"
                Text="Watch Video" OnClick="Next_Click" Font-Bold="True" />
            <br />
            <br />
            <br />
            <br />
        </center>
    </div>
</div>

CreateW4Form.aspx

<asp:Button Text="Download" runat="server"  OnClick="Download"/>

Namespaces

C#

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

Code

C#

CS.aspx.cs

public string sqlConfigConnString1;
public string sqlStatement1;
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        if (Session["userEmail"] != null)
        {
            Label1.Text = "Hello, " + Session["userEmail"].ToString().Trim();
        }
        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();
        }
        FormList.Attributes.Add("size", "18");
        FormList.Attributes.Add("Style", "color:blue");
    }
}

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 Button1_Click(object sender, EventArgs e)
{
    sqlConfigConnString1 = ConfigurationManager.ConnectionStrings["Citistaff"].ConnectionString;
    SqlConnection appConnect = new SqlConnection(sqlConfigConnString1);
    appConnect.ConnectionString = appConnect.ConnectionString;
    try
    {
        sqlStatement1 = "INSERT INTO ApplicantJobApplication (OnboardingUniqueId, TempsPlusID, ApplicantLName, ApplicantMName, ApplicantFName) SELECT A.TempPlusKey, A.TempPlusID, A.ApplicantLastName, A.ApplicantMName, A.ApplicantFirstName FROM ApllicantInfoK A WHERE A.Emailsession = '" + Session["userEmail"].ToString().Trim() + "'";
        sqlStatement1 += "SELECT A.TempPlusKey, A.TempPlusID, A.ApplicantLastName, A.ApplicantMName, A.ApplicantFirstName ";
        sqlStatement1 += "FROM ApllicantInfoK A WHERE A.Emailsession = '" + Session["userEmail"].ToString().Trim() + "'";
        if (appConnect.State == ConnectionState.Closed)
        {
            appConnect.OpenConnection();
            appConnect.ExecuteQuery(sqlStatement1);
            appConnect.DataAdapterConnection();
        }
    }
    catch (SqlException ex)
    {
        ShowMessage(ex.Message);
    }
    finally
    {
        if (appConnect.Conn.State == ConnectionState.Open)
            appConnect.CloseAll();
    }
    string message = "Your partial profile have been successfully added.";
    string url = "/W4.aspx";
    string script = "{ alert('";
    script += message;
    script += "');";
    script += "window.location = '";
    script += url;
    script += "'; }";
    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "alert", script, true);
    Response.Redirect("Videoscreen.aspx");
}

public void ShowMessage(string msg)
{
    System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}

protected void Button4_Click(object sender, EventArgs e)
{
    DataTable dt = Session["ListItems"] as DataTable;
    ListItemCollection liCol = FormList.Items;
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        ListItem li = liCol[i];
        if (li.Selected)
        {
            li.Text = FormList.SelectedItem.Value;
            li.Value = FormList.SelectedItem.Text;

            if (FormList.SelectedItem.Value == "1")
            {
                dt.Rows[i].Delete();
                Response.Redirect("CreateW4Form.aspx");
            }
            else if (FormList.SelectedItem.Value == "2")
            {
                dt.Rows[i].Delete();
                Response.Redirect("SexualHarassment.aspx");
            }
            else if (FormList.SelectedItem.Value == "3")
            {
                dt.Rows[i].Delete();
                Response.Redirect("ArbitrationAgreement.aspx");
            }
            else if (FormList.SelectedItem.Value == "4")
            {
                dt.Rows[i].Delete();
                Response.Redirect("DisciplineAttendancePolicy.aspx");
            }
            else if (FormList.SelectedItem.Value == "5")
            {
                dt.Rows[i].Delete();
                Response.Redirect("PaidSickLeave.aspx");
            }
            else if (FormList.SelectedItem.Value == "6")
            {
                dt.Rows[i].Delete();
                Response.Redirect("AuthorizationforReleaseofInformation.aspx");

            }
            else if (FormList.SelectedItem.Value == "7")
            {
                dt.Rows[i].Delete();
                Response.Redirect("GeneralCodeofSafePractices.aspx");
            }
            else if (FormList.SelectedItem.Value == "8")
            {
                dt.Rows[i].Delete();
                Response.Redirect("RightsUndertheFairCreditReportingAct.aspx");
            }
            else if (FormList.SelectedItem.Value == "9")
            {
                dt.Rows[i].Delete();
                Response.Redirect("MealPeriodPolicy.aspx");
            }
            else if (FormList.SelectedItem.Value == "10")
            {
                dt.Rows[i].Delete();
                Response.Redirect("MealBreakWaiverAgreement.aspx");
            }
            else if (FormList.SelectedItem.Value == "11")
            {
                dt.Rows[i].Delete();
                Response.Redirect("RestPeriodPolicy.aspx");
            }
            else if (FormList.SelectedItem.Value == "12")
            {
                dt.Rows[i].Delete();
                Response.Redirect("EmployeesafetyOrientationSignOffSheet.aspx");
            }
            else if (FormList.SelectedItem.Value == "13")
            {
                dt.Rows[i].Delete();
                Response.Redirect("PolicyStatementFirearmsWeaponsFreeWorkplace.aspx");
            }
            else if (FormList.SelectedItem.Value == "14")
            {
                dt.Rows[i].Delete();
                Response.Redirect("AssignmentAbandonment.aspx");
            }
            else if (FormList.SelectedItem.Value == "15")
            {
                dt.Rows[i].Delete();
                Response.Redirect("RemedyingtheEffectsofIdentityTheft.aspx");
            }
            else if (FormList.SelectedItem.Value == "16")
            {
                dt.Rows[i].Delete();
                Response.Redirect("DrugAlcohol.aspx");
            }
            else if (FormList.SelectedItem.Value == "17")
            {
                dt.Rows[i].Delete();
                Response.Redirect("GeneralSafetyVideo.aspx");
            }
        }
    }
}

protected void Next_Click(object sender, EventArgs e)
{
    Response.Redirect("Videoscreen.aspx");
}

CreateW4Form.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = Session["ListItems"] 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();
                    }
                }
            }
        }
    }
}

protected void Download(object sender, EventArgs e)
{
    int i = 0;
    using (ZipFile zip = new ZipFile())
    {
        zip.AlternateEncodingUsage = ZipOption.AsNecessary;
        zip.AddDirectoryByName("Files");
        foreach (var filePath in Directory.GetFiles(Server.MapPath("~/File")))
        {
            i = i + 1;
            zip.AddFile(filePath, "Files");
        }
        Response.Clear();
        Response.BufferOutput = false;
        string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
        zip.Save(Response.OutputStream);
        Response.End();
    }
}