forked from privateOmega/html-to-docx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
68 lines (61 loc) · 1.66 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
import JSZip from "jszip"
import addFilesToContainer from "./src/html-to-docx.ts"
function 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) {
console.error(error)
}
}
export default async function generateContainer(
htmlString,
headerHTMLString,
documentOptions = {},
footerHTMLString?: string,
) {
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)
}
await addFilesToContainer(
zip,
contentHTML,
documentOptions,
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")) {
return new Blob([buffer], {
type: "application/" +
"vnd.openxmlformats-officedocument.wordprocessingml.document",
})
}
throw new Error(
"Add blob support using a polyfill. " +
"E.g. https://github.com/bjornstar/blob-polyfill",
)
}