利用jquery jqprint进行web打印
2020-12-01 16:00:41
默认的网页打印效果不尽如人意,很多时候只需要打印网页上的一部分内容,这个时候需要jquery jqprint上场
关键代码如下:
<link href="printStyle.css" rel="stylesheet"type="text/css" media="print">
<script src="jquery.jqprint-0.3.js"></script>
function onprint() {
$(".main-container").jqprint();
}
高版本jquery加载这个会报错:CANNOT READ PROPERTY ‘opera’ OF UNDEFINED.
原因:
$.browser这个方法从1.9开始废除
加入如下代码(确保位于引入jQuery文件后,$.browser前)
<script>
jQuery.browser={};
(function(){
jQuery.browser.msie=false;
jQuery.browser.version=0;
if(navigator.userAgent.match(/MSIE ([0-9]+)./)){
jQuery.browser.msie=true;
jQuery.browser.version=RegExp.$1;
}
})();
</script>
或者直接修改jquery.jqprint-0.3.js源代码即可
附上本文用到的几个文件
printStyle.css
@page
{
size: auto; /* auto is the initial value */
margin: 0mm 10mm 0mm 10mm; /* this affects the margin in the printer settings 最关键的还是这个,去除页眉页脚*/
}
body
{
background-color:#FFFFFF;
margin: 0mm; /* this affects the margin on the content before sending to printer */
padding: 5mm 0 5mm 0 ;
}
jquery.jqprint-0.3.js
(function($){var opt;$.fn.jqprint=function(options){opt=$.extend({},$.fn.jqprint.defaults,options);var $element=(this instanceof jQuery)?this:$(this);if(opt.operaSupport&&$.browser.opera)
{var tab=window.open("","jqPrint-preview");tab.document.open();var doc=tab.document;}
else
{var $iframe=$("<iframe />");if(!opt.debug){$iframe.css({position:"absolute",width:"0px",height:"0px",left:"-600px",top:"-600px"});}
$iframe.appendTo("body");var doc=$iframe[0].contentWindow.document;}
if(opt.importCSS)
{if($("link[media=print]").length>0)
{$("link[media=print]").each(function(){doc.write("<link type='text/css' rel='stylesheet' href='"+$(this).attr("href")+"' media='print' />");});}
else
{$("link").each(function(){doc.write("<link type='text/css' rel='stylesheet' href='"+$(this).attr("href")+"' />");});}}
if(opt.printContainer){doc.write($element.outer());}
else{$element.each(function(){doc.write($(this).html());});}
doc.close();(opt.operaSupport&&$.browser.opera?tab:$iframe[0].contentWindow).focus();setTimeout(function(){(opt.operaSupport&&$.browser.opera?tab:$iframe[0].contentWindow).print();if(tab){tab.close();}},1000);}
$.fn.jqprint.defaults={debug:false,importCSS:true,printContainer:true,operaSupport:true};jQuery.fn.outer=function(){return $($('<div></div>').html(this.clone())).html();}})(jQuery);
jQuery.browser={};
(function(){
jQuery.browser.msie=false;
jQuery.browser.version=0;
if(navigator.userAgent.match(/MSIE ([0-9]+)./)){
jQuery.browser.msie=true;
jQuery.browser.version=RegExp.$1;
}
})();