-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
79 lines (66 loc) · 1.9 KB
/
index.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
/**
* Module dependencies.
*/
var event = require('event');
/**
* Print iframe.
*
* @see http://stackoverflow.com/questions/5946607/is-an-empty-iframe-src-valid
* @see http://stackoverflow.com/questions/1542320/margin-while-printing-html-page
* @see http://stackoverflow.com/questions/1960939/disabling-browser-print-options-headers-footers-margins-from-page/2780518#2780518
* @see http://bytes.com/topic/misc/answers/629926-ie7-printing-iframe-solution
*/
var iframe = document.createElement('iframe');
iframe.setAttribute('id', 'print-iframe');
iframe.setAttribute('src', 'about:blank');
iframe.style.width = iframe.style.height = 0;
iframe.style.border = 'none';
(function(){
event.bind(window, 'load', onload);
function onload() {
event.unbind(window, 'load', onload);
document.body.appendChild(iframe);
}
})();
/**
* Expose `print`.
*/
module.exports = print;
/**
* Print HTML elements on a printer.
*/
function print(str) {
var css = [
'<style type="text/css" media="print">',
' @page {',
' size: auto;', // auto is the current printer page size
' margin: 0mm;', // this affects the margin in the printer settings
' }',
' body {',
' background-color:#FFFFFF;',
' border: none;',
' margin: 0px;',
' }',
'</style>'
].join('\n');
var printer = iframe.contentWindow
? iframe.contentWindow
: iframe.contentDocument.document
? iframe.contentDocument.document
: iframe.contentDocument;
printer.document.open('text/html', 'replace');
printer.document.onreadystatechange = onready;
printer.document.write(css + str);
printer.document.close();
function onready() {
if ('complete' == printer.document.readyState) {
printer.document.body.focus();
try {
// <= IE9
printer.document.execCommand('print', false, null);
} catch (err) {
printer.print();
}
}
}
}