-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
64 lines (55 loc) · 2.05 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
/* eslint-disable no-useless-escape */
import JSZip from 'jszip';
import { minify } from 'html-minifier-terser';
import createDocumentOptionsAndMergeWithDefaults from './src/utils/options-utils';
import addFilesToContainer from './src/html-to-docx';
const minifyHTMLString = async (htmlString) => {
try {
if (typeof htmlString === 'string' || htmlString instanceof String) {
const minifiedHTMLString = await minify(htmlString, {
collapseWhitespace: true,
removeComments: true,
});
return minifiedHTMLString;
}
throw new Error('invalid html string');
} catch (error) {
return null;
}
};
async function generateContainer(
htmlString,
headerHTMLString,
documentOptions = {},
footerHTMLString
) {
const zip = new JSZip();
const normalizedDocumentOptions = createDocumentOptionsAndMergeWithDefaults(documentOptions);
let contentHTML = htmlString;
let headerHTML = headerHTMLString;
let footerHTML = footerHTMLString;
if (htmlString && !normalizedDocumentOptions['preprocessing']['skipHTMLMinify']) {
contentHTML = await minifyHTMLString(contentHTML);
}
if (headerHTMLString && !normalizedDocumentOptions['preprocessing']['skipHTMLMinify']) {
headerHTML = await minifyHTMLString(headerHTML);
}
if (footerHTMLString && !normalizedDocumentOptions['preprocessing']['skipHTMLMinify']) {
footerHTML = await minifyHTMLString(footerHTML);
}
await addFilesToContainer(zip, contentHTML, normalizedDocumentOptions, headerHTML, footerHTML);
const buffer = await zip.generateAsync({ type: 'arraybuffer' });
if (Object.prototype.hasOwnProperty.call(global, 'Buffer')) {
return Buffer.from(new Uint8Array(buffer));
}
if (Object.prototype.hasOwnProperty.call(global, 'Blob')) {
// eslint-disable-next-line no-undef
return new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
}
throw new Error(
'Add blob support using a polyfill eg https://github.com/bjornstar/blob-polyfill'
);
}
export default generateContainer;