简体   繁体   English

如何在新选项卡中打开来自 Response MemoryStream 的 PDF

[英]How to open in a new tab a PDF from Response MemoryStream

I'm not sure if is the good way to do that.我不确定是否是这样做的好方法。 I want to show a PDF in a new browser tab.我想在新的浏览器选项卡中显示 PDF。

I have a method who generate a MemoryStream and return to my ajax call.我有一个生成 MemoryStream 并返回到我的 ajax 调用的方法。 What is the good way procedure to do that?这样做的好方法是什么?

my Ajax Call:我的 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);            
        }

My question is here:我的问题在这里:

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

what is the good practice to display my PDF in a new tab?在新选项卡中显示我的 PDF 的好做法是什么?

You could try the following code:你可以试试下面的代码:

Javascript Javascript

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

});

Controller控制器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM