Monday, July 20, 2009

Writing PDF from stream to IE6 from ASP.NET

I *very much dislike* (stronger words come to mind here) things that you just happen to have to know about browser quirks and plug-in quirks. The amount of time you can spend trying to figure it out is horrible and, besides basic trouble shooting skills, there is not much you can do to reason your way out of it. Enter: IE6 and PDF's from a web server that uses gzip compression on aspx pages. Horrible. Getting the Open/Cancel/Save dialog to show is challenge number 1. It requires a very specific set of HTTP headers that's near impossible to guess (because there are quite a few possible combinations of HTTP headers out there).

Challenge number 2 is the gzip compression. IE6 doesn't understand that it should unzip before passing the PDF on to the plug-in. I think you can also resolve this issue by putting a gzip indicator in the PDF file, but since the PDF file was being generated by an other tool, that wasn't an option.

So, for issue 1 I finally pulled the following code together, after Googling it extensively:

public static void ExportReportToPDF(HttpContext aContext, string aFileName, bool aAttachment) {
byte[] result = ... stuff to generate the PDF.;
if (result != null) {
aContext.Response.ClearHeaders();
aContext.Response.ClearContent();
aContext.Response.Clear();
aContext.Response.ContentType = "application/pdf";
aContext.Response.AppendHeader("content-length", result.Length.ToString());
aContext.Response.Expires = -1;
aContext.Response.AddHeader("Content-Transfer-Encoding", "binary");
if (!String.IsNullOrEmpty(aFileName)) {
aContext.Response.AppendHeader("Content-Disposition", String.Format("{1}; filename=\"{0}\"", aFileName, aAttachment ? "attachment" : "inline"));
};
aContext.Response.AddHeader("Pragma", "no-cache");
aContext.Response.AddHeader("Cache-Control", "private");
aContext.Response.BinaryWrite(result);
aContext.Response.Flush();

aContext.Response.Close();
aContext.Response.End();
}


To address issue 2, you can use an ashx handler and reference it through a hyperlink. Assuming you don't have gzip compression turned on for the ashx.

Easy in the end, but getting the headers straight was a nightmare, only to be helped by an hour of Googling the issue.

No comments:

Post a Comment