forked from privateOmega/html-to-docx
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
63 lines (55 loc) · 1.7 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
/* eslint-disable no-useless-escape */
import JSZip from 'jszip';
import addFilesToContainer from './src/html-to-docx';
const minifyHTMLString = (htmlString) => {
try {
if (typeof htmlString === 'string' || htmlString instanceof String) {
const minifiedHTMLString = htmlString
.replace(/\n/g, ' ')
.replace(/\r/g, ' ')
.replace(/\r\n/g, ' ')
.replace(/[\t]+\</g, '<')
.replace(/\>[\t ]+\</g, '><')
.replace(/\>[\t ]+$/g, '>');
return minifiedHTMLString;
}
throw new Error('invalid html string');
} catch (error) {
return null;
}
};
async function generateContainer(
htmlString,
headerHTMLString,
documentOptions = {},
footerHTMLString
) {
const zip = new JSZip();
let contentHTML = htmlString;
let headerHTML = headerHTMLString;
let footerHTML = footerHTMLString;
if (htmlString) {
contentHTML = minifyHTMLString(contentHTML);
}
if (headerHTMLString) {
headerHTML = minifyHTMLString(headerHTML);
}
if (footerHTMLString) {
footerHTML = minifyHTMLString(footerHTML);
}
addFilesToContainer(zip, contentHTML, documentOptions, headerHTML, footerHTML);
const buffer = await zip.generateAsync({ type: 'arraybuffer' });
if (Object.prototype.hasOwnProperty.call(global, 'Blob')) {
// eslint-disable-next-line no-undef
return new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
}
if (Object.prototype.hasOwnProperty.call(global, 'Buffer')) {
return Buffer.from(new Uint8Array(buffer));
}
throw new Error(
'Add blob support using a polyfill eg https://github.com/bjornstar/blob-polyfill'
);
}
export default generateContainer;