8 Commits
5 changed files with 228 additions and 133 deletions
+2
View File
@@ -0,0 +1,2 @@
bower_components
node_modules
+22 -8
View File
@@ -18,13 +18,15 @@ or
You can submit the options object like:
$("#myElementId").print({
addGlobalStyles : true,
stylesheet : null,
rejectWindow : true,
noPrintSelector : ".no-print",
iframe : true,
append : null,
prepend : null
globalStyles: true,
mediaPrint: false,
stylesheet: null,
noPrintSelector: ".no-print",
iframe: true,
append: null,
prepend: null,
manuallyCopyFormValues: true,
deferred: $.Deferred()
});
Currently this plugin supports the following options:
@@ -65,6 +67,18 @@ 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
####manuallyCopyFormValues
- Default: `true`
- Acceptable-Values: Boolean
- Function: Should it copy user-updated form input values onto the printed markup (this is done by manually iterating over each form element)
####deferred
- Default: `$.Deferred()`
- Acceptable-Values: Any valid `jQuery.Deferred` object
- Function: A jQuery.Deferred object that is resolved once the print function is called
## Tested with
### jQuery
@@ -79,7 +93,7 @@ Currently this plugin supports the following options:
[CC-BY](http://creativecommons.org/licenses/by/3.0/).
## Demo
[jsFiddle](http://jsfiddle.net/5V24U/27/)
[jQuery.print/demo](http://doersguild.github.io/jQuery.print/demo/)
---------------------------------------
Like our [work](http://doersguild.com)? [Get in touch!](mailto:mail@doersguild.com)
+26
View File
@@ -0,0 +1,26 @@
{
"name": "jQuery.print",
"main": "jQuery.print.js",
"version": "1.3.0",
"homepage": "https://doersguild.github.io/jQuery.print/",
"authors": [
"Sathvik P <sathvik@doersguild.com>"
],
"description": "Easy to use, Element Printing Plugin for jQuery, for printing specific parts of a page",
"keywords": [
"print",
"element printing",
"jquery print"
],
"dependencies": {
"jquery": ">=1.7.2"
},
"license": "CC-BY",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}
+49 -65
View File
@@ -11,118 +11,102 @@
<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;
}
.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>
<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]-->
<h3><a href="https://github.com/DoersGuild/jQuery.print" id="view-on-github" class="btn"><span>View jQuery.print on GitHub</span></a></h3>
<div id="content_holder">
<div id="ele1" class="a">
<h3>Element 1</h3>
<p>
Some random text.
Some random text.
<input type="text" value="Dummy input text" />
</p>
<button class="print-link no-print" onclick="jQuery('#ele1').print()">
Print this
Print this (jQuery('#ele1').print())
</button>
</div>
<div id="ele2" class="b">
<h3>Element 2</h3>
<p>
Some other random text.
Some other random text.
</p>
<button class="print-link no-print">
Print this
Print this ($.print("#ele2")) and skip the button
</button>
</div>
<div id="ele3" class="a">
<h3>Element 3</h3>
<p class="no-print">
Some more random text.
Some more random text that is not to be printed.
</p>
<button class="print-link" onclick="jQuery.print('#ele3')">
Print this
Print this (jQuery.print('#ele3'))
</button>
</div>
<div id="ele4" class="b">
<h3 class='avoid-this'>Element 4</h3>
<p>
Some really random text.
Some really random text.
</p>
<button class="print-link avoid-this">
Print this
Print this in a new window, without this button and the title
</button>
</div>
<br/>
<button class="print-link" onclick="jQuery.print()">
Print page
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>')
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
});
//]]>
//<![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>
</html>
+129 -60
View File
@@ -1,40 +1,69 @@
/* jQuery.print, version 1.0.3
/* @license
* jQuery.print, version 1.3.0
* (c) Sathvik Ponangi, Doers' Guild
* Licence: CC-By (http://creativecommons.org/licenses/by/3.0/)
*--------------------------------------------------------------------------*/
(function($) {"use strict";
(function ($) {
"use strict";
// A nice closure for our definitions
function getjQueryObject(string) {
// Make string a vaild jQuery thing
var jqObj = $("");
try {
jqObj = $(string).clone();
} catch(e) {
jqObj = $("<span />").html(string);
jqObj = $(string)
.clone();
} catch (e) {
jqObj = $("<span />")
.html(string);
}
return jqObj;
}
function isNode(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");
function printFrame(frameWindow) {
// Print the selected window/iframe
var def = $.Deferred();
try {
setTimeout(function () {
// Fix for IE : Allow it to render the iframe
frameWindow.focus();
try {
// Fix for IE11 - printng the whole page instead of the iframe content
if (!frameWindow.document.execCommand('print', false, null)) {
// document.execCommand returns false if it failed -http://stackoverflow.com/a/21336448/937891
frameWindow.print();
}
} catch (e) {
frameWindow.print();
}
frameWindow.close();
deferred.resolve();
}, 250);
} catch (err) {
def.reject(err);
}
return def;
}
function printContentInNewWindow(content) {
// Open a new window and print selected content
var w = window.open();
w.document.write(content);
w.document.close();
return printFrame(w);
}
$.print = $.fn.print = function() {
function isNode(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");
}
$.print = $.fn.print = function () {
// Print a given set of elements
var options, $this, self = this;
// console.log("Printing", this, arguments);
if ( self instanceof $) {
if (self instanceof $) {
// Get the node if it is a jQuery object
self = self.get(0);
}
if (isNode(self)) {
// If `this` is a HTML element, i.e. for
// $(selector).print()
@@ -60,20 +89,20 @@
$this = $("html");
}
}
// Default options
var defaults = {
globalStyles : true,
mediaPrint : false,
stylesheet : null,
noPrintSelector : ".no-print",
iframe : true,
append : null,
prepend : null
globalStyles: true,
mediaPrint: false,
stylesheet: null,
noPrintSelector: ".no-print",
iframe: true,
append: null,
prepend: null,
manuallyCopyFormValues: true,
deferred: $.Deferred()
};
// Merge with user-options
options = $.extend({}, defaults, (options || {}));
var $styles = $("");
if (options.globalStyles) {
// Apply the stlyes from the current sheet to the printed page
@@ -86,25 +115,48 @@
// Add a custom stylesheet if given
$styles = $.merge($styles, $('<link rel="stylesheet" href="' + options.stylesheet + '">'));
}
// Create a copy of the element to print
var copy = $this.clone();
// Wrap it in a span to get the HTML markup string
copy = $("<span/>").append(copy);
copy = $("<span/>")
.append(copy);
// Remove unwanted elements
copy.find(options.noPrintSelector).remove();
copy.find(options.noPrintSelector)
.remove();
// Add in the styles
copy.append($styles.clone());
// Appedned content
copy.append(getjQueryObject(options.append));
// Prepended content
copy.prepend(getjQueryObject(options.prepend));
if (options.manuallyCopyFormValues) {
// Manually copy form values into the HTML for printing user-modified input fields
// http://stackoverflow.com/a/26707753
copy.find("input, select, textarea")
.each(function () {
var $field = $(this);
if ($field.is("[type='radio']") || $field.is("[type='checkbox']")) {
if ($field.prop("checked")) {
$field.attr("checked", "checked");
}
} else if ($field.is("select")) {
$field.find(":selected")
.attr("selected", "selected");
} else {
$field.attr("value", $field.val());
}
});
}
// Get the HTML markup string
var content = copy.html();
// Notify with generated markup & cloned elements - useful for logging, etc
try {
options.deferred.notify('generated_markup', content, copy);
} catch (err) {
console.warn('Error notifying deferred', err);
}
// Destroy the copy
copy.remove();
var w, wdoc;
if (options.iframe) {
// Use an iframe for printing
try {
@@ -112,50 +164,67 @@
var iframeCount = $iframe.length;
if (iframeCount === 0) {
// Create a new iFrame if none is given
$iframe = $('<iframe height="0" width="0" border="0" wmode="Opaque"/>').prependTo('body').css({
"position" : "absolute",
"top" : -999,
"left" : -999
});
$iframe = $('<iframe height="0" width="0" border="0" wmode="Opaque"/>')
.prependTo('body')
.css({
"position": "absolute",
"top": -999,
"left": -999
});
}
var w, wdoc;
w = $iframe.get(0);
w = w.contentWindow || w.contentDocument || w;
wdoc = w.document || w.contentDocument || w;
wdoc.open();
wdoc.write(content);
wdoc.close();
setTimeout(function() {
// Fix for IE : Allow it to render the iframe
w.focus();
w.print();
setTimeout(function() {
// Fix for IE
if (iframeCount === 0) {
// Destroy the iframe if created here
$iframe.remove();
printFrame(w)
.done(function () {
// Success
setTimeout(function () {
// Wait for IE
if (iframeCount === 0) {
// Destroy the iframe if created here
$iframe.remove();
}
}, 100);
})
.fail(function () {
// Use the pop-up method if iframe fails for some reason
console.error("Failed to print from iframe", e.stack, e.message);
printContentInNewWindow(content);
})
.always(function () {
try {
options.deferred.resolve();
} catch (err) {
console.warn('Error notifying deferred', err);
}
}, 100);
}, 250);
});
} catch (e) {
// Use the pop-up method if iframe fails for some reason
console.error("Failed to print from iframe", e.stack, e.message);
w = window.open();
w.document.write(content);
w.document.close();
w.focus();
w.print();
w.close();
printContentInNewWindow(content)
.always(function () {
try {
options.deferred.resolve();
} catch (err) {
console.warn('Error notifying deferred', err);
}
});
}
} else {
// Use a new window for printing
w = window.open();
w.document.write(content);
w.document.close();
w.focus();
w.print();
w.close();
printContentInNewWindow(content)
.always(function () {
try {
options.deferred.resolve();
} catch (err) {
console.warn('Error notifying deferred', err);
}
});
}
return this;
};
})(jQuery);
})(jQuery);