[英]Link to PDF using iTextSharp
這個問題可能有一個簡單的答案,但我似乎找不到解決方法。
因此,我目前正在使用iTextSharp生成PDF,並在表單提交時將此PDF發送回給用戶。 但是,我不想在響應流中發送此PDF,而是要提供指向文件的鏈接,即“感謝您提交,請單擊此處下載PDF”。
查看了Stack上大多數iTextSharp問題,但所有問題都與通過響應流發送有關。
謝謝
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
// Create PDF
var doc = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));
doc.Close();
byte[] docData = memoryStream.GetBuffer(); // get the generated PDF as raw data
// write the data to response stream and set appropriate headers:
Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(docData);
Response.End();
return View();
}
這完全獨立於iTextSharp。
您必須將創建的字節數組存儲在服務器上的某個位置,然后創建另一個操作以稍后通過某種ID來獲取生成的數據並將其提供給用戶。
您可以存儲在文件系統中,也可以存儲在會話或TempData中。
public ActionResult Index(FormCollection formCollection)
{
// Create PDF ...
byte[] docData = memoryStream.GetBuffer();
// create id and store data in Session
string id = Guid.NewGuid().ToString();
Session[id] = docData;
return View("Index", id);
}
在視圖Index.cshtml
,將字符串設置為模型類型,並生成下載鏈接:
@model string
@Html.ActionLink("Download pdf", "Download", "Controller", new { id = Model })
以及您的新下載操作:
public ActionResult Download(string id) {
var docData = (byte[])Session[id];
if (docData == null)
return HttpNotFound();
// clear data from session
Session[id] = null;
// a simpler way of returning binary data with mvc
return File(docData, "application/pdf", "test.pdf");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.