这是[查看/打印/保存 PDF] 的解决方案,它通过 MVC-ajax 调用从 byte[] 生成 PDF 模式对话框。它是由其他地方的许多其他半相关帖子构建的。有两种选择:PrintDialog1 使用 object 标签,分别为 PrintDialog2 使用 iframe 标签。
控制器 >>
[Post]
public ActionResult DoSomethingThatResultsInCreatingAPdf(CreatePaymentViewModel model)
{
byte[] pdf = DoSomethingThatResultsInCreatingAPdfByteArray();
string strPdf = System.Convert.ToBase64String(pdf);
var returnOjb = new { success = true, pdf = strPdf, errors = "" ...otherParams};
return Json(returnOjb, JsonRequestBehavior.AllowGet);
}
剃须刀页面>>
<div id="PrintPopup"></div>
<script type="text/javascript">
function DoSomethingThatResultsInCreatingAPdf(btn, event) {
event.preventDefault();
var action = '/Controller/DoSomethingThatResultsInCreatingAPdf/';
$.ajax({
url: action, type: 'POST', data: some_input_data,
success: function (result) {
if (result.success) {
PrintDialog-1or2(result.pdf);
}else{ $('#errors').html(result.errors); }
},
error: function () {}
});
}//___________________________________
function PrintDialog1(pdf) { //<object tag>
var blob = b64StrtoBlob(pdf, 'application/pdf');
var blobUrl = URL.createObjectURL(blob);
var content = String.format("<object data='{0}' class='ObjViewer'></object>", blobUrl);
$("#PrintPopup").empty();
$("#PrintPopup").html(content);
$("#PrintPopup").dialog({
open: true, modal: true, draggable: true, resizable: true, width: 800, position: { my: 'top', at: 'top+200' }, title: "PDF View, Print or Save...",
buttons : {'Close': function () { $(this).dialog('close'); }}
});
return false;
}//___________________________________
function PrintDialog2(pdf) { //<iframe tag>
var content = "<iframe src='data:application/pdf;base64," + pdf + "'></iframe>";
$("#PrintPopup").empty();
$("#PrintPopup").html(content);
$("#PrintPopup").dialog({
open: true, modal: true, draggable: true, resizable: true, width: 800, position: { my: 'top', at: 'top+200' }, title: "PDF View, Print or Save...",
buttons : {'Close': function () { $(this).dialog('close'); }}
});
return false;
}//___________________________________
String.format = function () {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}//___________________________________
function b64StrtoBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}//___________________________________