问题
I'm trying to export the gridview data to pdf and its doing fine.but the pdf file is showing error message like this--

The code is--
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 sample is like this--

<%@ 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>
<asp:Button ID="Button1" runat="server" onclick="Export_to_PDF"
Text="Export to PDF" Width="156px" />
</div>
</form>
</body>
</html>
why I'm getting this error? any help will be greatly appreciated.
回答1:
You are writing to the OutputStream
directly and then also pushing a custom object to the stream. Besides the duplication of efforts, the object you are pushing doesn't represent a PDF as we think of it, it is instead an internal representation of one. I'm going to suggest a couple of changes.
First, don't modify the HTTP response stream until you are 100% certain you have a valid PDF. Otherwise error messages get sent with a PDF type and things can get confusing fast. Second, similar to the first, don't bind your PDF writer to the HTTP response stream, this will make debugging easier. Instead, write to a MemoryStream
and grab the bytes from that if/when successful.
//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 isn't working then you're problem is probably 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 the single line below:
StringReader sr = new StringReader("<p>Hello</p>");
If that works then you need to figure out what's wrong with your HTML. Abandon all PDF concepts for a bit and inspect sw.ToString()
. Remember, iTextSharp has zero knowledge of ASP.Net, it can only work with HTML.
If the above still produces a broken PDF then you need to play around with the Response
object a bit. Simplify it by removing caching and headers. Don't open the PDF directly, instead download it to disk first. Post a link to the PDF and we might be able to help you more.
Also, HTMLWorker
is very old and not maintained anymore. Please consider upgrading to XmlWorker
instead.
来源:https://stackoverflow.com/questions/23695705/format-error-not-a-pdf-or-currupted