Reader Level:
Article

Convert Aspx Page Into PDF in ASP.NET

By Neha Sharma on Apr 08, 2013
This article is about to export an aspx page into Pdf file.

Introduction

This article explains how to export an aspx page to a PDF file.

Requirement

The only requirement is to add the DLL of "ITextSharp" to the application.

Code

In the code behind add the following namespaces:

using iTextSharp.text;

using iTextSharp.text.pdf;
using
iTextSharp.text.html;
using
iTextSharp.text.html.simpleparser;
using
System.Drawing;

Design a page.

Place the following code on the button click event to convert the aspx page into PDF:

protected void Button1_Click(object sender, EventArgs e)

{
       
string attachment = "attachment; filename=" + "abc" + ".pdf";
        Response.ClearContent();

        Response.AddHeader(
"content-disposition", attachment);
        Response.ContentType =
"application/pdf";
       
StringWriter s_tw = new StringWriter();
       
HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
        h_textw.AddStyleAttribute(
"font-size", "7pt");
        h_textw.AddStyleAttribute(
"color", "Black");
        Panel1.RenderControl(h_textw);
//Name of the Panel
       
Document doc = new Document();
        doc =
new Document(PageSize.A4, 5, 5, 15, 5);
       
FontFactory.GetFont("Verdana", 80, iTextSharp.text.Color.RED);
       
PdfWriter.GetInstance(doc, Response.OutputStream);
        doc.Open();

       
StringReader s_tr = new StringReader(s_tw.ToString());
       
HTMLWorker html_worker = new HTMLWorker(doc);
        html_worker.Parse(s_tr);

        doc.Close();
        Response.Write(doc);

   }

public override void VerifyRenderingInServerForm(Control control)

{
}

Save all and run; an error will occur as in the following image:

asp-net.jpg

This error occurs when we render a control into a response. Use the following point to resolve this error:

Add  EnableEventValidation="false" in the page directive on the source of your page at the top.

Now save all and view the page in the browser; when you click on the button to convert the apx page into a PDF it will work.

Article Extensions
Contents added by rupesh rai on Jun 27, 2013
Design Code

<%@ Page Title="Convert HTML to Image" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="HtmlToJpg.aspx.cs" Inherits="HtmlToJpg" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <form id="form1" runat="server">
        <table>
            <tr>
                <td>
                    <!-- Header -->
                </td>
            </tr>
            <tr>
                <td>
                    <!-- Body -->
                    <table cellpadding="0" cellspacing="0">
                        <tr>
                            <td>
                            </td>
                        </tr>
                        <tr>
                            <td style="height: 20px"></td>
                        </tr>
                        <tr>
                            <td>
                                <table cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td>
                                            <asp:RadioButton ID="radioButtonConvertUrl" Visible="false" GroupName="UrlOrHtmlCode" runat="server"
                                                Text="Convert URL" Checked="True" OnCheckedChanged="radioButtonConvertUrl_CheckedChanged"
                                                AutoPostBack="True" Font-Bold="True" />
                                        </td>
                                        <td style="width: 50px"></td>
                                        <td>
                                            <asp:RadioButton ID="radioButtonConvertHtmlCode" Visible="false" GroupName="UrlOrHtmlCode" runat="server"
                                                Text="Convert HTML Code" OnCheckedChanged="radioButtonConvertHtmlCode_CheckedChanged"
                                                AutoPostBack="True" Font-Bold="True" />
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td style="height: 20px"></td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Panel ID="panelUrl" runat="server">
                                    <table cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td style="padding-bottom: 5px">URL
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <asp:TextBox ID="textBoxUrl" runat="server" Text="http://www.google.com" Width="590px"></asp:TextBox>
                                            </td>
                                        </tr>
                                    </table>
                                </asp:Panel>
                                <asp:Panel ID="panelHtmlCode" runat="server" Visible="false">
                                    <table cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td>HTML
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <asp:TextBox ID="textBoxHtmlCode" runat="server" TextMode="MultiLine" Height="200px"
                                                    Width="590px">&lt;/br&gt;
