【问题标题】:Display PDF stream returned from controller in new window在新窗口中显示从控制器返回的 PDF 流
【发布时间】:2023-03-22 07:40:01
【问题描述】:

我正在处理一个项目,我需要在新选项卡中显示 pdf,我有一个控制器,它从报告服务获取 pdf 作为 byte[]

var data = Search(search_info);
var stream = new MemoryStream(data, 0, data.Length, true, true);    
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "filename=\"\"" + "caseoverview" + ".pdf" + "");
Response.ContentType = MimeTypes.ApplicationPdf;
Response.OutputStream.Write(data1, 0, Convert.ToInt32(stream.Length));
Response.Flush();
return new FileStreamResult(stream, "application/pdf");

我正在使用 Ajax 调用控制器:

@using (Ajax.BeginForm("Search", "Controller", null,
            new AjaxOptions
            {
                HttpMethod = "post",
                OnComplete = "OnCompleteMethod",
                OnFailure = "OnFailtureMethod"
            }))
        {

            <div id="query-filter" class="filters">
                @Html.Partial("QueryFilter", Model)
            </div>
            <div class="row">
                <div class="col-md-2 col-sm-6 col-md-offset-8">
                    <button class="btn btn-submit btn-block" type="submit">Find</button>
                </div>
                <div class="col-md-2 col-sm-6">
                    <button class="btn btn-submit btn-block" type="reset">Reset</button>
                </div>
            </div>
        }

成功方法的javascript是:

function OnCompleteMethod(dataq, status) {
    if (status === "success") {

        var w = window.open("data:application/pdf, " + escape(dataq.responseText));
        w.document.write(dataq.responseText);
        w.document.close();
}
}

这就是我在新标签中得到的:

有人可以帮我解决这个问题,并向我解释我做错了什么或解决方案中缺少什么。

非常感谢。

【问题讨论】:

    标签: javascript ajax pdf view


    【解决方案1】:

    我用不同的方法解决了这个问题,而不是使用 Ajax 调用,我只做了这个 javascript 函数:

    function reportPrinter() {
    var myParamether= $('#paramether').val();
    window.open('/MyController/ReportPrinterMethod?report=reportview&paramether=' + myParamether, 'ReportView', '');
    

    }

    在控制器中我改变了这种方法的方法:

     [HttpGet]
        public ActionResult ReportPrinterMethod(string myParamether)
        {
            if (!ModelState.IsValid) return View();
    
            var data = GetDataReport(myParamether); //Return a byte[] with the pdf content.
    
            Response.AddHeader("Content-Disposition", "filename=\"\"" + "reportview" + ".pdf" + "");
            Response.ContentType = "application/pdf";
            Response.OutputStream.Write(data, 0, Convert.ToInt32(data.Length));
            Response.Flush();
            Response.Close();
            return View();
        }
    

    这就解决了问题。

    【讨论】:

    • 我有几乎相同的问题,但我需要在模式弹出窗口中打开 pdf。这将在新的浏览器窗口中打开它。我试图更改操作以返回部分视图,但这不起作用。有没有办法让javascript在同一页面上打开文件?
    猜你喜欢
    • 2016-09-15
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多