How do I open a generated pdf on a form post?
I want the user to submit a form and get a pdf back. Like you would if you just pressed a link to a pdf.
I'm going through a few steps before the pdf is generated.First I interrupt a form post with JQuery:
$("#reportForm").submit(function (event) {
event.preventDefault();
$.post("/Registry/Persons/Report", $(this).serialize(),
function (data) {
// Return the generated pdf to the browser here
});
});
The form is posted to a function called Report which takes a formcollection:
[HttpPost]
public ActionResult Report(FormCollection collection)
{
// Convert keys to list of int
var ids = collection.AllKeys.ToList().Select(s => int.Parse(s)).ToList();
List<Person> list = new List<Person>(repository.GetPersons(ids));
return GeneratePdf(list);
}
This function calls a pdf generator that returns a pdf as a MemoryStream.
public FileResult GeneratePdf(List<Person> list)
{
// Display the document
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
return File(stream.ToArray(), "application/pdf", "Resultatfil");
}
If I print the data variable into a div I get a bunch of weird characters (which I presume is the generated pdf). But how 开发者_开发技巧do I send the pdf to the browser so that I get the "open/save" file dialog?
Don't use AJAX to download files. You can't do this with AJAX. In the success callback of your ajax call you will get the results of the controller action which represents the PDF file but obviously you can't do absolutely nothing with it as due to security reasons javascript forbids you to write to the client computer. So simply use a normal form submission.
Basically you will remove your javascript and leave the form submit normally. If you want the user to be prompted to download the file simply apply the corresponding Content-Disposition
HTTP header in your controller action:
public FileResult GeneratePdf(List<Person> list)
{
// Display the document
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
Response.AppendHeader("Content-Disposition", "attachment; filename=report.pdf");
return File(stream.ToArray(), "application/pdf", "Resultatfil");
}
精彩评论