&lt;/br&gt;
Please enter the HTML code to convert and the base URL to access the external images, scripts and css having relative URLs in the HTML code to convert.
                                                </asp:TextBox>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td style="height: 10px"></td>
                                        </tr>
                                        <tr>
                                            <td>Base URL
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <asp:TextBox ID="textBoxBaseUrl" runat="server" Text="" Width="590px"></asp:TextBox>
                                            </td>
                                        </tr>
                                    </table>
                                </asp:Panel>
                            </td>
                        </tr>
                        <tr>
                            <td style="height: 20px"></td>
                        </tr>
                        <tr>
                            <td style="font-weight: bold">Settings
                            </td>
                        </tr>
                        <tr>
                            <td style="height: 20px"></td>
                        </tr>
                        <tr>
                            <td>
                                <table cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td style="width: 96px">Image Format:
                                        </td>
                                        <td style="width: 8px"></td>
                                        <td style="width: 103px">
                                            <asp:DropDownList ID="dropDownListImageFormat" runat="server" AutoPostBack="True"
                                                OnSelectedIndexChanged="dropDownListImageFormat_SelectedIndexChanged">
                                                <asp:ListItem>PNG</asp:ListItem>
                                                <asp:ListItem>JPG</asp:ListItem>
                                                <asp:ListItem>BMP</asp:ListItem>
                                            </asp:DropDownList>
                                        </td>
                                        <td style="width: 7px"></td>
                                        <td style="height: 30px">
                                            <asp:CheckBox ID="checkBoxTransparentImage" Visible="false" runat="server" Text="Create Transparent Background (PNG only)"
                                                Checked="True" />
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td style="height: 10px"></td>
                        </tr>
                        <tr>
                            <td>
                                <table cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td>Browser Width:
                                        </td>
                                        <td style="width: 5px"></td>
                                        <td>
                                            <asp:TextBox ID="textBoxBrowserWidth" runat="server" Text="1200" Width="35px">1200</asp:TextBox>
                                        </td>
                                        <td style="width: 5px"></td>
                                        <td>px
                                        </td>
                                        <td style="width: 60px"></td>
                                        <td><%--Load HTML Timeout:--%>
                                        </td>
                                        <td style="width: 5px"></td>
                                        <td>
                                            <asp:TextBox ID="textBoxLoadHtmlTimeout" Visible="false" runat="server" Text="120" Width="30px">120</asp:TextBox>
                                        </td>
                                        <td style="width: 5px"></td>
                                        <td><%--sec--%>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td style="height: 10px"></td>
                        </tr>
                        <tr>
                            <td>
                                <table cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td style="height: 30px; font-weight: normal"><%--Triggering Mode:--%>
                                        </td>
                                        <td style="width: 5px; height: 30px;"></td>
                                        <td style="height: 30px;">
                                            <asp:DropDownList ID="dropDownListTriggeringMode" runat="server" AutoPostBack="True"
                                                OnSelectedIndexChanged="dropDownListTriggeringMode_SelectedIndexChanged" Visible="false">
                                                <asp:ListItem>Auto</asp:ListItem>
                                                <asp:ListItem>Manual</asp:ListItem>
                                                <asp:ListItem>WaitTime</asp:ListItem>
                                            </asp:DropDownList>
                                        </td>
                                        <td style="width: 28px; height: 30px;"></td>
                                        <td style="height: 30px">
                                            <asp:Panel ID="panelWaitTime" runat="server">
                                                <table cellpadding="0" cellspacing="0">
                                                    <tr>
                                                        <td><%--Wait Time:--%>
                                                        </td>
                                                        <td style="width: 5px"></td>
                                                        <td>
                                                            <asp:TextBox ID="textBoxWaitTime" runat="server" Text="2" Visible="false" Width="30px">2</asp:TextBox>
                                                        </td>
                                                        <td style="width: 5px"></td>
                                                        <td><%--sec--%>
                                                        </td>
                                                    </tr>
                                                </table>
                                            </asp:Panel>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td ></td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Button ID="buttonConvertToImage" runat="server" Text="Convert to Image" OnClick="buttonConvertToImage_Click" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                    <!-- Footer -->
                </td>
            </tr>
        </table>
    </form>
</asp:Content>



Source Code

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Threading;
using System.Net;
using HiQPdf;
public partial class HtmlToJpg : System.Web.UI.Page
{
    //protected void Page_Load(object sender, EventArgs e)
    //{

    //    //GetWebHtmlSourceCode("https://www.google.co.in/");
    //    saveURLToImage("http://www.google.com");

    //}

