以PDF格式下载无法正常工作?

时间:2012-10-12 06:51:05

标签: c# asp.net

这是我下载PDF文档的代码:

string attachment = "attachment; filename=Contacts.pdf";

Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
datalist1.Parent.Controls.Add(frm);

frm.Attributes["runat"] = "server";

frm.Controls.Add(datalist1);
frm.RenderControl(htw);

Response.Write(sw.ToString());
Response.End();

它在Excel中运行。在PDF下载时显示此错误:

  

(Adobe读者无法打开' fileName.pdf'因为它不是a   支持的文件类型或因为文件已损坏(例如:   它是作为电子邮件附件发送的,并未正确解码))

1 个答案:

答案 0 :(得分:0)

从DB通过传递ASPX表单:

try
{
    string selectQuery = 
        "SELECT Contact FROM dbo.Contacts WHERE dbo.Contacts.ContactID=" 
            + contactID.ToString();

    conn = new SqlConnection(CONN);
    SqlCommand cmd = new SqlCommand(selectQuery, conn);

    conn.Open();
    dr = cmd.ExecuteReader();

    dr.Read();
    context.Response.ContentType = "Application/pdf";
    context.Response.Headers.Add("Content-Disposition", 
        "attachment; filename=Contacts.pdf");
    context.Response.BinaryWrite((Byte[])dr[0]);
}
catch (Exception ex)
{
    // Display friendly message
    // Log and report error
}
finally
{
    dr.Close();
    conn.Dispose();
}