Export HTML to PDF and save file to Folder (Directory) using C# in ASP.Net

Last Reply one month ago By pandeyism

Posted one month ago

I have 2 web pages need to convert into 2 separated pdf files.  Then combine 2 separated pdf files into 1 pdf file. Then save last 1 pdf file.

How can I implement these tasks?

Posted one month ago

Hi KatieNgoc,

Refer below sample.

HTML

Default.aspx

<asp:Panel ID="pnlDetails" runat="server">
    <asp:Image ID="imgPhoto" ImageUrl="~/E-Sign.png" runat="server" /><br />
    <p>
        1. Get A Discount On A New Walk In Tub</p>
    <br />
    <p>
        Walk in tubs are a perfect addition for seniors living with mobility challenges
        or anyone worried about fall related injuries. Statistics tell us that falls happen
        in your bathroom more than any other room in the home.</p>
    <br />
    <p>
        In fact two-thirds of all bathroom injuries happen near the shower or bath-tub,
        according to The Center for Disease Control. Most falls typically happen when your
        stepping over the tub, slipping on a wet floor or when leaning on a glass door that
        wasn't designed to support your weight</p>
    <br />
    <p>
        A Walk-in tub is an investment in your future a simple modification to your bathroom
        can change your life. Keeping your independence and dignity, plus peace of mind
        for your loved ones all ad up to a better quality of life. Right now, Walk-in tub
        manufacturers all over the country are offering big senior discounts. Visit the
        walk-in tub website to find discounts and get a free quote on a new Walk-in tub.</p>
</asp:Panel>
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />

 Default2.aspx

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
<asp:Button Text="Export" runat="server" OnClick="Export" />

 

 

Namespaces

C#

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

Code

C#

Default.aspx.cs

protected void btnExport_Click(object sender, EventArgs e)
{
    imgPhoto.ImageUrl = GetUrl("E-Sign.png");
    if (!Directory.Exists(Server.MapPath("~/Files/")))
    {
        Directory.CreateDirectory(Server.MapPath("~/Files/"));
    }
    FileStream file = new FileStream(Server.MapPath("~/Files/") + "" + pnlDetails.ID + ".PDF", FileMode.Create, System.IO.FileAccess.Write);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    pnlDetails.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    MemoryStream ms = new MemoryStream();
    PdfWriter.GetInstance(pdfDoc, file);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    file.Close();
    Response.Redirect("Default2.aspx");
}
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
protected string GetUrl(string imagepath)
{
    string[] splits = Request.Url.AbsoluteUri.Split('/');
    if (splits.Length >= 2)
    {
        string url = splits[0] + "//";
        for (int i = 2; i < splits.Length - 1; i++)
        {
            url += splits[i];
            url += "/";
        }
        return url + imagepath;
    }
    return imagepath;
}

Defauult2.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
protected void Export(object sender, EventArgs e)
{
    if (!Directory.Exists(Server.MapPath("~/Files/")))
    {
        Directory.CreateDirectory(Server.MapPath("~/Files/"));
    }
    FileStream file = new FileStream(Server.MapPath("~/Files/") + "" + GridView1.ID + ".PDF", FileMode.Create, System.IO.FileAccess.Write);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    MemoryStream ms = new MemoryStream();
    PdfWriter.GetInstance(pdfDoc, file);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    file.Close();
    MergingFile();
}
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
private void MergingFile()
{
    List<PdfReader> pdfReaderList = new List<PdfReader>();
    foreach (string filePath in Directory.GetFiles(Server.MapPath("~/Files")))
    {
        PdfReader pdfReader = new PdfReader(filePath);
        pdfReaderList.Add(pdfReader);
    }
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Buffer = true;
    Document document = new Document(PageSize.A4, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/Folder/") + "OutPut.pdf", FileMode.Create));
    document.Open();
    foreach (PdfReader reader in pdfReaderList)
    {
        for (int i = 1; i <= reader.NumberOfPages; i++)
        {
            PdfImportedPage page = writer.GetImportedPage(reader, i);
            document.Add(iTextSharp.text.Image.GetInstance(page));
        }
    }
    document.Close();
    Byte[] FileBuffer = File.ReadAllBytes(Server.MapPath("~/Folder/") + "OutPut.pdf");
    if (FileBuffer != null)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", FileBuffer.Length.ToString());
        Response.BinaryWrite(FileBuffer);
    }
}