Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDF returning a corrupt file

Tags:

c#

asp.net

pdf

I am using the following bit of code to send a pdf file back to the user. this works fine on my pc and on all of our test pcs. however the user is complaining the document is corrupt. When I look at the pdf file sent back in notepad I can see some HTML after the binary infomation.

protected void btnGetFile_Click(object sender, EventArgs e)
        {
            string title = "DischargeSummary.pdf";
            string contentType = "application/pdf";
            byte[] documentBytes = GetDoc(DocID);

            Response.Clear();
            Response.ContentType = contentType;
            Response.AddHeader("content-disposition", "attachment;filename=" + title);
            Response.BinaryWrite(documentBytes);
        }
like image 863
user226305 Avatar asked Feb 15 '26 22:02

user226305


1 Answers

The issue is cause by the response object appending to the end of the file bytes the Parsed HTML for the page at the end of the file. This can be prevented by calling Response.Close(), after you

have written the file to the buffer.

protected void btnGetFile_Click(object sender, EventArgs e)
        {
            string title = "DischargeSummary.pdf";
            string contentType = "application/pdf";
            byte[] documentBytes = GetDoc(DocID);

            Response.Clear();
            Response.ContentType = contentType;
            Response.AddHeader("content-disposition", "attachment;filename=" + title);
            Response.BinaryWrite(documentBytes);
            Response.End();
        }
like image 106
John Nunn Avatar answered Feb 18 '26 12:02

John Nunn