开发者

How can I return a pdf from a web request in ASP.NET?

开发者 https://www.devze.com 2022-12-16 11:42 出处:网络
Simply put, I\'d like someone to be able to click a link, and get a one-time-use pdf.We have the library to create PDF files, so that\'s not an issue.

Simply put, I'd like someone to be able to click a link, and get a one-time-use pdf. We have the library to create PDF files, so that's not an issue.

We could generate a link to an aspx page,开发者_开发知识库 have that page generate the pdf, save the pdf to the filesystem, and then Response.Redirect to the saved pdf. Then we'd somehow have to keep track of and clean up the PDF file.

Since we don't ever need to keep this data, what I'd like to do instead, if possible, is to have the aspx page generate the pdf, and serve it directly back as a response to the original request. Is this possible?

(In our case, we're using C#, and we want to serve a pdf back, but it seems like any solution would probably work for various .NET languages and returned filetypes.)


Assuming you can get a byte[] representing your PDF:

Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition",
    "attachment;filename=\"FileName.pdf\"");

Response.BinaryWrite(yourPdfAsByteArray);

Response.Flush();

Response.End();


Look at how HTTP works. The client (=browser) doesn't rely on extensions, it only wants the server to return some metadata along with the document.

Metadata can be added with Response.AddHeader, and one 'metadata line' consists of Name and Value.

Content-Type is the property you are interested in, and the value is MIME type of the data (study: RFC1945 for HTTP headers, google for MIME type).

For ordinal aspx pages (html, ....) the property is 'text/html' (not so trivial, but for this example it is enough.). If you return JPG image, it can have name 'image.gif', but as long as you send 'image/jpeg' in Content-Type, it is processed as JPG image. Content-type for pdf is 'application/pdf'.

The browser will act according to default behaviour, for example, with Adobe plugin, it will display the PDF in it's window, if you don't have any plugin for PDF, it should download the file, etc..

Content-Disposition header says, what you should do with the data. If you want explicitly the client to 'download' some HTML/PDF/whatever, and not display it by default, value 'attachment' is what you want. It should have another parameter, (as suggested by Justin Niessner), which is used in case of something like:

http://server/download.aspx?file=11 -> Content-Disposition: attachment;filename=file.jpg says, how the file should be by default named.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号