2012-10-12 83 views
0

这是我下载一个PDF文档代码: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 reader could not open 'fileName.pdf' because it is either not a supported file type or because the file has been damaged (for example: it was sent as an email attachment and wasn't correctly decoded))

+0

是在DB的PDF? – IrishChieftain

+1

我认为你生成的不是一个有效的PDF文件 – secondflying

回答

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