0

这是我下载 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”,因为它不是受支持的文件类型或文件已损坏(例如:它作为电子邮件附件发送并且未正确解码))

4

1 回答 1

0

通过传递 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();
}
于 2012-10-12T07:03:09.183 回答