Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Asp.net Export WebPage with Images to PDF using iTextSharp in C#, VB.NET

May 17, 2013
Introduction:

Here I will explain how to export webpage with images to PDF in asp.net 
using iTextSharp in c#, vb.net.
Description:

In my previous articles I explained clearly Export gridview data to excel or word, Export gridview data to CSV file, Export Gridview data to pdf in asp.net, upload data from excel to sql server database, Export selected rows of gridview to excel/word and many articles relating to gridview, asp.net, c#, vb.net. Now I will explain how to export webpage with images to PDF in asp.net using iTextSharp in c#vb.net.

In asp.net we don’t have a direct feature to export gridview data to PDF for that reason here I am using third party library ITextSharp reference. First download dll from this site ITextSharp after that create one new website in visual studio and add ITextsharp dll reference to newly created website after that write the following code in aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJ3C-tQDXPIMmR_dS4yVjSxehkRh6cA3XmKuGynVFcv0my1TMzWis9ucLgUvpBhQ76zwFfKrp5SieMfZjZmiWdk8DCcL8rlv315aRPY8u3RjzO1zBros0Dm9NtVljyBYMtukeEmxuR01Q/" /></div>
<div><b>Export Webpage with images to pdf using itextsharp dll</b></div><br />
<div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnPDF" runat="server" Text="Export to PDF" OnClick="btnPDF_Click"/>
</form>
</body>
</html>
Now in code behind add these references


using System;
using System.Web;
using System.Web.UI;
using System.Data;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
After that write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
DataRow dtrow = dt.NewRow();    // Create New Row
dtrow["UserId"] = 1;            //Bind Data to Columns
dtrow["UserName"] = "SureshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();               // Create New Row
dtrow["UserId"] = 2;               //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();              // Create New Row
dtrow["UserId"] = 3;              //Bind Data to Columns
dtrow["UserName"] = "MaheshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void btnPDF_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.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, 0.0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
If you observe above code I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”. If we set VerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly

VB.NET Code


Imports System.Web
Imports System.Web.UI
Imports System.Data
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
Protected Sub BindGridview()
Dim dt As New DataTable()
dt.Columns.Add("UserId", GetType(Int32))
dt.Columns.Add("UserName", GetType(String))
dt.Columns.Add("Education", GetType(String))
dt.Columns.Add("Location", GetType(String))
Dim dtrow As DataRow = dt.NewRow()
' Create New Row
dtrow("UserId") = 1
'Bind Data to Columns
dtrow("UserName") = "SureshDasari"
dtrow("Education") = "B.Tech"
dtrow("Location") = "Chennai"
dt.Rows.Add(dtrow)
dtrow = dt.NewRow()
' Create New Row
dtrow("UserId") = 2
'Bind Data to Columns
dtrow("UserName") = "MadhavSai"
dtrow("Education") = "MBA"
dtrow("Location") = "Nagpur"
dt.Rows.Add(dtrow)
dtrow = dt.NewRow()
' Create New Row
dtrow("UserId") = 3
'Bind Data to Columns
dtrow("UserName") = "MaheshDasari"
dtrow("Education") = "B.Tech"
dtrow("Location") = "Nuzividu"
dt.Rows.Add(dtrow)
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnPDF_Click(sender As Object, e As EventArgs)
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()
End Sub
End Class
Demo


Once we export data to pdf our output will be like this 

Download sample code attached






During work with this application if you get any error message like
Control 'gvdetails' of type 'GridView' must be placed inside a form tag with runat=server


Check this post to solve this problem


Otherwise if you’re getting any error message like 

RegisterForEventValidation can only be called during Render();



Check this post to solve your problem



If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

71 comments :

Vidyasagar said...

Hi. Mr.Suresh, this is very nice post, can u post vice versa article, from PDF to excel or text file using C#.NET, thanks

Rammohan said...

Hi Suresh,
Very nice post ,even not only this every article which was posted by u was nice.

if u have an editable PDF export and import functinality pls post it..

