首页 > 解决方案 > 如何在新选项卡中打开来自 Response MemoryStream 的 PDF

问题描述

我不确定是否是这样做的好方法。我想在新的浏览器选项卡中显示 PDF。

我有一个生成 MemoryStream 并返回到我的 ajax 调用的方法。这样做的好方法是什么?

我的 Ajax 调用:

$("#selector").click(function () {
    urlToFunction = "/Controller/Function";
    $.ajax({
        url: urlToFunction,
        data: ({ id: 12345 }),
        type: 'GET',
        success: function (response) {
           ???? here
        },
        error:
            function (response) {
            }
    });   
});

[HttpGet]
        public async Task Print(int? id)
        {

            var ms = GETMemoryStreamPDF();

            Response.ContentType = "application/pdf; charset=utf-8";
            Response.Headers.Add("content-disposition", "attachment;filename=" + randomName + ".pdf;charset=utf-8'");            
            await Response.Body.WriteAsync(ms.GetBuffer(), 0, ms.GetBuffer().Length);            
        }

我的问题在这里:

success: function (response) {
           ???? here
        },

在新选项卡中显示我的 PDF 的最佳做法是什么?

标签: c#.netajaxasp.net-core-mvc

解决方案


您可以尝试以下代码:

Javascript

$("#selector").click(function (e) {
    e.preventDefault();
    window.open('@Url.Action("ActionName", "ControllerName", new { id=12345})', '_blank');

});

控制器

    [HttpGet]
    public IActionResult Pdf(int? id)
    {
        MemoryStream memoryStream = new MemoryStream();

        PdfWriter pdfWriter = new PdfWriter(memoryStream);

        PdfDocument pdfDocument = new PdfDocument(pdfWriter);

        Document document = new Document(pdfDocument);
        document.Add(new Paragraph("Welcome"));
        document.Close();

        byte[] file = memoryStream.ToArray();
        MemoryStream ms = new MemoryStream();
        ms.Write(file, 0, file.Length);
        ms.Position = 0;

        return File(fileStream: ms, contentType: "application/pdf", fileDownloadName: "test_file_name" + ".pdf");
    }

推荐阅读