    public static string GetWebHtmlSourceCode(string url)
    {
        string content = "";
        StreamReader objStreamReader = default(StreamReader);
        WebRequest objWebRequest = default(WebRequest);
        WebResponse objWebResponse = default(WebResponse);
        try
        {
            objWebRequest = WebRequest.Create(url);
            objWebResponse = objWebRequest.GetResponse();
            objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
            content = objStreamReader.ReadToEnd();
            objStreamReader.Close();
            byte[] b = Convert.FromBase64String(content);
            System.IO.MemoryStream ms = new System.IO.MemoryStream(b);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            string FilePath = HttpContext.Current.Server.MapPath("Large/") + "image.jpg";
            img.Save(FilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch
        {
            return content;
        }
        return content;
    }

    private void saveURLToImage(string url)
    {
        if (!string.IsNullOrEmpty(url))
        {
            string content = "";

            System.Net.WebRequest webRequest = WebRequest.Create(url);
            System.Net.WebResponse webResponse = webRequest.GetResponse();
            System.IO.StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
            content = sr.ReadToEnd();
            //save to file
            byte[] b = Convert.FromBase64String(content);
            System.IO.MemoryStream ms = new System.IO.MemoryStream(b);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            img.Save(@"d:\pic.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            img.Dispose();
            ms.Close();
        }
    }


    //private const int TIMEOUT = 30000;
    //private const string TMP_NAME = "TMP_SHOT.png";

    //private void Shot(string url, string rootDir)
    //{
    //    try
    //    {

    //        string arguments = url + " " + rootDir + "\\" + TMP_NAME;

    //        Process p = Process.Start(rootDir + "\\" + EXTRACTIMAGE_EXE, arguments);
    //        p.WaitForExit(TIMEOUT);
    //        if (!p.HasExited)
    //        {
    //            p.Kill();
    //            throw new Exception("Timed out while creating the thumbnail.");
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        Trace.WriteLine(ex.ToString());
    //        throw ex;
    //    }
    //}

    //public string GetImage(string url, string name, string rootDir,
    //int width, int height)
    //{

    //    try
    //    {
    //        string fileName = rootDir + "\\" + TMP_NAME;

    //        Shot(url, rootDir);


    //        System.Drawing.Image thumbImage =
    //            System.Drawing.Image.FromFile(fileName);

    //        Scale(thumbImage, width, height);

    //        System.Drawing.Image scaledImg = Scale(thumbImage, width, height);

    //        fileName = rootDir + "\\" + name + ".png";
    //        if (File.Exists(fileName))
    //            File.Delete(fileName);

    //        scaledImg.Save(fileName, ImageFormat.Png);

    //        return name + ".png";

    //    }
    //    catch (Exception ex)
    //    {
    //        //Trace.WriteLine(ex.ToString());
    //        return null;
    //    }
    //}

    //protected void btnShot_Click(object sender, EventArgs e)
    //{
    //    ScreenshotHelper ssh = new ScreenshotHelper();
    //    string imagePath = ssh.GetImage(txtUrl.Text, "MyImage",
    //                  Server.MapPath("~"),
    //                  Convert.ToInt32(txtWidth.Text),
    //                  Convert.ToInt32(txtHeight.Text)
    //                );

    //    theImage.ImageUrl = imagePath;

    //}


    protected void buttonConvertToImage_Click(object sender, EventArgs e)
    {
        // create the HTML to Image converter
        HtmlToImage htmlToImageConverter = new HtmlToImage();

        // set a demo serial number
        htmlToImageConverter.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

        // set browser width
        htmlToImageConverter.BrowserWidth = int.Parse(textBoxBrowserWidth.Text);

        // set HTML Load timeout
        htmlToImageConverter.HtmlLoadedTimeout = int.Parse(textBoxLoadHtmlTimeout.Text);

        // set whether the resulted image is transparent (has effect only when the output format is PNG)
        htmlToImageConverter.TransparentImage = (dropDownListImageFormat.SelectedValue == "PNG") ? checkBoxTransparentImage.Checked : false;

        // set triggering mode; for WaitTime mode set the wait time before convert
        switch (dropDownListTriggeringMode.SelectedValue)
        {
            case "Auto":
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;
            case "WaitTime":
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.WaitTime;
                htmlToImageConverter.WaitBeforeConvert = int.Parse(textBoxWaitTime.Text);
                break;
            case "Manual":
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Manual;
                break;
            default:
                htmlToImageConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;
        }

        // convert to image
        System.Drawing.Image imageObject = null;
        string imageFormatName = dropDownListImageFormat.SelectedValue.ToLower();
        string imageFileName = String.Format("HtmlToImage.{0}", imageFormatName);

        if (radioButtonConvertUrl.Checked)
        {
            // convert URL
            string url = textBoxUrl.Text;

            imageObject = htmlToImageConverter.ConvertUrlToImage(url)[0];
        }
        else
        {
            // convert HTML code
            string htmlCode = textBoxHtmlCode.Text;
            string baseUrl = textBoxBaseUrl.Text;

            imageObject = htmlToImageConverter.ConvertHtmlToImage(htmlCode, baseUrl)[0];
        }

        // get the image buffer in the selected image format
        byte[] imageBuffer = GetImageBuffer(imageObject);

        // the image object rturned by converter can be disposed
        imageObject.Dispose();

        // inform the browser about the binary data format
        string mimeType = imageFormatName == "jpg" ? "jpeg" : imageFormatName;
        HttpContext.Current.Response.AddHeader("Content-Type", "image/" + mimeType);

        // let the browser know how to open the image and the image name
        HttpContext.Current.Response.AddHeader("Content-Disposition",
                    String.Format("attachment; filename={0}; size={1}", imageFileName, imageBuffer.Length.ToString()));

        // write the image buffer to HTTP response
        HttpContext.Current.Response.BinaryWrite(imageBuffer);

        // call End() method of HTTP response to stop ASP.NET page processing
        HttpContext.Current.Response.End();
    }

    private byte[] GetImageBuffer(System.Drawing.Image imageObject)
    {
        // create a memory stream where to save the image
        System.IO.MemoryStream imageMemoryStream = new System.IO.MemoryStream();

        // save the image to memory stream
        imageObject.Save(imageMemoryStream, GetSelectedImageFormat());

        // get a copy of the image buffer to allow image disposing
        byte[] imageBuffer = new byte[imageMemoryStream.Length];
        Array.Copy(imageMemoryStream.GetBuffer(), imageBuffer, imageBuffer.Length);

        // close the memory stream
        imageMemoryStream.Close();

        return imageBuffer;
    }

    private System.Drawing.Imaging.ImageFormat GetSelectedImageFormat()
    {
        switch (dropDownListImageFormat.SelectedValue)
        {
            case "PNG":
                return System.Drawing.Imaging.ImageFormat.Png;
            case "JPG":
                return System.Drawing.Imaging.ImageFormat.Jpeg;
            case "BMP":
                return System.Drawing.Imaging.ImageFormat.Bmp;
            default:
                return System.Drawing.Imaging.ImageFormat.Png;
        }
    }

    protected void dropDownListImageFormat_SelectedIndexChanged(object sender, EventArgs e)
    {
        checkBoxTransparentImage.Visible = dropDownListImageFormat.SelectedValue == "PNG";
    }

    protected void radioButtonConvertUrl_CheckedChanged(object sender, EventArgs e)
    {
        panelUrl.Visible = radioButtonConvertUrl.Checked;
        panelHtmlCode.Visible = !radioButtonConvertUrl.Checked;
    }

    protected void radioButtonConvertHtmlCode_CheckedChanged(object sender, EventArgs e)
    {
        panelUrl.Visible = !radioButtonConvertHtmlCode.Checked;
        panelHtmlCode.Visible = radioButtonConvertHtmlCode.Checked;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            dropDownListImageFormat.SelectedValue = "PNG";
            //checkBoxTransparentImage.Visible = true;

            panelUrl.Visible = radioButtonConvertUrl.Checked;
            panelHtmlCode.Visible = !radioButtonConvertUrl.Checked;

            dropDownListTriggeringMode.SelectedValue = "WaitTime";
            //panelWaitTime.Visible = true;

            //Master.SelectNode("htmlToImage");
        }
    }

    protected void dropDownListTriggeringMode_SelectedIndexChanged(object sender, EventArgs e)
    {
        panelWaitTime.Visible = dropDownListTriggeringMode.SelectedValue == "WaitTime";
    }
}


Contents added by Rashid Khan on May 20, 2013
HI Neha.
I just add a line in this code.
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, s_tr);
        // html_worker.Parse(s_tr);
and use this code in my 1 page where i have list. it gives result fine.
but on invoice page both codes are not working



This is my invoice. i want pdf file same. in this page i have used. labels, asp repeater, above shown page is placed in panel.
or if crystal report is better option then how can i make pdf ?
Need badly.
waiting for your soonest reply. 

COMMENT USING