-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTMLToRTF.js
More file actions
281 lines (237 loc) · 9.54 KB
/
HTMLToRTF.js
File metadata and controls
281 lines (237 loc) · 9.54 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
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
/**
* HTML -> RTF converter (MS Word 97 compatible)
* Used reference: https://www.biblioscape.com/rtf15_spec.htm , https://latex2rtf.sourceforge.net/RTF-Spec-1.5.pdf
*/
function rowsToArray(t) {
if (!t) return [];
return t.replace(/\r\n|\r/g, '\n').split('\n');
}
function HTMLToRTF(parent, header, activeLanguage, config, ctx, document, author) {
function clearHash(text) {
let cleanedText = text;
if (text.endsWith('#'))
cleanedText = text.substring(0, text.length - 1);
return encodeToUTF(cleanedText.trim());
}
const handlerBold = (node, ctx, children) => `{\\b ${encodeToUTF(children)}\\b0}`;
function getLabel(node) {
const found = [... node?.childNodes].filter(x => x.getAttribute)
.map(x => x.getAttribute('href')?.substring(1).replace(/[-.]/g, '_') || x.id).filter(x => x)
.map(x => `{\\*\\bkmkstart sec_${x}}{\\*\\bkmkend sec_${x}}`).join('') || '';
return found;
}
function escapeRTF(text) {
if (!text) return '';
return text
.replace(/\\/g, '\\\\')
.replace(/{/g, '\\{')
.replace(/}/g, '\\}')
.replace(/\r\n|\r|\n/g, '\\par ');
}
const handlers = {
ul: (node, ctx, children) => {
ctx.listStack.push('itemize');
const body = children;
ctx.listStack.pop();
return body;
},
ol: (node, ctx, children) => {
ctx.listStack.push('enumerate');
const body = children;
ctx.listStack.pop();
return body;
},
li: (node, ctx, children) => {
const level = ctx.listStack ? ctx.listStack.length : 1;
const indentTwips = 720 * level; // 720 twips = 0.5 inch cca. 12pt
const isEnum = (ctx.listStack && ctx.listStack[ctx.listStack.length - 1] === 'enumerate');
if (isEnum) {
// simplified - no counter
return `{\\pard\\li${indentTwips} ${escapeRTF('1.')}\\tab ${children}\\par}\n`;
} else {
// bullet
return `{\\pard\\li${indentTwips} \\bullet\\tab ${children}\\par}\n`;
}
},
img: (node, ctx, children) => {
ctx.i_img = (ctx.i_img || 0) + 1;
const embed = ctx.embeds.get ? ctx.embeds.get(node.src) : null;
let pict = '';
function base64ToHex(base64) {
if (typeof base64 !== 'string') return '';
base64 = base64.replace(/\s+/g, '').replace(/-/g, '+').replace(/_/g, '/');
const pad = base64.length % 4;
if (pad) base64 += '='.repeat(4 - pad);
try {
const raw = atob(base64);
const bytes = Uint8Array.from(raw, c => c.charCodeAt(0));
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
} catch (e) {
return '';
}
}
if (embed) {
let format = 'png';
let hex = '';
if (typeof embed === 'object') {
format = embed.format || 'png';
if (embed.data && embed.data.startsWith('data:')) {
const matches = embed.data.match(/base64,(.*)$/);
if (matches) hex = base64ToHex(matches[1]);
} else if (embed.data && /^[0-9a-fA-F]+$/.test(embed.data)) {
hex = embed.data;
} else if (embed.data) {
hex = base64ToHex(embed.data);
}
} else if (typeof embed === 'string' && embed.startsWith('data:')) {
const m = embed.match(/base64,(.*)$/);
if (m) hex = base64ToHex(m[1]);
// try infer format
if (embed.indexOf('image/jpeg') >= 0) format = 'jpeg';
else if (embed.indexOf('image/png') >= 0) format = 'png';
}
let control = '\\pngblip';
if (format === 'jpeg' || format === 'jpg') control = '\\jpegblip';
else if (format === 'wmf' || format === 'emf') control = '\\wmetafile8';
if (hex) {
pict = `{\\pard\\qc{\\pict${control}\n${hex}}\\par}\n`;
} else {
// fallback: not any data
pict = `{\\pard\\qc [Image ${ctx.i_img} - not embedded] \\par}\n`;
}
} else {
pict = `{\\pard\\qc [Image ${ctx.i_img} - missing] \\par}\n`;
}
const caption = node.getAttribute('title') || '';
const cap = caption ? `{\\pard\\qc \\i ${escapeRTF(caption)}\\i0 \\par}\n` : '';
return pict + cap;
},
svg: (node, ctx, children) => {
// RTF not support SVG!
// TODO: convert SVG to PNG via canvas and embed as image?
ctx.i_svg = (ctx.i_svg || 0) + 1;
//const embed = ctx.embeds.get ? ctx.embeds.get(node) : null;
// Reuse img handler logic via fake node
return handlers.img(node, ctx, children);
},
h1: (node, ctx, children) => `{\\pard{\\s1 ${clearHash(children)}${getLabel(node)}\\par}\n`,
h2: (node, ctx, children) => `{\\pard{\\s2 ${clearHash(children)}${getLabel(node)}\\par}\n`,
h3: (node, ctx, children) => `{\\pard{\\s3 ${clearHash(children)}${getLabel(node)}\\par}\n`,
h4: (node, ctx, children) => `{\\pard{\\s4 ${clearHash(children)}${getLabel(node)}\\par}\n`,
h5: (node, ctx, children) => `{\\pard{\\s5 ${clearHash(children)}${getLabel(node)}\\par}\n`,
h6: (node, ctx, children) => `{\\pard{\\s6 ${clearHash(children)}${getLabel(node)}\\par}\n`,
p: (node, ctx, children) => `{\\pard ${children}\\par}\n`,
div: (node, ctx, children) => {
if (node.classList && (node.classList.contains('toolbar-item') || node.classList.contains('toolbar')))
return '';
if (node.classList && node.classList.contains('page-break'))
return '\\page\n';
return children;
},
code: (node, ctx, children) => {
// No language -> monospace
const codeText = node.textContent || '';
const escaped = escapeRTF(codeText);
return `{\\pard\\f1\\fs20 ${escaped}\\par}\n`;
},
strong: handlerBold,
b: handlerBold,
em: (node, ctx, children) => `{\\i ${children}\\i0}`,
table: (node, ctx, children) => {
return `${children}\n`;
},
thead: (node, ctx, children) => {
const cols = rowsToArray(children.trim());
const boldCols = cols.map(c => `{\\b ${escapeRTF(c).replace(/\\\\par/g, '\\tab')}\\b0}`).join('\\tab ').replace(/ \\tab \\tab/g, '').replace(/\\tab/g, '\\tab \\tab');
return `${boldCols} \\par\n`;
},
td: (node, ctx, children) => {
return `${children}\\tab `;
},
tr: (node, ctx, children) => {
if (node.parentElement && node.parentElement.tagName && node.parentElement.tagName.toLowerCase() === 'thead')
return children;
const tds = Array.from(node.children).filter(child => {
const t = child.tagName && child.tagName.toLowerCase();
return t === 'td' || t === 'th';
});
if (tds.length === 0) {
return `${children}\\par\n`;
}
const colTexts = tds.map(td => walk(td, ctx));
return colTexts.join('') + '\\par\n';
},
a: (node, ctx, children) => {
if (children.trim().replace('\\#', '#').length == 1)
return '';
let href = node.getAttribute('id') || '';
if (href && node.parentElement.tagName.toLowerCase().substring(0, 1) == 'h')
return;
// local text hyperlink
href = node.getAttribute('href') || '';
href = decodeURI(href || '');
if (href.startsWith('http')) {
// external link (http)
// RTF: {\field{\*\fldinst HYPERLINK "url"}{\fldrslt display}}
return `{\\field{\\*\\fldinst HYPERLINK "${href}"}{\\fldrslt ${encodeToUTF(children)}}}`;
}
const rawHref = node.getAttribute('href')?.replace(/[-.]/g, '_') || '';
if (rawHref.startsWith('#')) {
const name = rawHref.substring(1);
// link to bookmark (chapter)
return `{\\field{\\*\\fldinst HYPERLINK \\\\l "sec_${name.replace(/[-.]/g, '_')}"}{\\fldrslt ${encodeToUTF(children)}}}`;
} else {
try {
const absolute = node.href ? decodeURI(node.href) : href;
if (!absolute)
return;
return `{\\field{\\*\\fldinst HYPERLINK "${absolute}"}{\\fldrslt ${encodeToUTF(children)}}}`;
} catch (e) {
return children;
}
}
},
script: (node, ctx, children) => '',
style: (node, ctx, children) => '',
br: (node, ctx, children) => `\\line ${children}`,
summary: (node, ctx, children) => `${children}\\par`,
default: (node, ctx, children) => encodeToUTF(children)
};
// function encodeToUTF(text) {
// const bytes = encoder.encode(text);
// let rtfText = Array.from(bytes)
// .map(b => `\\\\'${b.toString(16).padStart(2,'0')}`).join('');
// return rtfText;
// }
function encodeToUTF(rtfText) {
// let rtfText = '';
// for (let i = 0; i < text.length; i++) {
// const cp = text.codePointAt(i);
// let uCode = cp;
// if (cp > 0xFFFF) {
// uCode = 0x110000 - cp;
// }
// rtfText += `\\u${-uCode}?`;
// if (cp > 0xFFFF) i++;
// }
return rtfText;
}
function walk(node, ctx) {
if (node.nodeType === Node.TEXT_NODE)
return escapeRTF(node.textContent);
const children = Array.from(node.childNodes)
.map(child => walk(child, ctx))
.join('');
const tag = node.nodeName.toLowerCase();
const handler = handlers[tag] || handlers.default;
return handler(node, ctx, children);
}
document = document.replace(/_AUTH_/g, author);
document = document.replace(/_DOCNAME_/g, header);
document = document.replace(/_LANG_/g, config[activeLanguage] || activeLanguage);
let rtfBody = walk(parent, ctx);
rtfBody = rtfBody.replace(/\\par\s*\{\s*\\pard{\\s/g, '\\pard{\\s');
rtfBody = rtfBody.replace(/ {\\pard \\par}/g, '');
rtfBody = rtfBody.replace(/{\\pard{\\s/, '\\pard{\\s');
return [document, rtfBody];
}