forked from kempsteven/vue-html2pdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvue-html2pdf.esm.js
494 lines (420 loc) · 16.3 KB
/
vue-html2pdf.esm.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import html2pdf from 'html2pdf.js';
//
var script = {
props: {
showLayout: {
type: Boolean,
default: false
},
floatLayout: {
type: Boolean,
default: true
},
enableDownload: {
type: Boolean,
default: true
},
previewModal: {
type: Boolean,
default: false
},
paginateElementsByHeight: {
type: Number
},
paddingElementAfterPaginated: {
type: Number
},
filename: {
type: String,
default: ("" + (new Date().getTime()))
},
pdfQuality: {
type: Number,
default: 2,
},
pdfFormat: {
default: 'a4',
},
pdfOrientation: {
type: String,
default: 'portrait'
},
pdfContentWidth: {
default: '800px'
},
htmlToPdfOptions: {
type: Object
},
manualPagination: {
type: Boolean,
default: false
}
},
data: function data () {
return {
hasAlreadyParsed: false,
progress: 0,
pdfWindow: null,
pdfFile: null
}
},
watch: {
progress: function progress (val) {
this.$emit('progress', val);
},
paginateElementsByHeight: function paginateElementsByHeight () {
this.resetPagination();
},
$props: {
handler: function handler () {
this.validateProps();
},
deep: true,
immediate: true
}
},
methods: {
validateProps: function validateProps () {
// If manual-pagination is false, paginate-elements-by-height props is required
if (!this.manualPagination) {
if (this.paginateElementsByHeight === undefined) {
console.error('Error: paginate-elements-by-height is required if manual-pagination is false');
}
}
},
resetPagination: function resetPagination () {
var parentElement = this.$refs.pdfContent.firstChild;
var pageBreaks = parentElement.getElementsByClassName('html2pdf__page-break');
var pageBreakLength = pageBreaks.length - 1;
if (pageBreakLength === -1) { return }
this.hasAlreadyParsed = false;
// Remove All Page Break (For Pagination)
for (var x = pageBreakLength; x >= 0; x--) {
pageBreaks[x].parentNode.removeChild(pageBreaks[x]);
}
},
generatePdf: function generatePdf () {
this.$emit('startPagination');
this.progress = 0;
this.paginationOfElements();
},
paginationOfElements: function paginationOfElements () {
this.progress = 25;
/*
When this props is true,
the props paginate-elements-by-height will not be used.
Instead the pagination process will rely on the elements with a class "html2pdf__page-break"
to know where to page break, which is automatically done by html2pdf.js
*/
if (this.manualPagination) {
this.progress = 70;
this.$emit('hasPaginated');
this.downloadPdf();
return
}
if (!this.hasAlreadyParsed) {
var parentElement = document.getElementById('pdf-parent-pagination') || this.$refs.pdfContent.firstChild;
var ArrOfContentChildren = Array.from(parentElement.children);
var childrenHeight = 0;
/*
Loop through Elements and add there height with childrenHeight variable.
Once the childrenHeight is >= this.paginateElementsByHeight, create a div with
a class named 'html2pdf__page-break' and insert the element before the element
that will be in the next page
*/
for (var i = 0; i < ArrOfContentChildren.length; i++){
var childElement = ArrOfContentChildren[i];
// Get The First Class of the element
var elementFirstClass = childElement.classList[0];
var isPageBreakClass = elementFirstClass === 'html2pdf__page-break';
if (isPageBreakClass) {
childrenHeight = 0;
} else {
// Get Element Height
var elementHeight = childElement.getBoundingClientRect().height;
// Get Computed Margin Top and Bottom
var elementComputedStyle = childElement.currentStyle || window.getComputedStyle(childElement);
var elementMarginTopBottom = parseInt(elementComputedStyle.marginTop) + parseInt(elementComputedStyle.marginBottom);
if (elementMarginTopBottom === 0) {
elementComputedStyle = childElement.getElementsByClassName('product-display')[0].currentStyle ||
window.getComputedStyle(childElement.getElementsByClassName('product-display')[0]);
elementMarginTopBottom = parseInt(elementComputedStyle.marginTop) + parseInt(elementComputedStyle.marginBottom);
}
// Add Both Element Height with the Elements Margin Top and Bottom
var elementHeightWithMargin = elementHeight + elementMarginTopBottom;
if ((childrenHeight + elementHeight) < this.paginateElementsByHeight) {
if (i === ArrOfContentChildren.length - 1) {
var diffLastHeight = 1120 - (this.paddingElementAfterPaginated * 2) - (childrenHeight + elementHeightWithMargin);
var section1 = document.createElement('div');
section1.style.height = diffLastHeight + 'px';
parentElement.insertAdjacentElement('beforeend', section1);
}
childrenHeight += elementHeightWithMargin;
} else {
var section = document.createElement('div');
section.classList.add('html2pdf__page-break');
parentElement.insertBefore(section, childElement);
// Add padding after paginated element
if (this.paddingElementAfterPaginated) {
childElement.style.marginTop = (this.paddingElementAfterPaginated) + "px";
}
// Reset Variables made the upper condition false
childrenHeight = elementHeightWithMargin;
if (i === ArrOfContentChildren.length - 1) {
var diffLastHeight$1 = 1120 - (this.paddingElementAfterPaginated * 2) - (elementHeightWithMargin);
var section1$1 = document.createElement('div');
section1$1.style.height = diffLastHeight$1 + 'px';
parentElement.insertAdjacentElement('beforeend', section1$1);
}
}
}
}
this.progress = 70;
/*
Set to true so that if would generate again we wouldn't need
to parse the HTML to paginate the elements
*/
this.hasAlreadyParsed = true;
} else {
this.progress = 70;
}
this.$emit('hasPaginated');
this.downloadPdf();
},
downloadPdf: async function downloadPdf () {
// Set Element and Html2pdf.js Options
var pdfContent = this.$refs.pdfContent;
var options = this.setOptions();
this.$emit('beforeDownload', { html2pdf: html2pdf, options: options, pdfContent: pdfContent });
var html2PdfSetup = html2pdf().set(options).from(pdfContent);
var pdfBlobUrl = null;
if (this.previewModal) {
this.pdfFile = await html2PdfSetup.output('bloburl');
pdfBlobUrl = this.pdfFile;
}
if (this.enableDownload) {
pdfBlobUrl = await html2PdfSetup.save().output('bloburl');
}
if (pdfBlobUrl) {
var res = await fetch(pdfBlobUrl);
var blobFile = await res.blob();
this.$emit('hasDownloaded', blobFile);
}
this.progress = 100;
},
setOptions: function setOptions () {
if (this.htmlToPdfOptions !== undefined && this.htmlToPdfOptions !== null) {
return this.htmlToPdfOptions
}
return {
margin: 0,
filename: ((this.filename) + ".pdf"),
image: {
type: 'jpeg',
quality: 0.98
},
enableLinks: false,
html2canvas: {
scale: this.pdfQuality,
useCORS: true
},
jsPDF: {
unit: 'in',
format: this.pdfFormat,
orientation: this.pdfOrientation
}
}
},
closePreview: function closePreview () {
this.pdfFile = null;
}
}
};
function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier /* server only */, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
if (typeof shadowMode !== 'boolean') {
createInjectorSSR = createInjector;
createInjector = shadowMode;
shadowMode = false;
}
// Vue.extend constructor export interop.
var options = typeof script === 'function' ? script.options : script;
// render functions
if (template && template.render) {
options.render = template.render;
options.staticRenderFns = template.staticRenderFns;
options._compiled = true;
// functional template
if (isFunctionalTemplate) {
options.functional = true;
}
}
// scopedId
if (scopeId) {
options._scopeId = scopeId;
}
var hook;
if (moduleIdentifier) {
// server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext); // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__;
}
// inject component styles
if (style) {
style.call(this, createInjectorSSR(context));
}
// register component module identifier for async chunk inference
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier);
}
};
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook;
}
else if (style) {
hook = shadowMode
? function (context) {
style.call(this, createInjectorShadow(context, this.$root.$options.shadowRoot));
}
: function (context) {
style.call(this, createInjector(context));
};
}
if (hook) {
if (options.functional) {
// register for functional component in vue file
var originalRender = options.render;
options.render = function renderWithStyleInjection(h, context) {
hook.call(context);
return originalRender(h, context);
};
}
else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate;
options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
}
}
return script;
}
var isOldIE = typeof navigator !== 'undefined' &&
/msie [6-9]\\b/.test(navigator.userAgent.toLowerCase());
function createInjector(context) {
return function (id, style) { return addStyle(id, style); };
}
var HEAD;
var styles = {};
function addStyle(id, css) {
var group = isOldIE ? css.media || 'default' : id;
var style = styles[group] || (styles[group] = { ids: new Set(), styles: [] });
if (!style.ids.has(id)) {
style.ids.add(id);
var code = css.source;
if (css.map) {
// https://developer.chrome.com/devtools/docs/javascript-debugging
// this makes source maps inside style tags work properly in Chrome
code += '\n/*# sourceURL=' + css.map.sources[0] + ' */';
// http://stackoverflow.com/a/26603875
code +=
'\n/*# sourceMappingURL=data:application/json;base64,' +
btoa(unescape(encodeURIComponent(JSON.stringify(css.map)))) +
' */';
}
if (!style.element) {
style.element = document.createElement('style');
style.element.type = 'text/css';
if (css.media)
{ style.element.setAttribute('media', css.media); }
if (HEAD === undefined) {
HEAD = document.head || document.getElementsByTagName('head')[0];
}
HEAD.appendChild(style.element);
}
if ('styleSheet' in style.element) {
style.styles.push(code);
style.element.styleSheet.cssText = style.styles
.filter(Boolean)
.join('\n');
}
else {
var index = style.ids.size - 1;
var textNode = document.createTextNode(code);
var nodes = style.element.childNodes;
if (nodes[index])
{ style.element.removeChild(nodes[index]); }
if (nodes.length)
{ style.element.insertBefore(textNode, nodes[index]); }
else
{ style.element.appendChild(textNode); }
}
}
}
/* script */
var __vue_script__ = script;
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"vue-html2pdf"},[_c('section',{staticClass:"layout-container",class:{
'show-layout' : _vm.showLayout,
'unset-all' : !_vm.floatLayout
}},[_c('section',{ref:"pdfContent",staticClass:"content-wrapper",style:(("width: " + _vm.pdfContentWidth + ";"))},[_vm._t("pdf-content")],2)]),_vm._v(" "),_c('transition',{attrs:{"name":"transition-anim"}},[(_vm.pdfFile)?_c('section',{staticClass:"pdf-preview"},[_c('button',{on:{"click":function($event){if($event.target !== $event.currentTarget){ return null; }return _vm.closePreview()}}},[_vm._v("\n\t\t\t\t\t×\n\t\t\t\t")]),_vm._v(" "),_c('iframe',{attrs:{"src":_vm.pdfFile,"width":"100%","height":"100%"}})]):_vm._e()])],1)};
var __vue_staticRenderFns__ = [];
/* style */
var __vue_inject_styles__ = function (inject) {
if (!inject) { return }
inject("data-v-13e8ad9e_0", { source: ".vue-html2pdf .layout-container[data-v-13e8ad9e]{position:fixed;width:100vw;height:100vh;left:-100vw;top:0;z-index:-9999;background:rgba(95,95,95,.8);display:flex;justify-content:center;align-items:flex-start;overflow:auto}.vue-html2pdf .layout-container.show-layout[data-v-13e8ad9e]{left:0;z-index:9999}.vue-html2pdf .layout-container.unset-all[data-v-13e8ad9e]{all:unset;width:auto;height:auto}.vue-html2pdf .pdf-preview[data-v-13e8ad9e]{position:fixed;width:65%;min-width:600px;height:80vh;top:100px;z-index:9999999;left:50%;transform:translateX(-50%);border-radius:5px;box-shadow:0 0 10px #00000048}.vue-html2pdf .pdf-preview button[data-v-13e8ad9e]{position:absolute;top:-20px;left:-15px;width:35px;height:35px;background:#555;border:0;box-shadow:0 0 10px #00000048;border-radius:50%;color:#fff;display:flex;align-items:center;justify-content:center;font-size:20px;cursor:pointer}.vue-html2pdf .pdf-preview iframe[data-v-13e8ad9e]{border:0}.vue-html2pdf .transition-anim-enter-active[data-v-13e8ad9e],.vue-html2pdf .transition-anim-leave-active[data-v-13e8ad9e]{transition:opacity .3s ease-in}.vue-html2pdf .transition-anim-enter[data-v-13e8ad9e],.vue-html2pdf .transition-anim-leave-to[data-v-13e8ad9e]{opacity:0}", map: undefined, media: undefined });
};
/* scoped */
var __vue_scope_id__ = "data-v-13e8ad9e";
/* module identifier */
var __vue_module_identifier__ = undefined;
/* functional template */
var __vue_is_functional_template__ = false;
/* style inject SSR */
/* style inject shadow dom */
var __vue_component__ = /*#__PURE__*/normalizeComponent(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
false,
createInjector,
undefined,
undefined
);
// Import vue component
// install function executed by Vue.use()
function install(Vue) {
if (install.installed) { return; }
install.installed = true;
Vue.component('VueHtml2pdf', __vue_component__);
}
// Create module definition for Vue.use()
var plugin = {
install: install,
};
// To auto-install when vue is found
/* global window global */
var GlobalVue = null;
if (typeof window !== 'undefined') {
GlobalVue = window.Vue;
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
}
// Inject install function into component - allows component
// to be registered via Vue.use() as well as Vue.component()
__vue_component__.install = install;
// It's possible to expose named exports when writing components that can
// also be used as directives, etc. - eg. import { RollupDemoDirective } from 'rollup-demo';
// export const RollupDemoDirective = component;
export default __vue_component__;