我们做网站,经常需要打印页面指定区域的内容,而网上关于这块的说法很多,各种各样的打印控件也不少。但许多打印方案都不怎么好,至少我不喜欢,要么封装复杂,要么难以维护。正好现在的项目也需要用到页面打印,于是在网上找了一个最简洁的打印插件,在它的基础上自己写了一个通用的打印方法,可以直观的修改样式。现在把代码贴出来,留置后用,也可以给大家一些参考。

通过这次试水,才知道,原来html中,media元素大有用途,这里正好小用一把,去掉超链接的url显示

1.网上找的js打印插件

/*
* Version 2.4.0 Copyright (C) 2013
* Tested in IE 11, FF 28.0 and Chrome 33.0.1750.154
* No official support for other browsers, but will TRY to accommodate challenges in other browsers.
* Example:
* Print Button: <div id="print_button">Print</div>
* Print Area : <div class="PrintArea" id="MyId" class="MyClass"> ... html ... </div>
* Javascript : <script>
* $("div#print_button").click(function(){
* $("div.PrintArea").printArea( [OPTIONS] );
* });
* </script>
* options are passed as json (example: {mode: "popup", popClose: false})
*
* {OPTIONS} | [type] | (default), values | Explanation
* --------- | --------- | ---------------------- | -----------
* @mode | [string] | (iframe),popup | printable window is either iframe or browser popup
* @popHt | [number] | (500) | popup window height
* @popWd | [number] | (400) | popup window width
* @popX | [number] | (500) | popup window screen X position
* @popY | [number] | (500) | popup window screen Y position
* @popTitle | [string] | ('') | popup window title element
* @popClose | [boolean] | (false),true | popup window close after printing
* @extraCss | [string] | ('') | comma separated list of extra css to include
* @retainAttr | [string[]] | ["id","class","style"] | string array of attributes to retain for the containment area. (ie: id, style, class)
* @standard | [string] | strict, loose, (html5) | Only for popup. For html 4.01, strict or loose document standard, or html 5 standard
* @extraHead | [string] | ('') | comma separated list of extra elements to be appended to the head tag
*/
(function($) {
var counter = 0;
var modes = { iframe : "iframe", popup : "popup" };
var standards = { strict : "strict", loose : "loose", html5 : "html5" };
var defaults = {
mode : modes.iframe,
standard : standards.html5,
popHt : 500,
popWd : 400,
popX : 200,
popY : 200,
popTitle : '',
popClose : false,
extraCss : '',
extraHead : '',
retainAttr: ["id", "class", "style"]
};
var settings = {};//global settings
$.fn.printArea = function( options )
{
$.extend( settings, defaults, options );
counter++;
var idPrefix = "printArea_";
$( "[id^=" + idPrefix + "]" ).remove();
settings.id = idPrefix + counter;
var $printSource = $(this);
var PrintAreaWindow = PrintArea.getPrintWindow();
PrintArea.write( PrintAreaWindow.doc, $printSource );
setTimeout( function () { PrintArea.print( PrintAreaWindow ); }, 1000 );
}; var PrintArea = {
print : function( PAWindow ) {
var paWindow = PAWindow.win;
$(PAWindow.doc).ready(function(){
paWindow.focus();
paWindow.print();
if ( settings.mode == modes.popup && settings.popClose )
setTimeout(function() { paWindow.close(); }, 2000);
});
},
write : function ( PADocument, $ele ) {
PADocument.open();
PADocument.write( PrintArea.docType() + "<html>" + PrintArea.getHead() + PrintArea.getBody( $ele ) + "</html>" );
PADocument.close();
},
docType : function() {
if ( settings.mode == modes.iframe ) return ""; if ( settings.standard == standards.html5 ) return "<!DOCTYPE html>"; var transitional = settings.standard == standards.loose ? " Transitional" : "";
var dtd = settings.standard == standards.loose ? "loose" : "strict";
return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' + transitional + '//EN" "http://www.w3.org/TR/html4/' + dtd + '.dtd">';
},
getHead : function() {
var extraHead = "";
var links = "";
var styles = ''; if ( settings.extraHead ) settings.extraHead.replace( /([^,]+)/g, function(m){ extraHead += m });
$(document).find("link")
.filter(function () { // Requirement: <link> element MUST have rel="stylesheet" to be considered in print document
var relAttr = $(this).attr("rel");
return ($.type(relAttr) === 'undefined') == false && relAttr.toLowerCase() == 'stylesheet';
})
.filter(function () { // Include if media is undefined, empty, print or all
var mediaAttr = $(this).attr("media");
return $.type(mediaAttr) === 'undefined' || mediaAttr == "" || mediaAttr.toLowerCase() == 'print' || mediaAttr.toLowerCase() == 'all'
})
.each(function () {
links += '<link type="text/css" rel="stylesheet" media="print" href="' + $(this).attr("href") + '" />';
styles += '@import url("' + $(this).attr("href") + '") print;';
});
if ( settings.extraCss ) settings.extraCss.replace( /([^,\s]+)/g, function(m){ links += '<link type="text/css" rel="stylesheet" href="' + m + '">' });
return '<head><title>' + settings.popTitle + '</title>' + extraHead + links + '<style type="text/css"> @media print{a:link:after {content: ""}}</style></head>';
//return "<head><title>" + settings.popTitle + "</title>" + extraHead + links + "</head>";
},
getBody : function ( elements ) {
var htm = "";
var attrs = settings.retainAttr;
elements.each(function() {
var ele = PrintArea.getFormData( $(this) );
var attributes = ""
for ( var x = 0; x < attrs.length; x++ )
{
var eleAttr = $(ele).attr( attrs[x] );
if ( eleAttr ) attributes += (attributes.length > 0 ? " ":"") + attrs[x] + "='" + eleAttr + "'";
}
htm += '<div ' + attributes + '>' + $(ele).html() + '</div>';
});
return "<body>" + htm + "</body>";
},
getFormData : function ( ele ) {
var copy = ele.clone();
var copiedInputs = $("input,select,textarea", copy);
$("input,select,textarea", ele).each(function( i ){
var typeInput = $(this).attr("type");
if ($.type(typeInput) === 'undefined') typeInput = $(this).is("select") ? "select" : $(this).is("textarea") ? "textarea" : "";
var copiedInput = copiedInputs.eq( i );
if ( typeInput == "radio" || typeInput == "checkbox" ) copiedInput.attr( "checked", $(this).is(":checked") );
else if ( typeInput == "text" ) copiedInput.attr( "value", $(this).val() );
else if ( typeInput == "select" )
$(this).find( "option" ).each( function( i ) {
if ( $(this).is(":selected") ) $("option", copiedInput).eq( i ).attr( "selected", true );
});
else if ( typeInput == "textarea" ) copiedInput.text( $(this).val() );
});
return copy;
},
getPrintWindow : function () {
switch ( settings.mode )
{
case modes.iframe :
var f = new PrintArea.Iframe();
return { win : f.contentWindow || f, doc : f.doc };
case modes.popup :
var p = new PrintArea.Popup();
return { win : p, doc : p.doc };
}
},
Iframe : function () {
var frameId = settings.id;
var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;right:0px;top:0px;';
var iframe;
try
{
iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).attr({ style: iframeStyle, id: frameId, src: "#" + new Date().getTime() });
iframe.doc = null;
iframe.doc = iframe.contentDocument ? iframe.contentDocument : ( iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
}
catch( e ) { throw e + ". iframes may not be supported in this browser."; }
if ( iframe.doc == null ) throw "Cannot find document.";
return iframe;
},
Popup : function () {
var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=yes";
var newWin = window.open( "", "_blank", windowAttr );
newWin.doc = newWin.document;
return newWin;
}
};
})(jQuery);

