Search code examples
c#asp.netdownloadhttpresponse

Response.BinaryWrite() works for one page, not another


I have a helper function in a class library that creates and serves a custom PDF:

byte[] file = GetPdfBytesFromHtmlString( htmlCodeToConvert );

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader( "Content-Type", "binary/octet-stream" );
response.AddHeader( "Content-Disposition", "attachment; filename=" + filename + "; size=" + file.Length.ToString() );
response.Flush();
response.BinaryWrite( downloadBytes );
response.Flush();
response.End();

When this code is executed on one page, everything works. Another page is mostly identical, the only difference being the output of the HTML to be written to the PDF, which I have verified is working correctly. However, nothing happens. I've stepped through the code, it just goes its merry way, but the browser doesn't prompt to download.

I know I'm leaving a lot of code out, but because it works in one instance and not another, I'm stumped and looking for ideas to pursue a solution.


Solution

  • I really hate answering my own question, because it means I didn't do enough research before asking it. However, I was reviewing it and realized I'd only tested in Firefox. Running it in IE exposed a script error that contained the text "Error parsing near '%PDF - 1.4%' which I'd seen while searching but didn't follow up on.

    The problem is the page that's not working uses an AJAX Update Panel, which I hadn't realized when I stated the code was identical. The export button click code is, but the markup isn't.

    The second reply in this post contains some additional info and a workaround.