javascript 我想在模态窗口中显示 PDF ajax 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14153207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:50:56  来源:igfitidea点击:

I want to show PDF ajax response in a modal window

javascripthtmljquery

提问by Dinoop mathew

Using ajax I am getting the response as a PDF base64 data. Here in this example I am showing it in a new window, instead of that I want to show the PDF in a modal popup. Is there any way to do that?

使用 ajax,我将响应作为 PDF base64 数据。在这个例子中,我在一个新窗口中显示它,而不是我想在模态弹出窗口中显示 PDF。有没有办法做到这一点?

$.ajax({
        type : "POST",
        url : getPrintablePDF,
        dataType : "json",
        contentType : 'application/json; charset=utf-8',
        data : JSON.stringify(params),
        success : function(data) {
            //console.log(data);
            var myResponse = eval(data);
            window.open('data:application/pdf;base64,' + myResponse.base64EncodedResponse);

        }
    });     

回答by Praveen Kumar Purushothaman

Try using <object />or <embed />or using <iframe />

尝试使用<object /><embed />或使用<iframe />

I am giving an example with <iframe />as it is supported by all the browsers.

我举了一个例子,<iframe />因为它被所有浏览器支持。

$.ajax({
    type : "POST",
    url : getPrintablePDF,
    dataType : "json",
    contentType : 'application/json; charset=utf-8',
    data : JSON.stringify(params),
    success : function(data) {
        var myResponse = eval(data);
        $("<iframe />") // create an iframe
          // add the source
          .attr('src', 'data:application/pdf;base64,' + myResponse.base64EncodedResponse)
          .appendTo('.modal-body'); // append to modal body or wherever you want
    }
});    

回答by JustLearning

I got it to work based on this post

我根据这篇文章让它工作

You need to have a controller action that returns a file:

您需要有一个返回文件的控制器操作:

        [HttpGet]
    public async Task<ActionResult> Print(int? poId) {
        if (poId == null) {
            return Json(new { success = true, errorMessage = "Could not find purchase order!" }, JsonRequestBehavior.AllowGet);
        }

        try {
            PurchaseOrderWork dal = new PurchaseOrderWork(db);
            var db_po = await dal.GetAsyncPurchaseOrderById(poId.Value);

            var viewModel = GetEntryViewModel(db_po);
            var file = ControllerContext.GeneratePdf(viewModel, "_PrintOut");
            ViewBag.ID = poId;
            return File(file, "application/pdf");
        }
        catch (DataException ex) {
            return Json(new { success = true, errorMessage = "Failed to extract purchase order!", errorDetails = ex.Message },JsonRequestBehavior.AllowGet);
        }
    }

Then in your cshtml place an html object in your modal:

然后在你的 cshtml 中,在你的模态中放置一个 html 对象:

<div class=" container row form-horizontal">
<div id="printModal" class="modal fade in" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg print-dialog">
        <div class="modal-content print-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
                <h4 class="modal-title">Report ID = @ViewBag.ID</h4>
            </div>
            <div class="modal-body">
                <div id="detailAlert" class="alert alert-danger display-hide">
                    <button class="close" data-close="alert"></button>
                    <span>Some Errors have occured!</span>
                </div>
                <div class="form-group">
                    <object id="pdfbox" style="width: 100%; height: 800px; overflow:hidden"
                            type="application/pdf" data="@Url.Action("Print", "PurchaseOrders", new { poId=10 })"></object></object>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn green-haze btn-outline pull-left">
                    <span><i class="fa fa-fw fa-save"></i></span>&nbsp; Save
                </button>
                <button type="button" data-dismiss="modal" class="btn dark btn-outline">Close</button>
            </div>
        </div>
    </div>
</div>

Finally pass the urlto your html object:

最后传递url给你的html object

    function PrintOrder(poId) {
    var url = '/PurchaseOrders/Print?poId=' + poId;
  //  $.get(url, function (data) {
        $('#printModal').find('object').prop('data', url);
        $('#printModal').modal('show');
  //  });
}

Please comment if this code can be improved

请评论此代码是否可以改进