如何从 ASP.NET 中的 Web 请求返回 pdf? [英] How can I return a pdf from a web request in ASP.NET?

查看:12
本文介绍了如何从 ASP.NET 中的 Web 请求返回 pdf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,我希望有人能够单击链接并获得一次性使用的 pdf.我们有创建 PDF 文件的库,所以这不是问题.

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.

我们可以生成一个指向 aspx 页面的链接,让该页面生成 pdf,将 pdf 保存到文件系统,然后 Response.Redirect 到保存的 pdf.然后我们必须以某种方式跟踪和清理 PDF 文件.

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.

因为我们永远不需要保留这些数据,如果可能的话,我想做的是让 aspx 页面生成 pdf,并将其作为对原始请求的响应直接返回.这可能吗?

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?

(在我们的例子中,我们使用的是 C#,我们想要返回一个 pdf,但似乎任何解决方案都可能适用于各种 .NET 语言和返回的文件类型.)

(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.)

推荐答案

假设您可以获得一个 byte[] 代表您的 PDF:

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();

这篇关于如何从 ASP.NET 中的 Web 请求返回 pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