Unknown said...

nice post sir

Unknown said...

sir,
how we extract text and images from doc file using asp.net C#

Unknown said...
This comment has been removed by the author.
Unknown said...

Thanku sir ..sir i have 4 page (login.aspx ,default.aspx,def1aspx,def2.aspx).i m working def2.aspx.if i click browser back button throw out login.aspx or show error page (custom control ).how i can used?

Vidyasagar said...

Hi Mr.Suresh, i'm eagerly waiting for your reply for first comment in this post...thank u very much..

Navjot Singh said...

Hi Suresh ,

thanks for nice post but I am facing an issue that
I have added src of image in my page like this:

src="./1.jpg"

image is located in my application. so when i click on export button HTML Parser give error:

Could not find file 'C:\1.jpg'.

any solution regarding this...

Unknown said...

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
string imageFilePath = Server.MapPath(".") + "/image/xyz.png";
iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(imageFilePath);
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, 4f, 4f, 10f, -400f);
png.ScaleToFit(110, 110);
png.Alignment = iTextSharp.text.Image.UNDERLYING;
png.SetAbsolutePosition(480, 800);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(png);
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
---------------------
right click on project add new folder on project name image and add images name xyz.png ........

Unknown said...

Hi Mr.Suresh, i'm eagerly waiting for your reply for six comment in this post...thank u very much

Anonymous said...

http://mc.tt/efNwx52CXM

Anonymous said...

Hi Suresh,
This is Bhati.Can u tell me how i convert website in hindi..

Abey E Mathews said...

thanku

Abey E Mathews said...

how to send generated pdf as email,means attach file (with out downloading with button click)

Unknown said...

Font size too small: 0

I have error while convert my panel to pdf...

Please help me sir.....

Anonymous said...

Sir, I am abhinavsingh993 Please tell you won that comptition for which I was voted for you or not , as usual you content is mindblowing

Anonymous said...

Can i convert a web page in PDF which has a text in HIndi/ urdu ...

Unknown said...

Nice tutorial

raj said...

I have a doubt Dasari...

your code is perfect but its doesn't work when "sorting" operation performed on grid..

and it doesn't work when grid is empty..

Anonymous said...

For me download is not firing..and am not getting any errors too.i am using the same code and reference of the dll which u posted. can any one help me..thanks

@bhi said...

Error Location : htmlparser.Parse(sr);
Error Message : The path is not of a legal form.

dvn said...

