Hamed Zojaji Hamed Zojaji - 5 months ago 30
Ajax Question

How can I call an MVC action to download a PDF file?

I call an MVC action that it creates a memory PDF file. I want to return file and download immediately after finishing action.

Ajax code to call MVC action

function convertToPDF() {
$.ajax({
url: "/Tracker/ConvertPathInfoToPDF",
type: "GET",
data: JSON.stringify({ 'pInfo': null }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {

},
error: function () {
alert("Unable to call /Tracker/ConvertPathInfoToPDF");
}
});
}


MVC Action

public FileResult ConvertPathInfoToPDF(PositionInfo[] pInfo)
{
MemoryStream fs = new MemoryStream();
//FileStream fs = new FileStream(@"C:\Test.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
Rectangle rec = new Rectangle(PageSize.A4);
Document doc = new Document(rec);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
doc.Add(new Paragraph("Hamed!"));
doc.Close();

return File(fs, System.Net.Mime.MediaTypeNames.Application.Octet, "Test.pdf");
}


The MVC action is run compeletly but I receive the following error in the browser:


Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Answer

MVC Action :

public FileResult ConvertPathInfoToPDF(PositionInfo[] pInfo)
    {
        MemoryStream fs = new MemoryStream();
        Rectangle rec = new Rectangle(PageSize.A4);
        Document doc = new Document(rec);
        PdfWriter writer = PdfWriter.GetInstance(doc, fs);
        doc.Open();
        doc.Add(new Paragraph("Hamed!"));
        doc.Close();

        byte[] content = fs.ToArray();

        return File(content, "application/pdf", "Test.pdf");
    }

Ajax code to call MVC action :

function convertToPDF() {
        window.location = '/Tracker/ConvertPathInfoToPDF?pInfo=null';
    }