I have created an ASP.NET MVC web app in which I accept some information from the client via an AJAX post and create a pdf using iTextSharp. On returning a response to the client, I would like the browser to automatically download the pdf on the user's computer. I began by actually saving the file to a folder and returning the absolute path, so I know the code generates the pdf successfully. Instead of returning the actual path, though, I have read that I can instead store it in a MemoryStream and put that in my response. I have tried returning the actual MemoryStream, converting it to a byte array and returning that, returning a FileStreamResult, and adding the MemoryStream to the Response, but nothing seems to be working. I know similar questions have been asked, but none of the code I have found seems to solve my problem. Can someone please tell me what I need to change in my code to accomplish this, please?
AJAX code:
.ajax({
url: "/Reports/GenShoppingList",
type: "Post",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(recipeIdArray),
datatype: "application/pdf"
});
Pdf Creation and Response code:
public static void GenShoppingListPDF(StringBuilder ingredientNames)
{
MemoryStream MemoryStream = new MemoryStream();
doc = new Document();
PdfWriter.GetInstance(doc, MemoryStream).CloseStream = false;
doc.Open();
doc.Add(new Paragraph(ingredientNames.ToString()));
doc.Close();
string fileName = "ShoppingList-" + DateTime.Now.ToString() + ".pdf";
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
response.BinaryWrite(MemoryStream.ToArray());
response.Flush();
response.Close();
response.End();
}
The StringBuilder object is passed into the code via a controller action that simply creates the object and calls this static method. The controller action return type is void.
Final Solution: Through further research and discussion, I have concluded that JQuery AJAX does not support posting data and returning a pdf. Rather, it is best to simply use a plain XMLHttpRequest and forego using JQUERY.