How to convert ASP.Net ASPX Page to PDF file and save it on servers disk in ASP.Net

Last Reply on Oct 04, 2012 05:43 AM By Mudassar

Posted on Oct 04, 2012 02:46 AM

hi,

how i convert aspx page to pdf file with images. can u provide any link.

thanks.

Posted on Oct 04, 2012 05:43 AM Modified on on Dec 24, 2014 08:59 AM

HTML

<asp:Panel ID = "Panel1" runat="server">
<div>
    <img src="http://www.aspsnippets.com/images/Blue/Logo.png" /><br />
</div>
<div style="font-family: Arial">
    This is a test page</div>
<div>
    <table border="1" width="100">
        <tr>
            <td>
                Name
            </td>
            <td>
                Age
            </td>
        </tr>
        <tr>
            <td>
                John
            </td>
            <td>
                11
            </td>
        </tr>
        <tr>
            <td>
                Sam
            </td>
            <td>
                13
            </td>
        </tr>
        <tr>
            <td>
                Tony
            </td>
            <td>
                12
            </td>
        </tr>
    </table>
</div>
<div>
</asp:Panel>
<asp:Button ID="btnExport" runat="server" Text="Export" 
    onclick="btnExport_Click" /></div>

Namespaces

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

Code

protected void btnExport_Click(object sender, EventArgs e)
{
    FileStream file = new FileStream(Server.MapPath("~/Files/") + "Test.PDF", FileMode.Create, System.IO.FileAccess.Write);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    Panel1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    MemoryStream ms = new MemoryStream();
    PdfWriter.GetInstance(pdfDoc, file);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    file.Close();
}

public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}