2. 我的调用方法

function printArticle(areaId) {
var styles = ".PrintStyleBtn{border:none;width:100%;;height:40px;line-height:40px;background-color:#eee;} .PrintStyleBtn input{ border-radius:5px;background-color:#999;color:#fff;float:right;margin:8px;height:24px;line-height:16px;padding:0px 5px;}.selected{background-color:#ccc;} .PrintStyleBtn span{margin:3px 0px;display:inline-block;border-radius:3px;height:24px;line-height:20px;padding:2px 5px;}.PrintStyleBtn span:hover{background-color:#999;} .print_content{border:1px solid #ddd;width:800px;height:auto;padding:20px;margin:50px auto;}";
insertStyleSheet(styles, "PrintStyle");
var printFrameHtml =
'<div id="PrintFrame" style="border:none;width:100%;height:100%;position:absolute;top:0;left:0;background-color:#fff;">'
+ '<div class="PrintStyleBtn" style="">'
+ ' Font size:'
+ ' <span name="size">Small</span> |'
+ ' <span name="size" class="selected">Medium</span> |'
+ ' <span name="size">Large</span>    '
+ ' Line spacing:'
+ ' <span name="space">Compact</span> |'
+ ' <span name="space" class="selected">Normal</span>    '
+ ' Image:'
+ ' <span name="image" class="selected">Yes</span> |'
+ ' <span name="image">No</span>    '
+ ' <input id="btnCancel" type="button" value="Cancel"/>'
+ ' <input id="btnPrint" type="button" value="Print" />'
+ '</div>'
+ '<div class="print_content">' + $('#' + areaId).html() + '</div></div>';
$("body").append(printFrameHtml);
$('.print_content').find(".viva-content-edit").remove();
$('.PrintStyleBtn').find('span').on('click', function () {
var obj = $(this),
name = obj.attr('name'),
value = obj.html();
$('.PrintStyleBtn').find('span[name="' + name + '"]').removeClass('selected');
obj.addClass('selected');
if (name == 'size')
$('.print_content').css('font-size', value == 'Small' ? 'small' : value == 'Medium' ? 'medium' : 'large' );
if (name == 'space')
$('.print_content').css('line-height', value == 'Compact' ? '1' : 'normal');
if (name == 'image') {
if (value == "Yes") {
$('.print_content').find("img").show();
} else {
$('.print_content').find("img").hide();
}
}
});
$('.PrintStyleBtn').find('input').on('click', function () {
if (this.value == 'Print') {
$('.print_content').printArea();
}
$('#PrintFrame').remove();
});
}

