I'm trying to generate a PDF file with HTML content that's being sent via AJAX from JavaScript.
I have the HTML being sent properly, and the PDF being generated correctly using the HTML, but I'm stuck trying to figure out how to initiate the file download on the user's browser.
This is what I'm currently trying. This works in a IHttpHandler
file when hitting the URL for the file directly, but doesn't work in the ApiController
when posting via AJAX.
I've also tried posting to the IHttpHandler file with the same results. Everything works fine until I try to initiate the download by using BinaryWrite
.
public class DownloadScheduleController : ApiController
{
public void Post(HtmlModel data)
{
var htmlContent = data.html;
var pdfBytes = (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(htmlContent);
using (var mstream = new System.IO.MemoryStream())
{
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=UserSchedule.pdf");
HttpContext.Current.Response.BinaryWrite(pdfBytes);
HttpContext.Current.Response.End();
}
}
}
Here is the Ajax request. It's using Angular's $http.
$http({
method: 'POST',
url: 'api/downloadSchedule',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data
});
Alternatively I could return the PDF binary to JavaScript, but then how do I use JavaScript to save the pdf?
Any help will be greatly appreciated.