【问题标题】:How to open in a new tab a PDF from Response MemoryStream如何在新选项卡中打开来自 Response MemoryStream 的 PDF
【发布时间】:2020-02-27 21:09:46
【问题描述】:

我不确定是否是这样做的好方法。我想在新的浏览器选项卡中显示 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# .net ajax asp.net-core-mvc


    【解决方案1】:

    你可以试试下面的代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 2021-12-26
      • 1970-01-01
      • 2021-12-02
      • 2019-04-12
      • 2013-12-22
      • 2017-04-28
      相关资源
      最近更新 更多