How to export web page as PDF with Image? - itextsharp
C# - How to export webpage with images to PDF in asp.net using iTextSharp
In my previous posts I explained How to export dataset to excel in C#? and How to save a map as an image? - MapXtreme.
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>
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", "attachment;filename=TestPage.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:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0_q0XzsnOle6YWnQhp2FoRg4oJHUpWv5yI7u69-5bo3qsr5pJULq55UWT1m7s6IJIrn8aVbDrch4rX9OdZOB7Y3vPmvfMpA-8tfbwZAR5oppQmMX0gzoCwwBlzFCkv7SemJ7qrD7lYV_9/s72-c/export-to-pdf.jpg)
RegisterForEventValidation can only be called during Render(); error
ReplyDeleteto resolved this make sure you have EnableEventValidation="false" on your aspx page.
DeleteI 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?
ReplyDeleteyeah sure! please show me your code.. @Aks
Delete
ReplyDeleteam 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
hmm! check your connection string, passing parameters or in case of parsing fails..!!
DeleteHai ravi,
ReplyDeleteI'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??
hey shweta,
DeleteAs for as your question concern, I think you should try applying CSS & div.
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.
ReplyDeleteCan this be done? Thanks in advance.
Hey Lee,
DeleteIf 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.
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.
DeleteI need a dynamic pdf generated like your original example but have it displayed in the browser instead of it launching Adobe Acrobat.
thanks.
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.
DeleteResponse.AddHeader("content-disposition", "inline;filename=TestPage.pdf");
Great! It's working. :)
DeleteThanks for updating me.
hi how to apply css of the page web for the pdf ?
ReplyDeletehello wissam,
DeleteIf you are using table in your code then you can set it's style property. It will work for you.