Non-pdf format error or

I am trying to export gridview data to pdf and make it fine.but, the pdf file shows an error message like this -

enter image description here

The code -

protected void Export_to_PDF(object sender, System.EventArgs e) { try { Response.Clear(); //this clears the Response of any headers or previous output Response.Buffer = true; //ma Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=DataTable.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); } catch (Exception ex) { Console.WriteLine("An error occurred: '{0}'", ex); } 

}

my example is this:

enter image description here

  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoginMaster.aspx.cs" Inherits="QuestionCategories" %> <!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>Grid View Example............Page</title> </head> <body> <form id="form1" runat="server"> <div style="height: 316px"> <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="New User" /><br /> <br /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="UserName" ForeColor="#333333" GridLines="None" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"> <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <Columns> <asp:CommandField HeaderText="Edit-Update" ShowEditButton="True" /> <asp:BoundField DataField="UserName" HeaderText="User Name" /> <asp:BoundField DataField="usergroup" HeaderText="User Group" /> <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" /> </Columns> <RowStyle BackColor="#FFFBD6" ForeColor="#333333" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" /> <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> &nbsp;<asp:Button ID="Button1" runat="server" onclick="Export_to_PDF" Text="Export to PDF" Width="156px" /> </div> </form> </body> </html> 

why am i getting this error? Any help would be greatly appreciated.

0
c # pdf itextsharp
May 16 '14 at 13:03
source share
1 answer

You write directly to the OutputStream , and then also click on the object a custom object. Apart from duplicating efforts, the object you put forward is not a PDF, as we think about it, it is an internal representation of one. I am going to suggest a couple of changes.

First, do not change the flow of HTTP responses until you are 100% sure that you have a valid PDF. Otherwise, error messages are sent with the type of PDF, and everything can get confused quickly. Secondly, similar to the first, do not associate your PDF writer with the HTTP response stream, this will facilitate debugging. Instead, write to a MemoryStream and take the bytes from this if / on success.

 //Do PDF stuff first //We'll put our final bytes here when we're done byte[] bytes; //Write to a MemoryStream so that we don't pollute the HTTP pipeline using (var ms = new MemoryStream()) { //This is all the same StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); //Use our above MemoryStream instead of the OutputStream PdfWriter.GetInstance(pdfDoc, ms); //Same pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); //The above is done, get the byte representation of our PDF bytes = ms.ToArray(); } //If the above works, change the HTTP stream to output the PDF Response.Clear(); //this clears the Response of any headers or previous output Response.Buffer = true; //ma Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=DataTable.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); //Write our byte array Response.BinaryWrite(bytes); Response.End(); 

EDIT

If the above does not work, then you probably have a problem with these four lines:

 StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); 

Try replacing the above four with one line below:

 StringReader sr = new StringReader("<p>Hello</p>"); 

If this works, you need to find out what is wrong with your HTML. Drop all PDF concepts for validation and check sw.ToString() . Remember, iTextSharp has zero ASP.Net knowledge, it can only work with HTML.

If a broken PDF is still being created above, you need to play around with the Response object a bit. Simplify it by removing caching and headers. Do not open the PDF directly, but first download it to disk. Send a link to the PDF and we can help you.

In addition, HTMLWorker very old and is no longer supported. Instead, switch to XmlWorker .

+1
May 16 '14 at 19:33
source share



All Articles