1.jquery生成iframe,填充html内容打印
都需要引入jquery
function toPrintView(obj)//id-str 打印区域的id
{
var newstr = $(obj).parent().parent().next().html();//打印区域
var iframe = document.createElement('IFRAME');
var doc = null;
//iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
// 引入打印的专有CSS样式,根据实际修改
doc.write("<LINK rel=\"stylesheet\" type=\"text/css\" href=\"/content/css/print.css\">");
doc.write('<div><dd>' + newstr + '</dd></div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
//判断浏览器版本号
//if (navigator.userAgent.indexOf("MSIE") > 0) {
// document.body.removeChild(iframe);
//}
document.body.removeChild(iframe);
}
该部分参照网上案例
2.页面添加iframe标签打印
<iframe id="iframeid" name="iframename" style="width:0;height:0" src="/html/views/info/contentprint.html"></iframe>
//打印
function toPrintView(obj) {
var newstr = $(obj).parent().parent().next().html();//打印区域
var iframeWindow = frames['iframename'];
var iform = $("#pcontent", iframeWindow.document.body)
iform.html("");
iform.append('<div><dd>' + newstr + '</dd></div>');
iframeWindow.document.close();
iframeWindow.focus();
iframeWindow.print();
}
contentprint.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="/content/css/print.css">/*打印内容的样式*/
</head>
<body>
<div id="pcontent"></div>
</body>
</html>
<script>
</script>