forked from joseluisq/printd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
220 lines (175 loc) · 5.76 KB
/
index.ts
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
const URL_LONG = /^(((http[s]?)|file):)?(\/\/)+([0-9a-zA-Z-_.=?&].+)$/
const URL_SHORT = /^((\.|\.\.)?\/)([0-9a-zA-Z-_.=?&]+\/)*([0-9a-zA-Z-_.=?&]+)$/
const isValidURL = (str: string) => URL_LONG.test(str) || URL_SHORT.test(str)
export function createStyle (doc: Document, cssText: string) {
const style: HTMLStyleElement = doc.createElement('style')
style.type = 'text/css'
style.appendChild(window.document.createTextNode(cssText))
return style
}
export function createLinkStyle (doc: Document, url: string) {
const style: HTMLLinkElement = doc.createElement('link')
style.type = 'text/css'
style.rel = 'stylesheet'
style.href = url
return style
}
export function createIFrame (parent: HTMLElement) {
// tslint:disable-next-line
if (typeof window !== 'undefined') {
const el: HTMLIFrameElement = window.document.createElement('iframe')
const css = 'visibility:hidden;width:0;height:0;position:absolute;z-index:-9999;bottom:0;'
el.setAttribute('src', 'about:blank')
el.setAttribute('style', css)
el.setAttribute('width', '0')
el.setAttribute('height', '0')
el.setAttribute('wmode', 'opaque')
parent.appendChild(el)
return el
} else {
return null
}
}
export interface PrintdOptions {
/** Parent element where the printable element will be appended. */
parent?: HTMLElement
/** Specifies a custom document head elements */
headElements?: HTMLElement[]
/** Specifies a custom document body elements */
bodyElements?: HTMLElement[]
}
export interface PrintdCallbackArgs {
/** Iframe reference */
iframe: HTMLIFrameElement
/** HTMLElement copy reference */
element?: HTMLElement
/** Function to launch the print dialog after content was loaded */
launchPrint: Function
}
export type PrintdCallback = (args: PrintdCallbackArgs) => void
const DEFAULT_OPTIONS: PrintdOptions = {
// tslint:disable-next-line
parent: typeof window !== 'undefined' ? window.document.body : undefined,
headElements: [],
bodyElements: []
}
/** Printd class that prints HTML elements in a blank document */
export default class Printd {
private readonly opts: Required<PrintdOptions>
private readonly iframe: HTMLIFrameElement | null
private isLoading = false
private hasEvents = false
private callback?: PrintdCallback
private elCopy?: HTMLElement
constructor (options?: PrintdOptions) {
this.opts = Object.assign(DEFAULT_OPTIONS, (options || {})) as Required<PrintdOptions>
this.iframe = createIFrame(this.opts.parent)
}
/** Gets current Iframe reference */
getIFrame () {
return this.iframe
}
/**
* Print an HTMLElement
*
* @param el HTMLElement
* @param styles Optional styles (css texts or urls) that will add to iframe document.head
* @param scripts Optional scripts (script texts or urls) that will add to iframe document.body
* @param callback Optional callback that will be triggered when content is ready to print
*/
print (el: HTMLElement, styles?: string[], scripts?: string[], callback?: PrintdCallback) {
if (this.isLoading) return
const { contentDocument, contentWindow } = this.iframe
if (!contentDocument || !contentWindow) return
this.iframe.src = 'about:blank'
this.elCopy = el.cloneNode(true) as HTMLElement
if (!this.elCopy) return
this.isLoading = true
this.callback = callback
const doc = contentWindow.document
doc.open()
doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"></head><body></body></html>')
this.addEvents()
// 1. append custom elements
const { headElements, bodyElements } = this.opts
// 1.1 append custom head elements
if (Array.isArray(headElements)) {
headElements.forEach((el) => doc.head.appendChild(el))
}
// 1.1 append custom body elements
if (Array.isArray(bodyElements)) {
bodyElements.forEach((el) => doc.body.appendChild(el))
}
// 2. append custom styles
if (Array.isArray(styles)) {
styles.forEach((value) => {
if (value) {
if (isValidURL(value)) {
doc.head.appendChild(createLinkStyle(doc, value))
} else {
doc.head.appendChild(createStyle(doc, value))
}
}
})
}
// 3. append element copy
doc.body.appendChild(this.elCopy)
// 4. append custom scripts
if (Array.isArray(scripts)) {
scripts.forEach((value) => {
if (value) {
const script = doc.createElement('script')
if (isValidURL(value)) {
script.src = value
} else {
script.innerText = value
}
doc.body.appendChild(script)
}
})
}
doc.close()
}
/**
* Print an URL
*
* @param url URL to print
* @param callback Optional callback that will be triggered when content is ready to print
*/
printURL (url: string, callback?: PrintdCallback) {
if (this.isLoading) return
this.addEvents()
this.isLoading = true
this.callback = callback
this.iframe.src = url
}
private launchPrint (contentWindow: Window) {
const result = contentWindow.document.execCommand('print', false, null)
if (!result) {
contentWindow.print()
}
}
private addEvents () {
if (!this.hasEvents) {
this.hasEvents = true
this.iframe.addEventListener('load', () => this.onLoad(), false)
}
}
private onLoad () {
if (this.iframe) {
this.isLoading = false
const { contentDocument, contentWindow } = this.iframe
if (!contentDocument || !contentWindow) return
if (this.callback) {
this.callback({
iframe: this.iframe,
element: this.elCopy,
launchPrint: () => this.launchPrint(contentWindow)
})
} else {
this.launchPrint(contentWindow)
}
}
}
}
export { Printd }