格式错误不是一个PDF或currupted [英] Format error not a pdf or currupted

查看:297
本文介绍了格式错误不是一个PDF或currupted的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在GridView数据导出为PDF和它做fine.but PDF文件显示这样的错误信息 -

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

在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 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>
        &nbsp;<asp:Button ID="Button1" runat="server" onclick="Export_to_PDF" 
            Text="Export to PDF" Width="156px" />
    </div>
    </form>
</body>
</html>

为什么我得到这个错误?
任何帮助将大大AP preciated。

why I'm getting this error? any help will be greatly appreciated.

推荐答案

您正在编写的的OutputStream 直接随后还推着一个自定义对象到流。除了事倍功半,你正在推动,因为我们认为它不会重新present一个PDF对象,它是不是一个的内部重新presentation。我要提出一些改动。

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.

首先,直到确定100%你有一个有效的PDF不修改HTTP响应流。否则,错误信息得到了PDF类型发送,事情可能会比较混乱快。其次,类似于第一,不要你的PDF作家绑定到HTTP响应流中,这将使调试更加方便。相反,写入的MemoryStream 并从抢字节,如果/当成功的。

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();

修改

如果上述不工作,然后你的问题很可能是与这些四行:

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>");

如果成功,那么你需要弄清楚什么是错了你的HTML。放弃所有的PDF概念了一下,检查 sw.ToString()。请记住,有iTextSharp的的ASP.Net零知识,它只能与HTML工作。

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.

如果上面仍然会产生一个破碎的PDF,那么你需要玩的响应对象了一下。通过删除缓存和头简化IT。不要直接打开PDF,而不是首先将其下载到磁盘。张贴链接到PDF,我们也许能帮助你。

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.

此外, HTMLWorker 是很旧,不能维持了。请考虑升级到 XmlWorker 代替。

Also, HTMLWorker is very old and not maintained anymore. Please consider upgrading to XmlWorker instead.

这篇关于格式错误不是一个PDF或currupted的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