[jQuery] 使用jQuery printPage plugin打印其他頁面內容
目標:
點選按鈕後可以打印其他頁面的內容,可用於套版、內部表單套印...等等。
程式碼:
1.View(HTML布局)
1 <h2>維修申請單</h2> 2 3 <form id="RepairForm"> 4 <p> 5 6 @Html.Label("dept", "申請部門") 7 <select class="DropDownList" id="dept" name="dept"></select> 8 <br /> 9 10 @Html.Label("deviceType", "設備類型") 11 <select class="DropDownList" id="deviceType" name="deviceType"></select> 12 <br /> 13 14 @Html.Label("deviceId", "設備編號") 15 <select class="DropDownList" id="deviceId" name="deviceId"></select> 16 <br /> 17 18 @Html.Label("problemType", "問題類型") 19 <select class="DropDownList" id="problemType" name="problemType"></select> 20 <br /> 21 22 @Html.Label("problemDesc", "問題描述") 23 @Html.TextArea("problemDesc") 24 <br /> 25 26 <!--<button id="btnTest" name="btnTest" type="button" onclick="test()">測試DropDownList's Value</button>--> 27 28 </p> 29 30 <input type="submit" value="提出申請" /> 31 </form> 32 33 <a class="btnPrint" id="printClick"/>
此次主角在這句<a class="btnPrint" id="printClick"/>
2.View(JavaScript)
在$(document).ready()中放入以下程式碼
1 $(document).ready(function () { 2 $(".btnPrint").printPage({ 3 message: "請稍後...打印準備中..." 4 }) 5 })
提交表單後按jQuery dialog的打印按鈕後打印/Home/About頁面
1 $("#RepairForm").submit( 2 function () { 3 $(".DropDownList").attr("disabled", false); //提交前把控件開啟才能提交 4 5 if (problemType.value == "Value") { 6 alert("Hey,你資料沒填完整!!"); 7 location.reload(); //資料寫錯就重新整理重填 8 return false; 9 } 10 11 $.post("/Repair/PostData", //接收提交的Action 12 $("#RepairForm").serialize(), //提交 13 function (result) { 14 if (result.msg == "Error") { 15 alert("Hey,你資料沒填完整!!"); 16 location.reload(); //資料寫錯就重新整理重填 17 } else { 18 19 //jQuery UI Dialog 20 var html = 21 '<div class="dialog" id="dialog-message">' + 22 ' <p>' + 23 ' <span class="ui-icon ui-icon-print" style="float: left; margin: 0 7px 0 0;"></span>' + 24 '您的申請單號為[' + result.msg + ']<br/><br/>是否現在打印?' + 25 ' </p>' + 26 '</div>'; 27 return $(html).dialog({ 28 modal: true, 29 title: "是否需要打印?", 30 buttons: { 31 "打印": function () { 32 //jQuery.printPage 33 var urlPrint = '/Home/About'; //設定打印網址 34 var obj = document.getElementById('printClick'); 35 obj.href = urlPrint; //改變打印目標 36 obj.click(); //打印 37 $(this).dialog("close"); //打印後關閉Dialog 38 } 39 40 } 41 }); 42 43 }//else 44 }, 45 "json" //接收由Controller返回的資料類型 46 ); 47 return false; //避免讓ASP.NET處理Submit($post) 48 }); //Submit
3.其餘後端Code略
運行結果:
1.提交表單彈出dialog
2.printPage開始準備文檔
3.Chrome的打印預覽
備註:
1.插件網址:http://plugins.jquery.com/printpage/
2.測試環境