4

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)

  • 1
    Possible duplicate of [How can I present a file for download from an MVC controller?](http://stackoverflow.com/questions/730699/how-can-i-present-a-file-for-download-from-an-mvc-controller) – Nick Acosta Jul 02 '16 at 07:12

1 Answers1

4

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(); // Convert to byte[]

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

Ajax code to call MVC action :

function convertToPDF() {
        window.location = '/Tracker/ConvertPathInfoToPDF?pInfo=null';
    }
Yasser Bazrforoosh
  • 1,246
  • 10
  • 13