I have a question about outputting PDF files. Currently I’m storing the PDF in the database in binary form. I’m outputting the PDF file via a URL such as:
http://myhost.com/FileManager.aspx?FileId=8465b2f9-b64e-4a9a-a449-94b5adb3b278
so from what I could deduce, to the browser this is an .aspx page that is loading and not a PDF. Firefox and IE interpret this correctly and launch Adobe Acrobat, however since Chrome (12.0.742.112) has its own implementation of a PDF reader, it will open the file correctly, but then when someone goes to save the file in chrome, it wants to save it as a .aspx. If I simply rename the .aspx to .pdf, the file downloads correctly. However, I”m trying to avoid telling my customer that s/he may have to take that extra step.
When I chose to look at the headers that loaded in Chrome via Web Inspector, I see this:
FileManager.aspx:-1 Resource interpreted as Document but transferred
with MIME type application/pdf
I can completely understand why Chrome would say this.
Furthermore, I get a save as box upon page load when I add:
Response.AddHeader("content-disposition", "attachment;filename=blah.pdf");
However, I was hoping to just keep the file in a browser. So aside from using some URL Rewrite, is there a way I can manipulate the HTTP Headers to simply open the page as a PDF and save correctly in Chrome?
Lastly, I tried using a WebService, but I can’t seem to write the binary data to the page.
this.Context.Response.BinaryWrite(bytes);
Any help is appreciated!
In the web application’s top-level web.config, add the following
<add>element to the<httpHandlers>section:…where
ProjectName.FileManageris the full name (namespace and classname) of theFileManagerclass inFileManager.aspx.cs.This tells ASP.NET to handle the path
/FileManager.pdfusing the handler defined byProjectName.FileManager. (System.Web.UI.Pageimplements theIHttpHandlerinterface, so every webform is a handler.)Now you can serve the PDFs via a URL with a .pdf extension like so:
http://myhost.com/FileManager.pdf?FileId=8465b2f9-b64e-4a9a-a449-94b5adb3b278You do not need to rename the physical
FileManager.aspxfile. When the user enters /FileManager.pdf?FileId=foo in the browser, ASP.NET will handle the request with the ProjectName.FileManager class defined in FileManager.aspx.Note:
The above should work on Cassini (the Visual Studio “mini” webserver) with no further changes. However IIS by default only sends *.aspx, *.asmx, *.ashx requests to ASP.NET. Therefore, for the above to work on IIS, you need to tell it to send requests for
/FileManager.pdfto ASP.NET. That is, you need to configure a “mapping”.With IIS 6 you need to configure the mapping using IIS manager.
With IIS 7 you can configure a mapping from your web.config–this makes deployment easier, but it depends on how your hosting is set up.