繁体   English   中英

ABCpdf-使用.NET Core 2.1下载PDF-HttpContext / HttpResponse

[英]ABCpdf - Download PDF with .NET Core 2.1 - HttpContext/HttpResponse

我正在创建一个网页,允许用户使用ABCpdf将报告下载为PDF。 但是阅读文档时,我看到的唯一选择是使用doc.Save("test.pdf") (将文件保存在托管应用程序的服务器上)或使用'HttpContext.Current.ApplicationInstance.CompleteRequest();' doc.Save("test.pdf") 'HttpContext.Current.ApplicationInstance.CompleteRequest();' (这是在客户端保存的,这是我想要的,但是HttpContext.Current在.NET Core上不可用。

我拥有的创可贴解决方案是doc.Save() ,我将文件保存在服务器上,然后将链接发送到视图,然后从服务器下载该视图。 我可以想到的潜在风险是,确保在服务器上开始下载后进行“清理”。

是否有替代/.NET Core等效于HttpContext.Current和HttpResponse?

这是我要工作的代码:

byte[] theData = doc.GetData();
Response.ClearHeaders();
Response.ClearContent();
Response.Expires = -1000;
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", theData.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=test.pdf"); 
Response.BinaryWrite(theData);
HttpContext.Current.ApplicationInstance.CompleteRequest();

我收到的错误(不详细)

'HttpResponse' does not contain a definition for 'ClearHeaders'
'HttpResponse' does not contain a definition for 'ClearContent'
'HttpResponse' does not contain a definition for 'Expires'
'HttpResponse' does not contain a definition for 'AddHeader'
'HttpResponse' does not contain a definition for 'BinaryWrite'
'HttpContext' does not contain a definition for 'Current'

我已将此答案更新为实际有效的方法! GetStream可以满足您的需求,但是,如果要在.NET Core中方便地下载文件,则按照https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first中的说明创建控制器将容易得多。 -web-api?view = aspnetcore-2.1 然后,您可以创建一个路由控制器,以使用Asp.net core将流中的文件提供服务,如将PDF返回到浏览器所示。 因此,您的控制器将类似于:

[Route("api/[controller]")]
public class PDFController : Controller {
// GET: api/<controller>
    [HttpGet]
    public IActionResult Get() {
        using (Doc theDoc = new Doc()) {
            theDoc.FontSize = 96;
            theDoc.AddText("Hello World");
            Response.Headers.Clear();
            Response.Headers.Add("content-disposition", "attachment; filename=test.pdf");
            return new FileStreamResult(theDoc.GetStream(), "application/pdf");
        }
    }
}

出于好奇,我只是对此进行了模拟,它确实起作用了-当您转到URL localhost:port / api / pdf时,将PDF直接下载到浏览器中。 如果将内容处置设置为“ inline; filename = test.pdf”,它将显示在浏览器中,并可以作为test.pdf下载。

有关GetStream方法的更多信息,请参见: https ://www.websupergoo.com/helppdfnet/default.htm?page = source%2F5-abcpdf%2Fdoc%2F1-methods%2Fgetstream.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM