[英]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.