使用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);
}
});
答案 0 :(得分:5)
<object />
或<embed />
或使用<iframe />
我正在提供<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
}
});
答案 1 :(得分:0)
我根据这个post
开始工作您需要有一个返回文件的控制器操作:
[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);
}
}
然后在你的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> Save
</button>
<button type="button" data-dismiss="modal" class="btn dark btn-outline">Close</button>
</div>
</div>
</div>
</div>
最后将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');
// });
}
如果可以改进此代码,请发表评论