How can I trigger an MVC action to load a PDF file?

I invoke an MVC action that creates a PDF file in memory. I want to return the file and download immediately after the action completes.

Ajax code for invoking an 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 successful, but I get the following error in the browser:

Failed to load resource: server responded with status 500 (Internal server error)

+4
source share
1 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(); // Convert to byte[]

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

Ajax code for invoking an MVC action:

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

All Articles