Error Location: htmlparser.Parse(sr);
Error Message="Object reference not set to an instance of an object."
Here is The StackTrace:
Source="itextsharp"
StackTrace:
at iTextSharp.text.html.simpleparser.HTMLWorker.CreateLineSeparator(IDictionary`2 attrs)
at iTextSharp.text.html.simpleparser.HTMLTagProcessors.HTMLTagProcessor_HR.StartElement(HTMLWorker worker, String tag, IDictionary`2 attrs)
at iTextSharp.text.html.simpleparser.HTMLWorker.StartElement(String tag, IDictionary`2 attrs)
at iTextSharp.text.xml.simpleparser.SimpleXMLParser.ProcessTag(Boolean start)
at iTextSharp.text.xml.simpleparser.SimpleXMLParser.Go(TextReader reader)
at iTextSharp.text.xml.simpleparser.SimpleXMLParser.Parse(ISimpleXMLDocHandler doc, ISimpleXMLDocHandlerComment comment, TextReader r, Boolean html)
at iTextSharp.text.html.simpleparser.HTMLWorker.Parse(TextReader reader)
at LesionPickForMamo3.btnExportPDF_Click(Object sender, EventArgs e) in c:\Projects\ImageMapTest\LesionPickForMamo3.aspx.cs:line 53
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:

dvn said...

I found the problem. ITextSharp did not like the horizontal-line tags that i have in my asp.net page. I removed those horizontal-line tags and the tool ran fine but the output captured into the PDF file with missing info -- the image was modified by the user by adding some check mark and those check marks were not shown in the PDF file

Padhu said...

Hi,

I got error from creation of pdf file. Please help me....

Error:

Server Error in '/Web' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 322: PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
Line 323: pdfDoc.Open();
Line 324: htmlparser.Parse(sr);
Line 325: pdfDoc.Close();
Line 326: Response.Write(pdfDoc);

Source File: e:\Projects\Padmanaban\Web\tolivault\Forms\LidqReport.aspx Line: 324

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
iTextSharp.text.html.simpleparser.HTMLWorker.CreateLineSeparator(IDictionary`2 attrs) +47
iTextSharp.text.html.simpleparser.HTMLTagProcessor_HR.StartElement(HTMLWorker worker, String tag, IDictionary`2 attrs) +55
iTextSharp.text.html.simpleparser.HTMLWorker.StartElement(String tag, IDictionary`2 attrs) +123
iTextSharp.text.xml.simpleparser.SimpleXMLParser.ProcessTag(Boolean start) +75
iTextSharp.text.xml.simpleparser.SimpleXMLParser.Go(TextReader reader) +2162
iTextSharp.text.xml.simpleparser.SimpleXMLParser.Parse(ISimpleXMLDocHandler doc, ISimpleXMLDocHandlerComment comment, TextReader r, Boolean html) +83
iTextSharp.text.html.simpleparser.HTMLWorker.Parse(TextReader reader) +59
ASP.tolivault_forms_lidqreport_aspx.Button1_Click(Object sender, EventArgs e) in e:\Projects\Padmanaban\Web\tolivault\Forms\LidqReport.aspx:324
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

Unknown said...

Hi. Mr.Suresh,
Error Location: this.Page.RenderControl(hw);
Error Message="The extension 'upaGrafico' extension is not registered. Extender controls must be registered using RegisterExtenderControl() before calling RegisterScriptDescriptors(). Parameter name: ExtenderControl".
Can you help me? thanks.

Unknown said...

Hi Suresh,

This is abhishek. Nice post it is.
And when i excecute the code pdf generates, in that the columns names are not showing only rows are showing.

Unknown said...

i want to use Indian rupee symbol before the value instead of Rs. in pdf.
Am using itextsharp to generate the pdf. even i get the background image for that pdf but am suffering due to this rupee symbol prob..
Can i get any help?
Thanks in advance sir!
ragavanragavan14@gmail.com

bala said...
This comment has been removed by the author.
bala said...

//send generated pdf as email,means attach file (with out downloading with button click)
protected void email_send(object sender, EventArgs e)
{

String strFrom = your_mail_id.Text;
String strTo = to_mail_id.Text;
String strSubject = subject.Text;
String strMsg = message.Text;

try
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
print.RenderControl(hw);
MailMessage mail = new MailMessage();

mail.IsBodyHtml = true;
mail.To.Add(new MailAddress(strTo));
mail.Subject = "Report";
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
mail.Attachments.Add(new Attachment(mAtt, "Report.xls"));

mail.Subject = strSubject;
SmtpClient objSMTPClient = new SmtpClient();
mail.From = new MailAddress(strFrom);
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
objSMTPClient.Send(mail);
lbldisplay.Text = "Email Sent Sucessfully";
}
catch
{
lbldisplay.Text = "Email Not Sent";
}
}

public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
return;
}

Unknown said...

Hi,

Column names are displaying in pdf file

Anonymous said...

but online server dont suppot the itextsharp how to solve this problem?
ple reply santhosh.mca15@gmail.com

Anonymous said...

Hi suresh,

I used for concept to export data from gridview to PDF. but , could you plz tell me how to handle the case by using itextsharp, if not data content is there to display , but need to show that information to user inside PDF . Hope you will help on this soon.

Regards,
Minnu

kavithakesavan said...

Hi ,Suresh ..I'm receiving below error
The number of columns in PdfPTable constructor must be greater than zero

kavithakesavan said...

Contents in my page will generate dynamically.

Unknown said...

