-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathrtf-to-html.html
More file actions
509 lines (443 loc) · 13.2 KB
/
rtf-to-html.html
File metadata and controls
509 lines (443 loc) · 13.2 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RTF to HTML Converter</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: Helvetica, Arial, sans-serif;
max-width: 1400px;
margin: 0 auto;
padding: 20px;
background: #f5f5f5;
}
h1 {
color: #333;
margin-bottom: 10px;
}
.instructions {
background: #e3f2fd;
border-left: 4px solid #2196f3;
padding: 15px;
margin-bottom: 20px;
border-radius: 4px;
}
.paste-area {
width: 100%;
min-height: 120px;
padding: 15px;
border: 2px dashed #ccc;
border-radius: 8px;
background: white;
font-size: 16px;
margin-bottom: 20px;
outline: none;
transition: border-color 0.3s;
}
.paste-area:focus {
border-color: #2196f3;
border-style: solid;
}
.results {
display: grid;
gap: 20px;
}
.section {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.section h2 {
margin-top: 0;
color: #2196f3;
font-size: 18px;
border-bottom: 2px solid #e0e0e0;
padding-bottom: 10px;
margin-bottom: 15px;
}
.preview-container {
background: #f9f9f9;
border: 1px solid #e0e0e0;
border-radius: 4px;
padding: 0;
overflow-x: auto;
overflow-y: auto;
margin-bottom: 15px;
max-width: 100%;
}
.preview-container pre {
margin: 0;
padding: 15px;
white-space: pre;
overflow-x: visible;
width: max-content;
min-width: 100%;
}
.code-container {
position: relative;
max-width: 100%;
}
.code-output {
width: 100%;
min-height: 200px;
padding: 15px;
border: 1px solid #e0e0e0;
border-radius: 4px;
background: #f9f9f9;
font-family: 'Courier New', monospace;
font-size: 16px;
resize: vertical;
overflow-x: auto;
white-space: pre;
}
.copy-btn {
display: block;
margin-bottom: 10px;
padding: 8px 16px;
background: #2196f3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
font-family: Helvetica, Arial, sans-serif;
width: fit-content;
}
.copy-btn:hover {
background: #1976d2;
}
.copy-btn:active {
background: #0d47a1;
}
.copy-btn.copied {
background: #4caf50;
}
.empty-state {
text-align: center;
color: #999;
padding: 40px;
font-size: 18px;
}
.error {
background: #ffebee;
border-left: 4px solid #f44336;
padding: 15px;
margin-bottom: 20px;
border-radius: 4px;
color: #c62828;
}
</style>
</head>
<body>
<h1>RTF to HTML converter</h1>
<div class="instructions">
<strong>Instructions:</strong> Paste your RTF content below. If RTF format is detected, it will be converted to colorized HTML with inline styles.
</div>
<textarea class="paste-area" placeholder="Click here and paste your RTF content (Cmd+V or Ctrl+V)..."></textarea>
<div class="results" id="results">
<div class="empty-state">Paste RTF content to see the converted HTML</div>
</div>
<script type="module">
const pasteArea = document.querySelector('.paste-area');
const resultsDiv = document.getElementById('results');
function parseRTFColor(colorDef) {
const redMatch = colorDef.match(/\\red(\d+)/);
const greenMatch = colorDef.match(/\\green(\d+)/);
const blueMatch = colorDef.match(/\\blue(\d+)/);
if (redMatch && greenMatch && blueMatch) {
const r = parseInt(redMatch[1]);
const g = parseInt(greenMatch[1]);
const b = parseInt(blueMatch[1]);
return `rgb(${r}, ${g}, ${b})`;
}
return null;
}
function parseRTFColorTable(rtf) {
const colorTableMatch = rtf.match(/\{\\colortbl;([^}]+)\}/);
if (!colorTableMatch) return [];
const colorTable = [null]; // Index 0 is the auto/default color (represented by leading ;)
const colorDefs = colorTableMatch[1].split(';');
for (const colorDef of colorDefs) {
if (colorDef.trim()) { // Skip empty entries
const color = parseRTFColor(colorDef.trim());
colorTable.push(color);
}
}
return colorTable;
}
function rtfToHtml(rtf) {
const colorTable = parseRTFColorTable(rtf);
// Extract the background color and default text color from the initial formatting
let backgroundColor = null;
let defaultTextColor = null;
// Look for the initial color settings: \cf2 \cb3
const initialFormatMatch = rtf.match(/\\f0\\fs\d+\s+\\cf(\d+)\s+\\cb(\d+)/);
if (initialFormatMatch) {
const textColorIndex = parseInt(initialFormatMatch[1]);
const bgColorIndex = parseInt(initialFormatMatch[2]);
defaultTextColor = colorTable[textColorIndex];
backgroundColor = colorTable[bgColorIndex];
}
// Skip all header sections by finding where the actual paragraph content starts
// Look for \pard which marks the start of paragraph content
const pardIndex = rtf.indexOf('\\pard');
if (pardIndex === -1) {
throw new Error('Could not find paragraph content');
}
// Find the pattern that marks the start of actual text content
// Format is typically: \f0\fs20 \cf2 \cb3 \CocoaLigature0 [space] [actual content]
const contentPattern = /\\f0\\fs\d+\s+\\cf\d+\s+\\cb\d+\s+\\CocoaLigature\d+\s+/;
const match = rtf.substring(pardIndex).match(contentPattern);
if (!match) {
throw new Error('Could not find content start marker');
}
const contentStartOffset = pardIndex + match.index + match[0].length;
// Find the last closing brace
const lastBrace = rtf.lastIndexOf('}');
let content = rtf.substring(contentStartOffset, lastBrace);
let html = '';
let i = 0;
let currentColor = defaultTextColor; // Start with the default text color
let currentBgColor = backgroundColor; // Start with the default background color
let isBold = false;
while (i < content.length) {
const char = content[i];
if (char === '\\') {
// Look ahead to see what control word this is
let controlWord = '';
let j = i + 1;
// Check for hex escape \'XX
if (j < content.length && content[j] === "'") {
j++; // skip the '
let hexCode = '';
while (j < content.length && /[0-9a-fA-F]/.test(content[j]) && hexCode.length < 2) {
hexCode += content[j];
j++;
}
if (hexCode.length === 2) {
const charCode = parseInt(hexCode, 16);
html += String.fromCharCode(charCode);
i = j;
continue;
}
}
// Collect the control word
while (j < content.length && /[a-z]/i.test(content[j])) {
controlWord += content[j];
j++;
}
// Get any numeric parameter
let numParam = '';
while (j < content.length && /[0-9]/.test(content[j])) {
numParam += content[j];
j++;
}
// Skip the space after control word if present
if (j < content.length && content[j] === ' ') {
j++;
}
if (controlWord === 'cf') {
// Color change
const colorIndex = parseInt(numParam);
currentColor = colorTable[colorIndex] || defaultTextColor;
i = j;
} else if (controlWord === 'cb') {
// Background color change
const colorIndex = parseInt(numParam);
currentBgColor = colorTable[colorIndex] || backgroundColor;
i = j;
} else if (controlWord === 'b') {
// Bold formatting
if (numParam === '0') {
isBold = false;
} else {
isBold = true;
}
i = j;
} else if (controlWord === 'uc') {
// Unicode character count - skip
i = j;
} else if (controlWord === 'u') {
// Unicode character
const codePoint = parseInt(numParam);
if (codePoint < 0) {
// Negative values need to be converted (two's complement for 16-bit)
const unsigned = 65536 + codePoint;
html += String.fromCharCode(unsigned);
} else {
html += String.fromCharCode(codePoint);
}
// Skip the alternative representation (usually follows \u)
// Look for a space and then skip the next character
if (j < content.length && content[j] === '?') {
j++;
}
i = j;
} else if (controlWord === '') {
// Check for escaped special character or newline
if (i + 1 < content.length) {
const nextChar = content[i + 1];
if (nextChar === '\\') {
html += '\\';
i += 2;
} else if (nextChar === '\n') {
html += '\n';
i += 2;
} else {
// Just a backslash followed by something else
i++;
}
} else {
i++;
}
} else {
// Unknown control word, skip it
i = j;
}
} else if (char === '\n') {
// Preserve line breaks
html += '\n';
i++;
} else {
// Regular character - collect text until we hit a control code or newline
let text = '';
let startPos = i;
while (i < content.length && content[i] !== '\\' && content[i] !== '\n') {
text += content[i];
i++;
}
// Don't trim - preserve spaces
if (text.length > 0) {
const styles = [];
if (currentColor) {
styles.push(`color: ${currentColor}`);
}
if (currentBgColor && currentBgColor !== backgroundColor) {
styles.push(`background: ${currentBgColor}`);
}
if (isBold) {
styles.push('font-weight: bold');
}
if (styles.length > 0) {
html += `<span style="${styles.join('; ')};">${escapeHtml(text)}</span>`;
} else {
html += escapeHtml(text);
}
}
}
}
return { html, backgroundColor, defaultTextColor };
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
pasteArea.addEventListener('paste', async (e) => {
e.preventDefault();
const clipboardData = e.clipboardData;
resultsDiv.innerHTML = '';
if (!clipboardData) {
resultsDiv.innerHTML = '<div class="empty-state">No clipboard data detected</div>';
return;
}
// Look for RTF data
const rtfData = clipboardData.getData('text/rtf');
if (!rtfData) {
resultsDiv.innerHTML = '<div class="error">No RTF format detected in clipboard. Please copy RTF content.</div>';
return;
}
try {
const result = rtfToHtml(rtfData);
const htmlOutput = result.html;
const backgroundColor = result.backgroundColor;
const defaultTextColor = result.defaultTextColor;
// Build the full HTML with background and text color if available
let preStyle = '';
const styles = [];
if (backgroundColor) {
styles.push(`background: ${backgroundColor}`);
}
if (defaultTextColor) {
styles.push(`color: ${defaultTextColor}`);
}
if (styles.length > 0) {
preStyle = ` style="${styles.join('; ')}; padding: 15px; border-radius: 4px;"`;
}
const fullHtml = `<pre${preStyle}>${htmlOutput}</pre>`;
// Create raw RTF section
const rawSection = document.createElement('div');
rawSection.className = 'section';
rawSection.innerHTML = `
<h2>Raw RTF data</h2>
<div class="code-container">
<button class="copy-btn">Copy</button>
<textarea class="code-output" readonly>${escapeHtml(rtfData)}</textarea>
</div>
`;
resultsDiv.appendChild(rawSection);
// Add copy functionality for raw RTF
const rawCopyBtn = rawSection.querySelector('.copy-btn');
const rawTextarea = rawSection.querySelector('.code-output');
rawCopyBtn.addEventListener('click', () => {
rawTextarea.select();
document.execCommand('copy');
rawCopyBtn.textContent = 'Copied!';
rawCopyBtn.classList.add('copied');
setTimeout(() => {
rawCopyBtn.textContent = 'Copy';
rawCopyBtn.classList.remove('copied');
}, 2000);
});
// Create HTML code section
const codeSection = document.createElement('div');
codeSection.className = 'section';
codeSection.innerHTML = `
<h2>HTML code</h2>
<div class="code-container">
<button class="copy-btn">Copy</button>
<textarea class="code-output" readonly>${escapeHtml(fullHtml)}</textarea>
</div>
`;
resultsDiv.appendChild(codeSection);
// Add copy functionality
const copyBtn = codeSection.querySelector('.copy-btn');
const textarea = codeSection.querySelector('.code-output');
copyBtn.addEventListener('click', () => {
textarea.select();
document.execCommand('copy');
copyBtn.textContent = 'Copied!';
copyBtn.classList.add('copied');
setTimeout(() => {
copyBtn.textContent = 'Copy';
copyBtn.classList.remove('copied');
}, 2000);
});
// Create preview section
const previewSection = document.createElement('div');
previewSection.className = 'section';
previewSection.innerHTML = `
<h2>Preview</h2>
<div class="preview-container">
${fullHtml}
</div>
`;
resultsDiv.appendChild(previewSection);
} catch (error) {
resultsDiv.innerHTML = `<div class="error">Error parsing RTF: ${error.message}</div>`;
}
});
// Clear the textarea on paste
pasteArea.addEventListener('paste', () => {
setTimeout(() => {
pasteArea.value = '';
}, 0);
});
</script>
</body>
</html>