google-site-verification=ECX1M6_Vb39ty4VtQDXQce6wOjmPTxSettd3hTIZb9Q

How to export web page as PDF with Image? - itextsharp

random

How to export web page as PDF with Image? - itextsharp

C# - How to export webpage with images to PDF in asp.net using iTextSharp


But sometimes we have a scenario to export data/reports from webpage to PDF. In this article I will explain how to export web page as PDF with Image in ASP .Net, C#. Find the source code below:-

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" EnableEventValidation="false"
    Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Export WebPage As PDF With Image Sample</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" runat="server" ImageUrl="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpTZ8H6wlWhadQTB5RWS8ktChAI_nGLj86NMFIecjKYzDjFmVCHAyYDW4UA5CiSs_Nek8dEokpqc8whOs8ITdT8gL0Ji6wbALJMvQIACkbwfmdbpwoZtF5ewdQdy_N_gGpkqGj8BrPhjaG/s1600/etechpulse_logo.png" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <br />
        <asp:Button ID="btnExportasPDF" runat="server" Text="Export WebPage As PDF With Image"
            OnClick="btnExportasPDF_Click" />
    </div>
    </form>
</body>
</html>

webpage to pdf,html to pdf,web to pdf,covert to pdf, save pdf as,data exporting,export data to pdf, sample code

Default.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

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

public partial class _Default : System.Web.UI.Page
{
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("EmpId", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        dt.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
        dt.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
        dt.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
        dt.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
        dt.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void btnExportasPDF_Click(object sender, EventArgs e)
    {
        Response.ContentType = "application/pdf";


        Response.AddHeader("content-disposition", "inline;filename=TestPage.pdf"); 


       //Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");      

        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        this.Page.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
}

 To download the source code click here

How to export web page as PDF with Image? - itextsharp Reviewed by Ravi Kumar on 4:19 PM Rating: 5

15 comments:

  1. RegisterForEventValidation can only be called during Render(); error

    ReplyDelete
    Replies
    1. to resolved this make sure you have EnableEventValidation="false" on your aspx page.

      Delete
  2. I am using the same code. My webpage has a table and an image which does not show up in the downloaded file. Can you help?

    ReplyDelete

  3. am trying to export an we page with image to pdf file
    in the code behind I am using the same code as yours...
    but i am getting an error like

    input string was not in a correct format.
    htmlparser(sr);
    please help

    ReplyDelete
    Replies
    1. hmm! check your connection string, passing parameters or in case of parsing fails..!!

      Delete
  4. Hai ravi,

    I'm trying to export the table(doesn't contain grid) to pdf with a code snippet similar to the code snippet mentioned above and its working fine but my problem is when I'm exporting it to pdf the labels present in the page are scattered through out the page its not coming in proper order where as its working fine in print preview. may i know y this is happening??

    ReplyDelete
    Replies
    1. hey shweta,

      As for as your question concern, I think you should try applying CSS & div.

      Delete
  5. Hey, I got your example to work and it's very close to the functionality I need except for one thing. Instead of generating the pdf in a separate instace of Adobe Acrobat, I would like to generate the dynamic pdf in the browser with the option of having it open in a new tab.

    Can this be done? Thanks in advance.

    ReplyDelete
    Replies
    1. Hey Lee,

      If you want to open pdf file in new browser tab use below code:-

      string path = Server.MapPath("TestPage.pdf");
      WebClient client = new WebClient();
      Byte[] buffer = client.DownloadData(path);

      if (buffer != null)
      {
      Response.ContentType = "application/pdf";
      Response.AddHeader("content-length", buffer.Length.ToString());
      Response.BinaryWrite(buffer);
      }

      I hope this will help you.

      Delete
    2. Hey, thanks for the quick response. I think the code snippet you have is for a PDF that has already been built from looking at the path variable.

      I need a dynamic pdf generated like your original example but have it displayed in the browser instead of it launching Adobe Acrobat.

      thanks.

      Delete
    3. Never mind, I happened upon another article and I need to enter this code to have the dynamic pdf generated in the browser. The key change is having "inline" rather than "attachment" followed by the filename verbiage.

      Response.AddHeader("content-disposition", "inline;filename=TestPage.pdf");

      Delete
    4. Great! It's working. :)
      Thanks for updating me.

      Delete
  6. hi how to apply css of the page web for the pdf ?

    ReplyDelete
    Replies
    1. hello wissam,
      If you are using table in your code then you can set it's style property. It will work for you.

      Delete

All Rights Reserved by Etechpulse © 2012 - 2017

Contact Form

Name

Email *

Message *

Powered by Blogger.