hello sir
this blog was very nice . i used for ref lot of time but i got the error in the pdfDoc.Close() line

Error : The document has no pages.

Can you please help me to finish the project

bhanu said...

i got this error.when i run ur code my application.


"Expected > for tag: near line 33, column 2"

Unknown said...

Could not find file 'c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Images\Accendere%20Logo.jpg'.

error location
htmlparser.Parse(sr);

Unknown said...

Hi Suresh,Its a nice work you have done..

Theosoft

Anonymous said...

hii suresh i am using your code but the problem is if i am having java script on my page then that also get printed in pdf can you help or you can tell me how i can make pdf exact like print preview that we see in browser of a page

Anonymous said...

Script control 'UpdateProgress1' is not a registered script control. Script controls must be registered using RegisterScriptControl() before calling RegisterScriptDescriptors().
Parameter name: scriptControl

ERROR CAME LIKE THIS

Anonymous said...

hi i m manoj kumar suresh sir your article too much good i salute you .ur article really helpful

Unknown said...

hii
suresh i'am a big fan of u..
u r just awesome..
can u help me to generate pdf of my web page..
while the controls are generating dynamically at run time from server side.

Anonymous said...

how to display the indian rupee symbol. itextsharp shows all other sysmbols except ours..any solution ?

thanx.
V.R.Hari

Anonymous said...

Hi,
I got error mentioned at below.
Could not load file or assembly 'itextsharp, Version=4.1.2.0, Culture=neutral, PublicKeyToken=8354ae6d2174ddca' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Anonymous said...

Hai. . .
Thank you for such great examples.
You are giving very useful coding and ideas.
Thank you sir.
Have a happy coding.
I feel good.
Thank you sir.

Anonymous said...

Hi Suresh,
I am getting following error when exporting html aspx page to pdf
Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.Paragraph

