-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdocx2html.js
More file actions
59 lines (53 loc) · 1.74 KB
/
Copy pathdocx2html.js
File metadata and controls
59 lines (53 loc) · 1.74 KB
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
import mammoth from './mammoth/mammoth.browser'
const monospaceFonts = ["consolas", "courier", "courier new"];
let options = {
transformDocument: mammoth.transforms.paragraph(transformParagraph),
preserveColors: true,
preserveFonts: true,
styleMap: [
"p[style-name='Title'] => h1:fresh",
"p[style-name='Heading 1'] => h1:fresh",
"p[style-name='Heading 2'] => h2:fresh",
"p[style-name='Heading 3'] => h3:fresh",
"p[style-name='Heading 4'] => h4:fresh",
"p[style-name='Heading 5'] => h5:fresh",
"p[style-name='Heading 6'] => h6:fresh",
],
convertImage: mammoth.images.imgElement(function(image) {
return image.read().then(function(buffer) {
let file = new File([buffer], {type: image.contentType})
let url = URL.createObjectURL(file);
return {
src: url,
width: image.width,
height: image.height,
style: image.style
};
});
})
}
export default async function docx2html(blob){
try {
let arrayBuffer = await blob.arrayBuffer();
let result = await mammoth.convertToHtml({arrayBuffer}, options);
return result.value;
} catch (error) {
console.log(error);
return '';
}
}
function transformParagraph(paragraph) {
var runs = mammoth.transforms.getDescendantsOfType(paragraph, "run");
var isMatch = runs.length > 0 && runs.every(function(run) {
return run.font && monospaceFonts.indexOf(run.font.toLowerCase()) !== -1;
});
if (isMatch) {
return {
...paragraph,
styleId: "code",
styleName: "Code"
};
} else {
return paragraph;
}
}