微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何调用MVC动作来下载PDF文件?

调用一个MVC动作,它创建一个内存PDF文件.我想在完成操作后立即返回文件并下载.

用于调用MVC操作的Ajax代码

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行动

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");
    }

MVC操作是完全运行但我在浏览器中收到以下错误

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

解决方法:

MVC行动:

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");
    }

用于调用MVC操作的Ajax代码

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