-
Notifications
You must be signed in to change notification settings - Fork 102
/
index.js
93 lines (81 loc) · 2.55 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function addStyles (win, styles) {
styles.forEach(style => {
let link = win.document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', style);
win.document.getElementsByTagName('head')[0].appendChild(link);
});
}
function openWindow (url, name, props) {
let windowRef = null;
if (/*@cc_on!@*/false) { // for IE only
windowRef = window.open('', name, props);
windowRef.close();
}
windowRef = window.open(url, name, props);
if (!windowRef.opener) {
windowRef.opener = self;
}
windowRef.focus();
return windowRef;
}
const VueHtmlToPaper = {
install (app, options = {}) {
app.config.globalProperties.$htmlToPaper = (el, localOptions, cb = () => true) => {
let defaultName = '_blank',
defaultSpecs = ['fullscreen=yes','titlebar=yes', 'scrollbars=yes'],
defaultReplace = true,
defaultStyles = [],
defaultWindowTitle = window.document.title;
let {
name = defaultName,
specs = defaultSpecs,
replace = defaultReplace,
styles = defaultStyles,
autoClose = true,
windowTitle = defaultWindowTitle,
} = options;
// If has localOptions
// TODO: improve logic
if (!!localOptions) {
if (localOptions.name) name = localOptions.name;
if (localOptions.specs) specs = localOptions.specs;
if (localOptions.replace) replace = localOptions.replace;
if (localOptions.styles) styles = localOptions.styles;
if (localOptions.autoClose === false) autoClose = localOptions.autoClose;
if (localOptions.windowTitle) windowTitle = localOptions.windowTitle;
}
specs = !!specs.length ? specs.join(',') : '';
const element = window.document.getElementById(el);
if (!element) {
alert(`Element to print #${el} not found!`);
return;
}
const url = '';
const win = openWindow(url, name, specs);
win.document.write(`
<html>
<head>
<title>${windowTitle || window.document.title}</title>
</head>
<body>
${element.innerHTML}
</body>
</html>
`);
addStyles(win, styles);
setTimeout(() => {
win.focus();
win.print();
console.warn('autoClose', autoClose);
if (autoClose) {
setTimeout(function () {win.close();}, 1);
}
cb();
}, 1000);
return true;
};
},
};
export default VueHtmlToPaper;