There is probably a simple answer to this question but I just can't seem to find a solution.
So I'm currently generating a PDF using iTextSharp and sending this PDF back to the user on form submit. However, instead of sending this PDF in the response stream I'd like to render a link to the file ie "Thank you for submitting, click here to download the PDF".
Looked at most iTextSharp questions on Stack but all relate to sending it via teh response stream.
Thanks
[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();
}
This is totally independent of iTextSharp.
You have to store the created byte array somewhere on your server and create another action to fetch that generated data later by some kind of an ID and serve it to the user.
You can store in in the filesystem or just in the session or 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);
}
In the view Index.cshtml
you set string as the modeltype and generate a donwload link:
@model string
@Html.ActionLink("Download pdf", "Download", "Controller", new { id = Model })
And your new download action:
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");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.