3.附带页面sample

<input type="button" onclick="printArticle('articleRight');" value='Print' />
<div id="articleRight">
<div class="article-title">Test Article Tilte</div>
<div class="article-content">Test Article Content</div>
</div>

js灵活打印web页面区域内容的通用方法的更多相关文章

  1. js打印WEB页面内容代码大全

    第一种方法:指定不打印区域 使用CSS,定义一个.noprint的class,将不打印的内容放入这个class内. 详细如下: <style media=print type="tex ...

  2. 打印web页面指定区域的三种方法

    本文和大家分享一下web页面实现指定区域打印功能的三种方法,一起来看下吧. 第一种方法:使用CSS 定义一 个.noprint的class,将不打印的内容放入这个class内. 代码如下: <s ...

  3. js打印div指定区域内容

    <script> function myPrint(obj){ var newWindow=window.open("打印窗口","_blank") ...

  4. PHP关于web页面交互内容

    学php学了有一段时间了总结总结给大家分享一下 PHP中的引用 第一段程序: <?php $first_name="firstName"; $first=&$firs ...

  5. WEB页面下载内容导出excel

    internal class DownloadHandler : IDownloadHandler    {        public DownloadHandler()        {      ...

  6. 论一种基于JS技术的WEB前端动态生成框图的方法

    前言 HTML是一种标记语言,由HTML的标签元素和文本编写的文档可被浏览器描述为一幅网页.通常情况下网页的实现是由HTML.CSS和Javascript三者结合完成的,HTML负责网页的结构,CSS ...

  7. 【原】移动web页面给用户发送邮件的方法 (邮件含文本、图片、链接)

    微信商户通有这么一个需求,用户打开H5页面后,引导用户到电脑下载设计资源包,由于各种内部原因,被告知无后台资源支持,自己折腾了一段时间找了下面2个办法,简单做下笔记. 使用mailto功能,让用户自己 ...

  8. 移动web页面给用户发送邮件的方法

    微信商户通有这么一个需求,用户打开H5页面后,引导用户到电脑下载设计资源包,由于各种内部原因,被告知无后台资源支持,自己折腾了一段时间找了下面2个办法,简单做下笔记. 使用mailto功能,让用户自己 ...

  9. js实现在当前页面搜索高亮显示字的方法

    在html页面上,有时候会遇到一些检索高亮显示的问题,具体用js是实现的方式,代码展示. Jsp页面设置方式 <li class="pull-left" id="s ...

随机推荐

  1. LeetCode 【47. Permutations II】

    Given a collection of numbers that might contain duplicates, return all possible unique permutations ...

  2. 如何清除某条SQL的执行计划

    如果遇到绑定窥探导致执行计划慢的情况,想要清除某条SQL的执行计划,让它硬解析,找了很久都没有找到直接操作share pool的方法(除非alter system flush shared_pool) ...

  3. 10、java中的抽象类

    当多个类中出现相同功能,但是功能主体不同,这是可以进行向上抽取.这时,只抽取功能定义,而不抽取功能主体. 抽象:看不懂. 抽象类的特点:1,抽象方法一定在抽象类中.2,抽象方法和抽象类都必须被abst ...

  4. overload, override和overwrite之间的区别

    Overload.Overwrite和Override的概念比较容易混淆,而且Overwrite和Override的中文翻译五花八门,让人很Confuse,顾保持英文原意: Overload  重载 ...

  5. 面对一个新的MCU,我再也不敢说第一步是点灯了

    折腾了几天AT91SAM3S,今天才算是把开发板上的3个LED点亮. 在点亮之前,起码看了百八十页的Datasheet,动用了N次百度. 各种时钟,看门狗,分散加载,中断向量,都得去整.这些都远远超过 ...

  6. CSAPP(前言)

    很久之前就听过有过CSAPP这本书的传闻了,今天终于决定上手这本神作:既然是神作,就要仔细拜读一下,今天看了一下前言部分还真的令人耳目一新,单单是前言部分就让我学习到几个新的知识点: 1.c和Java ...

  7. oracle两列相同的去重

    源地址:https://zhidao.baidu.com/question/66722841.html 1.不含大字段(clob等)的表格: 1 2 3 4 5 6 7 8 9 --例子表格:crea ...

  8. 【知识点】业务连接服务(BCS)认证概念整理

    业务连接服务(BCS)认证概念整理 I. BDC认证模型 BDC服务支持两种认证模型:信任的子系统,模拟和代理. 在信任的子系统模型中,中间层(通常是Web服务器)通过一个固定的身份来向后端服务器取得 ...

  9. AS3下如何来判断XML属性的是否存在

    在as3中判断xml节点是否存在可用XMLList中的方法:hasOwnProperty(p:String):Boolean. 但是判断xml节点是否存在某一属性,对象中好像没有该方法,只能用unde ...

  10. JAVA设计模式之访问者模式

    在阎宏博士的<JAVA与模式>一书中开头是这样描述访问者(Visitor)模式的: 访问者模式是对象的行为模式.访问者模式的目的是封装一些施加于某种数据结构元素之上的操作.一旦这些操作需要 ...