forked from jasonday/printThis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
printThis.js
244 lines (213 loc) · 9.65 KB
/
printThis.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*
* printThis v1.5
* @desc Printing plug-in for jQuery
* @author Jason Day
*
* Resources (based on) :
* jPrintArea: http://plugins.jquery.com/project/jPrintArea
* jqPrint: https://github.com/permanenttourist/jquery.jqprint
* Ben Nadal: http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm
*
* Licensed under the MIT licence:
* http://www.opensource.org/licenses/mit-license.php
*
* (c) Jason Day 2015
*
* Usage:
*
* $("#mySelector").printThis({
* debug: false, * show the iframe for debugging
* importCSS: true, * import page CSS
* importStyle: false, * import style tags
* printContainer: true, * grab outer container as well as the contents of the selector
* loadCSS: "path/to/my.css", * path to additional css file - us an array [] for multiple
* pageTitle: "", * add title to print page
* removeInline: false, * remove all inline styles from print elements
* printDelay: 333, * variable print delay
* header: null, * prefix to html
* formValues: true * preserve input/form values
* });
*
* Notes:
* - the loadCSS will load additional css (with or without @media print) into the iframe, adjusting layout
*/
;
(function($) {
var opt;
$.fn.printThis = function(options) {
opt = $.extend({}, $.fn.printThis.defaults, options);
var $element = this instanceof jQuery ? this : $(this);
var strFrameName = "printThis-" + (new Date()).getTime();
if (window.location.hostname !== document.domain && navigator.userAgent.match(/msie/i)) {
// Ugly IE hacks due to IE not inheriting document.domain from parent
// checks if document.domain is set by comparing the host name against document.domain
var iframeSrc = "javascript:document.write(\"<head><script>document.domain=\\\"" + document.domain + "\\\";</script></head><body></body>\")";
var printI = document.createElement('iframe');
printI.name = "printIframe";
printI.id = strFrameName;
printI.className = "MSIE";
document.body.appendChild(printI);
printI.src = iframeSrc;
} else {
// other browsers inherit document.domain, and IE works if document.domain is not explicitly set
var $frame = $("<iframe id='" + strFrameName + "' name='printIframe' />");
$frame.appendTo("body");
}
var $iframe = $("#" + strFrameName);
// show frame if in debug mode
if (!opt.debug) $iframe.css({
position: "absolute",
width: "0px",
height: "0px",
left: "-600px",
top: "-600px"
});
// $iframe.ready() and $iframe.load were inconsistent between browsers
setTimeout(function() {
// Add doctype to fix the style difference between printing and render
function setDocType($iframe,doctype){
var win, doc;
win = $iframe.get(0);
win = win.contentWindow || win.contentDocument || win;
doc = win.document || win.contentDocument || win;
doc.open();
doc.write(doctype);
doc.close();
}
if(opt.doctypeString){
setDocType($iframe,opt.doctypeString);
}
var $doc = $iframe.contents(),
$head = $doc.find("head"),
$body = $doc.find("body");
// add base tag to ensure elements use the parent domain
$head.append('<base href="' + document.location.protocol + '//' + document.location.host + '">');
// import page stylesheets
if (opt.importCSS) $("link[rel=stylesheet]").each(function() {
var href = $(this).attr("href");
if (href) {
var media = $(this).attr("media") || "all";
$head.append("<link type='text/css' rel='stylesheet' href='" + href + "' media='" + media + "'>")
}
});
// import style tags
if (opt.importStyle) $("style").each(function() {
$(this).clone().appendTo($head);
//$head.append($(this));
});
//add title of the page
if (opt.pageTitle) $head.append("<title>" + opt.pageTitle + "</title>");
// import additional stylesheet(s)
if (opt.loadCSS) {
if( $.isArray(opt.loadCSS)) {
jQuery.each(opt.loadCSS, function(index, value) {
$head.append("<link type='text/css' rel='stylesheet' href='" + this + "'>");
});
} else {
$head.append("<link type='text/css' rel='stylesheet' href='" + opt.loadCSS + "'>");
}
}
// print header
if (opt.header) $body.append(opt.header);
// grab $.selector as container
if (opt.printContainer) $body.append($element.outer());
// otherwise just print interior elements of container
else $element.each(function() {
$body.append($(this).html());
});
// capture form/field values
if (opt.formValues) {
// loop through inputs
var $input = $element.find('input');
if ($input.length) {
$input.each(function() {
var $this = $(this),
$name = $(this).attr('name'),
$checker = $this.is(':checkbox') || $this.is(':radio'),
$iframeInput = $doc.find('input[name="' + $name + '"]'),
$value = $this.val();
//order matters here
if (!$checker) {
$iframeInput.val($value);
} else if ($this.is(':checked')) {
if ($this.is(':checkbox')) {
$iframeInput.attr('checked', 'checked');
} else if ($this.is(':radio')) {
$doc.find('input[name="' + $name + '"][value=' + $value + ']').attr('checked', 'checked');
}
}
});
}
//loop through selects
var $select = $element.find('select');
if ($select.length) {
$select.each(function() {
var $this = $(this),
$name = $(this).attr('name'),
$value = $this.val();
$doc.find('select[name="' + $name + '"]').val($value);
});
}
//loop through textareas
var $textarea = $element.find('textarea');
if ($textarea.length) {
$textarea.each(function() {
var $this = $(this),
$name = $(this).attr('name'),
$value = $this.val();
$doc.find('textarea[name="' + $name + '"]').val($value);
});
}
} // end capture form/field values
// remove inline styles
if (opt.removeInline) {
// $.removeAttr available jQuery 1.7+
if ($.isFunction($.removeAttr)) {
$doc.find("body *").removeAttr("style");
} else {
$doc.find("body *").attr("style", "");
}
}
setTimeout(function() {
if ($iframe.hasClass("MSIE")) {
// check if the iframe was created with the ugly hack
// and perform another ugly hack out of neccessity
window.frames["printIframe"].focus();
$head.append("<script> window.print(); </script>");
} else {
// proper method
if (document.queryCommandSupported("print")) {
$iframe[0].contentWindow.document.execCommand("print", false, null);
} else {
$iframe[0].contentWindow.focus();
$iframe[0].contentWindow.print();
}
}
//remove iframe after print
if (!opt.debug) {
setTimeout(function() {
$iframe.remove();
}, 1000);
}
}, opt.printDelay);
}, 333);
};
// defaults
$.fn.printThis.defaults = {
debug: false, // show the iframe for debugging
importCSS: true, // import parent page css
importStyle: false, // import style tags
printContainer: true, // print outer container/$.selector
loadCSS: "", // load an additional css file - load multiple stylesheets with an array []
pageTitle: "", // add title to print page
removeInline: false, // remove all inline styles
printDelay: 333, // variable print delay
header: null, // prefix to html
formValues: true, // preserve input/form values
doctypeString: '<!DOCTYPE html>' // html doctype
};
// $.selector container
jQuery.fn.outer = function() {
return $($("<div></div>").html(this.clone())).html()
}
})(jQuery);