[InvalidCastException: Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.Paragraph'.]
iTextSharp.text.html.simpleparser.HTMLWorker.ProcessLink() +575
iTextSharp.text.html.simpleparser.HTMLTagProcessor_A.EndElement(HTMLWorker worker, String tag) +15
iTextSharp.text.html.simpleparser.HTMLWorker.EndElement(String tag) +52
iTextSharp.text.xml.simpleparser.SimpleXMLParser.Go(TextReader reader) +1287
iTextSharp.text.html.simpleparser.HTMLWorker.Parse(TextReader reader) +78
PoliceCrashReportWeb._Default.ItextSharpExportToPdf() in d:\RFPs\NJ Police Crash Investigation Report\PoliceCrashReport\PoliceCrashReport\PoliceCrashReportWeb\Default.aspx.cs:40
PoliceCrashReportWeb._Default.lnkExport_Click(Object sender, EventArgs e) in d:\RFPs\NJ Police Crash Investigation Report\PoliceCrashReport\PoliceCrashReport\PoliceCrashReportWeb\Default.aspx.cs:228
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +116
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +101
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9642610
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

Anonymous said...

Hi suresh, your code is working But rendered pdf cannot open in Adobe Acrobat reader and says "either not a file type or Content Damaged"

Unknown said...

HI have arise image overwrite issue. Can you please help for it.
How it solved.?

I have shared screenshot.
https://picasaweb.google.com/102349157032425307790/February252014#5984291658391518402

Unknown said...

i m using this code bt i m getting error..

Input string was not in a correct format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.

S kaushik said...

Sir... while saving as pdf Gridview headers are not shown and all the data is assigned to right of the page and PDF is using 100% page size for showing grid ...

is there any method to save pdf in same format as it looks as webpage

Anonymous said...

Server Error in '/OCAP' Application.

Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

how to solve this ,please help me sir. ratnaja.mukthi@gmail.com is my mail id.

Anonymous said...

use your code
but error Unable to cast object of type 'iTextSharp.text.html.simpleparser.IncTable' to type 'iTextSharp.text.ITextElementArray'.

Anonymous said...

Hi sir,
m extracting a form to pdf which is like table structure, created with "div" tags..
After Exporting it to pdf, it comes in a single line and the table structure is no longer visible...
can u pls suggest any solution?????

Anonymous said...

how to sole this problem

System.NullReferenceException: Object reference not set to an instance of an object.

at iTextSharp.text.html.simpleparser.HTMLWorker.CreateLineSeparator(IDictionary`2 attrs)

Pratik Panbude said...

Hi sir,

I am trying to conver pdf to image files.
How to convert pdf to jpg.

Please help me out

Unknown said...

Hello sir i have used your code to export Aspx page to pdf & it works fine but when i am using a ajax controls then it gives me error message i.e :-
"
Extender control 'CalendarExtender2' is not a registered extender control. Extender controls must be registered using RegisterExtenderControl() before calling RegisterScriptDescriptors().
Parameter name: extenderControl
"
please give a solution to resolve it...
Thanks in advance

Unknown said...

Protected Sub imgPdf_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgPdf.Click
Dim outputFilename = qHeaderID & "-SurveyPrint"
Dim filename As String = ConfigurationManager.AppSettings("ExportFilePath") + "\\" & outputFilename & ".pdf"
Dim fileList As String() = Directory.GetFiles(ConfigurationManager.AppSettings("ExportFilePath"), outputFilename & ".pdf")
For Each file__1 As String In fileList
'Debug.WriteLine(file + "will be deleted");
File.Delete(file__1)
Next
Dim ss As String = Request.Url.AbsoluteUri.ToUpper()
Dim url As String = Request.Url.AbsoluteUri.ToUpper().Replace("SurveySimulator.aspx", "SurveySimulator.aspx")
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=" & filename)
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
Dim text As String = sr.ReadToEnd()
' convert string to stream
Dim byteArray As Byte() = Encoding.ASCII.GetBytes(text)
' GetyBytes method is used to to create a byte array
Dim stream As New MemoryStream(byteArray)
Dim reader As New StreamReader(stream)
htmlparser.Parse(reader)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()
End Sub

I got below error

"Expected > for tag: near line 33, column 2"

Manish Swarnkar said...

Extender control 'ConfirmButtonExtender1' is not a registered extender control. Extender controls must be registered using RegisterExtenderControl() before calling RegisterScriptDescriptors().
Parameter name: extenderControl

Anonymous said...

Hindi font is not display using this code

Anonymous said...

Hindi font is not display using this code

Anonymous said...

sir .... vvv urjent how to display dynamic image (Comming from codebehind file url) in pdf file ...

Gokufast said...

"Remote Server Error (407) proxy authentication required"

DomFilk said...

I'm not a developer, i always use this free online pdf to image converter

lorium ipsum said...

hi ..How can i convert .aspx page to PDF which contain many tables some label control where data is binded ..How to do this

Anonymous said...

I got an error msg: Illegal characters in path.......
on htmlparser.Parse(sr);

Unknown said...

How to Convert/Export an ASPX web page with texboxes and other controls(Checkbox,Radio buttons etc) to PDF using itextsharp

Can any one help?

Unknown said...
This comment has been removed by the author.
Unknown said...

lorium ipsum :-
Did u find any solution?
Iam also facing the same issue

Unknown said...

hello suresh,
i wanna ask u something how to set html table background image and print to pdf in windows application,actually i am creating string builder html table and set table background image but when i print table to pdf there is no image showing in pdf.

Unknown said...

Hi, thanks alot for you
i have one problem ,evry thing it's converted very good except the gridview nothing in appears in pdf

Unknown said...

Hi Suresh,

I am trying to use iTextsharp.dll to convert my invoice page to pdf. But I am getting error at htmlParser.Parse(sr);

error message:
=============
An exception of type 'System.InvalidCastException' occurred in itextsharp.dll but was not handled in user code
Additional information: Unable to cast object of type 'iTextSharp.text.html.simpleparser.TableWrapper' to type 'iTextSharp.text.ITextElementArray'.

Tried a lot googling. No luck. Kindly help me to proceed further in my project.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.