Fix for printing on Internet Explorer

This commit is contained in:
Sathvik P
2013-05-20 11:36:51 +05:30
parent b5192e060a
commit 735ed54a08
6 changed files with 268 additions and 113 deletions
+7 -5
View File
@@ -5,7 +5,7 @@ jQuery.print is a plugin for printing specific parts of a page
## Usage
Include it in your HTML after importing jQuery, like:
<script type="text/JavaScript" src="./js/libs/jquery.print.js" />
<script type="text/JavaScript" src="path/to/jquery.print.js" />
Use it like:
@@ -71,18 +71,20 @@ Currently this plugin supports the following options:
- Acceptable-Values: Any valid `jQuery-selector` or HTML-text
- Function: Adds custom HTML before (prepend) or after (append) the selected content
## Tested on
## Tested with
### jQuery
* [jQuery](http://jquery.com/) v. 1.7.2
* [jQuery](http://jquery.com/) v. 1.9.1
### Browser Support (tested versions)
* Google Chrome - v 20
### Browsers
* Google Chrome - v 20, 26
* Internet Explorer - v 10
## License
[CC-BY](http://creativecommons.org/licenses/by/3.0/).
## Live at
## Demo
[jsFiddle](http://jsfiddle.net/5V24U/27/)
---------------------------------------
+2
View File
@@ -0,0 +1,2 @@
/*! normalize.css v1.1.0 | MIT License | git.io/normalize */
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}html,button,input,select,textarea{font-family:sans-serif}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{font-size:2em;margin:.67em 0}h2{font-size:1.5em;margin:.83em 0}h3{font-size:1.17em;margin:1em 0}h4{font-size:1em;margin:1.33em 0}h5{font-size:.83em;margin:1.67em 0}h6{font-size:.67em;margin:2.33em 0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}blockquote{margin:1em 40px}dfn{font-style:italic}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}mark{background:#ff0;color:#000}p,pre{margin:1em 0}code,kbd,pre,samp{font-family:monospace,serif;_font-family:'courier new',monospace;font-size:1em}pre{white-space:pre;white-space:pre-wrap;word-wrap:break-word}q{quotes:none}q:before,q:after{content:'';content:none}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}dl,menu,ol,ul{margin:1em 0}dd{margin:0 0 0 40px}menu,ol,ul{padding:0 0 0 40px}nav ul,nav ol{list-style:none;list-style-image:none}img{border:0;-ms-interpolation-mode:bicubic}svg:not(:root){overflow:hidden}figure{margin:0}form{margin:0}fieldset{border:1px solid #c0c0c0;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0;white-space:normal;*margin-left:-7px}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;*overflow:visible}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0;*height:13px;*width:13px}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}
+128
View File
@@ -0,0 +1,128 @@
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>jQuery.Print</title>
<meta name="description" content="jQuery.print is a plugin for printing specific parts of a page">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/normalize.min.css">
<style type='text/css'>
.a {
background: black;
color: white;
}
.b {
color: #aaa;
}
</style>
<!--[if lt IE 9]>
<script src="js/vendor/html5-3.6-respond-1.1.0.min.js"></script>
<![endif]-->
</head>
<body>
<!--[if lt IE 9]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
<![endif]-->
<div id="content_holder">
<div id="ele1" class="a">
<h3>Element 1</h3>
<p>
Some random text.
</p>
<button class="print-link" onclick="$('#ele1').print()">
Print this
</button>
</div>
<div id="ele2" class="b">
<h3>Element 2</h3>
<p>
Some other random text.
</p>
<button class="print-link no-print">
Print this
</button>
</div>
<div id="ele3" class="a">
<h3>Element 3</h3>
<p class="no-print">
Some more random text.
</p>
<button class="print-link" onclick="$.print('#ele3')">
Print this
</button>
</div>
<div id="ele4" class="b">
<h3 class='avoid-this'>Element 4</h3>
<p>
Some really random text.
</p>
<button class="print-link">
Print this
</button>
</div>
<br/>
<button class="print-link" onclick="$.print()">
Print page
</button>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')
</script>
<script src="../jQuery.print.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(function() {
$("#ele2").find('.print-link').on('click', function() {
//Print ele2 with default options
$.print("#ele2");
});
$("#ele4").find('button').on('click', function() {
//Print ele4 with custom options
$("#ele4").print({
//Use Global styles
globalStyles : false,
//Add link with attrbute media=print
mediaPrint : false,
//Custom stylesheet
stylesheet : "http://fonts.googleapis.com/css?family=Inconsolata",
//Print in a hidden iframe
iframe : false,
//Don't print this
noPrintSelector : ".avoid-this",
//Add this on top
append : "Hello World!!!<br/>",
//Add this at bottom
prepend : "<br/>Buh Bye!"
});
});
// Fork https://github.com/sathvikp/jQuery.print for the full list of options
});
//]]>
</script>
</body>
</html>
+12
View File
@@ -0,0 +1,12 @@
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}</style>";
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment();
for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='&shy;<style media="'+h+'"> #mq-test-1 { width: 42px; }</style>';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document);
/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B<y;B++){A=D[B],z=A.href,C=A.media,x=A.rel&&A.rel.toLowerCase()==="stylesheet";if(!!z&&x&&!o[z]){if(A.styleSheet&&A.styleSheet.rawCssText){m(A.styleSheet.rawCssText,z,C);o[z]=true}else{if((!/^([a-zA-Z:]*\/\/)/.test(z)&&!g)||z.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:z,media:C})}}}}u()},u=function(){if(d.length){var x=d.shift();n(x.href,function(y){m(y,x.href,x.media);o[x.href]=true;u()})}},m=function(I,x,z){var G=I.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),J=G&&G.length||0,x=x.substring(0,x.lastIndexOf("/")),y=function(K){return K.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+x+"$2$3")},A=!J&&z,D=0,C,E,F,B,H;if(x.length){x+="/"}if(A){J=1}for(;D<J;D++){C=0;if(A){E=z;k.push(y(I))}else{E=G[D].match(/@media *([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&y(RegExp.$2))}B=E.split(",");H=B.length;for(;C<H;C++){F=B[C];i.push({media:F.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/)&&RegExp.$2||"all",rules:k.length-1,hasquery:F.indexOf("(")>-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l<h){clearTimeout(r);r=setTimeout(j,h);return}else{l=z}for(var E in i){var K=i[E],C=K.minw,J=K.maxw,A=C===null,L=J===null,y="em";if(!!C){C=parseFloat(C)*(C.indexOf(y)>-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this);
File diff suppressed because one or more lines are too long
+114 -108
View File
@@ -1,121 +1,127 @@
/* jQuery.print, version 1.01
* (c) Sathvik Ponangi
/* jQuery.print, version 1.0.2
* (c) Sathvik Ponangi, Doers' Guild
* Licence: CC-By (http://creativecommons.org/licenses/by/3.0/)
*--------------------------------------------------------------------------*/
(function($) {
// A nice closure for our definitions
(function($) {"use strict";
// A nice closure for our definitions
$.print = $.fn.print = function() {
// Print a given set of elements
$.print = $.fn.print = function() {
// Print a given set of elements
var isNode = function(o) {
/* http://stackoverflow.com/a/384380/937891 */
return (typeof Node === "object" ? o instanceof Node : o
&& typeof o === "object" && typeof o.nodeType === "number"
&& typeof o.nodeName === "string");
}
var isNode = function(o) {
/* http://stackoverflow.com/a/384380/937891 */
return ( typeof Node === "object" ? o instanceof Node : o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string");
}
var options, $this;
var options, $this;
if (isNode(this)) {
// If `this` is a HTML element, i.e. for
// $(selector).print()
$this = $(this);
} else {
if (arguments.length > 0) {
// $.print(selector,options)
$this = $(arguments[0]);
if (isNode($this[0])) {
if (arguments.length > 1) {
options = arguments[1];
}
} else {
// $.print(options)
options = arguments[0];
$this = $(this);
}
} else {
// $.print()
$this = $(this);
}
}
if (isNode(this)) {
// If `this` is a HTML element, i.e. for
// $(selector).print()
$this = $(this);
} else {
if (arguments.length > 0) {
// $.print(selector,options)
$this = $(arguments[0]);
if (isNode($this[0])) {
if (arguments.length > 1) {
options = arguments[1];
}
} else {
// $.print(options)
options = arguments[0];
$this = $(this);
}
} else {
// $.print()
$this = $(this);
}
}
var defaults = {
globalStyles : true,
mediaPrint : false,
stylesheet : null,
rejectWindow : true,
noPrintSelector : ".no-print",
iframe : true,
append : null,
prepend : null
};
// Default options
options = $.extend(defaults, options);
// Merge with user-options
var defaults = {
globalStyles : true,
mediaPrint:false,
stylesheet : null,
rejectWindow : true,
noPrintSelector : ".no-print",
iframe : true,
append : null,
prepend : null
}; // Default options
options = $.extend(defaults, options); // Merge with user-options
if (options.rejectWindow && $this[0] === window) {
// Use document instead of window as it holds all HTML
$this = $(document);
}
if (options.rejectWindow && $this[0] === window) {
// Use document instead of window as it holds all HTML
$this = $(document);
}
var styles = $("");
if (options.globalStyles) {
// Apply the stlyes from the current sheet to the printed page
styles = $("style, link, meta, title");
} else if (options.mediaPrint) {
// Apply the media-print stylesheet
styles = $("link[media=print]");
}
if (options.stylesheet) {
// Add a custom stylesheet if given
styles = $.merge(styles, $('<link rel="stylesheet" href="' + options.stylesheet + '">'));
}
var styles = $("");
if (options.globalStyles) {
// Apply the stlyes from the current sheet to the printed page
styles = $("style, link");
} else if (options.mediaPrint) {
// Apply the media-print stylesheet
styles = $("link[media=print]");
}
if (options.stylesheet) {
// Add a custom stylesheet if given
styles = $.merge(styles, $('<link rel="stylesheet" href="'
+ options.stylesheet + '">'));
}
var copy = $this.clone();
// Create a copy of the element to print
copy = $("<span/>").append(copy);
copy.find(options.noPrintSelector).remove();
// Remove unwanted elements
copy.append(styles.clone());
copy.append($(options.append).clone());
copy.prepend($(options.prepend).clone());
var content = copy.html();
copy.remove();
var copy = $this.clone(); // Create a copy of the element to print
copy = $("<span/>").append(copy);
copy.find(options.noPrintSelector).remove();// Remove unwanted elements
copy.append(styles.clone());
copy.append($(options.append).clone());
copy.prepend($(options.prepend).clone());
var content = copy.html();
copy.remove();
var w, wdoc;
if (options.iframe) {
// Use an iframe for printing
try {
$iframe = $(options.iframe + "");
var iframeCount = $iframe.length;
if (iframeCount === 0) {
// Create a new iFrame if none is given
$iframe = $('<iframe/>').appendTo('body').hide();
}
w = $iframe[0];
w = w.contentWindow || w.contentDocument;
wdoc = w.document || w;
wdoc.open();
wdoc.write(content);
w.print();
if (iframeCount === 0) {
// Destroy the iframe if created here
$iframe.remove();
}
} catch (e) {
// Use the pop-up method if iframe fails for some reason
w = window.open();
w.document.write(content);
w.print();
w.close();
}
} else {
// Use a new window for printing
w = window.open();
w.document.write(content);
w.print();
w.close();
}
return this;
};
var w, wdoc;
if (options.iframe) {
// Use an iframe for printing
try {
$iframe = $(options.iframe + "");
var iframeCount = $iframe.length;
if (iframeCount === 0) {
// Create a new iFrame if none is given
$iframe = $('<iframe/>').appendTo('body').hide();
}
w = $iframe[0];
w = w.contentWindow || w.contentDocument;
wdoc = w.document || w;
wdoc.open();
wdoc.write(content);
wdoc.close();
w.focus();
w.print();
if (iframeCount === 0) {
// Destroy the iframe if created here
$iframe.remove();
}
} catch (e) {
// Use the pop-up method if iframe fails for some reason
w = window.open();
w.document.write(content);
w.document.close();
w.focus();
w.print();
w.close();
}
} else {
// Use a new window for printing
w = window.open();
w.document.write(content);
w.document.close();
w.focus();
w.print();
w.close();
}
return this;
};
})(jQuery);