I am using this method to return a PDF file. It works normal if I call this action directly via URL:
public ActionResult GerarProva(int idEpo, int numero, bool existeProvaGerada)
{
try
{
var relatorioBll = new RelatorioBll();
var dados = relatorioBll.ObterQuestoesProva(numero, idEpo, existeProvaGerada);
_dadosGeracaoProva = dados;
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.AddHeader("content-disposition",
"attachment;filename=" + ControllerContext.RouteData.Values["action"] + DateTime.Now.ToFileTime() +
".pdf");
System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Stream pdfStream = System.Web.HttpContext.Current.Response.OutputStream;
GerarPdf<ProvaItem>.GerarProva(pdfStream, dados.ToList());
System.Web.HttpContext.Current.Response.Write(dados);
System.Web.HttpContext.Current.Response.End();
return File(System.Web.HttpContext.Current.Response.OutputStream, "application/pdf");
}
catch (Exception ex)
{
Danger("Erro: " + ex.Message);
}
return RedirectToAction("Index");
}
But I would like to download the file through ajax. I need to perform a javascript action within the "success":
$.ajax({
url: link,
success: function (data) {
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Preview.pdf";
link.click();
},
error: function (err, er, e) {
if (err.responseText.indexOf("encontradas") === -1) {
alert("Erro.");
} else {
alert("Erro: Não foram encontradas questões válidas para a geração da prova.");
}
}
});
I tried this code, but the pdf comes with blank pages. One of my assumptions is that my server side method is not returning the correct type ...