-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrtftohtml.pas
More file actions
736 lines (699 loc) · 19.5 KB
/
Copy pathrtftohtml.pas
File metadata and controls
736 lines (699 loc) · 19.5 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//-----------------------------------------------------------------------------------
// RichKit Package © 2026 by Alexander Tverskoy
// Licensed under the MIT License
// You may obtain a copy of the License at https://opensource.org/licenses/MIT
//-----------------------------------------------------------------------------------
unit RtfToHtml;
{$mode objfpc}{$H+}
interface
// Convert RTF string to HTML
function ConvertRtfToHtml(const Rtf: string): string;
implementation
uses
SysUtils, Classes, StrUtils, LConvEncoding, LazUTF8;
const
MaxListLevel = 9; // Maximum nesting level for lists
type
TRtfState = record
Bold: boolean;
Italic: boolean;
Underline: boolean;
FontName: string; // Font family name for current run
FontSize: integer; // Font size in half-points, 0 means default
end;
TListInfo = record
ListType: string; // 'ul' or 'ol'
Indent: integer; // List indent in twips
end;
function EscapeHtml(const S: string): string;
begin
Result := S;
Result := StringReplace(Result, '&', '&', [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
Result := StringReplace(Result, '"', '"', [rfReplaceAll]);
Result := StringReplace(Result, '''', ''', [rfReplaceAll]);
end;
function FormatText(const S: string; State: TRtfState): string;
var
Escaped, StyleStr: string;
begin
Escaped := EscapeHtml(S);
if State.Bold then
Escaped := '<strong>' + Escaped + '</strong>';
if State.Italic then
Escaped := '<em>' + Escaped + '</em>';
if State.Underline then
Escaped := '<u>' + Escaped + '</u>';
StyleStr := '';
if State.FontName <> '' then
StyleStr := StyleStr + 'font-family: ' + State.FontName;
if State.FontSize > 0 then
begin
if StyleStr <> '' then StyleStr := StyleStr + '; ';
StyleStr := StyleStr + 'font-size: ' + IntToStr(State.FontSize div 2) + 'pt';
end;
if StyleStr <> '' then
Escaped := '<span style="' + StyleStr + ';">' + Escaped + '</span>';
Result := Escaped;
end;
function ConvertRtfToHtml(const Rtf: string): string;
var
i: integer;
ch: char;
state: TRtfState;
rawBytes: ansistring;
html: string;
groupStates: array of TRtfState = nil;
groupDepth: integer;
skipGroupDepth: integer;
inSkipGroup: boolean;
controlWord: string;
param: integer;
hasParam: boolean;
startPos: integer;
hexStr: string;
codepage: string;
unicodeSkip: integer;
currentRunText: string;
currentRunFormat: TRtfState;
paragraphText: string;
// List handling
listLevel: integer;
listStack: array[0..MaxListLevel] of TListInfo;
// Current list item state
inListItem: boolean;
currentListItemContent: string;
// Current paragraph indent in twips
currentIndent: integer;
// Marker group handling
inListItemMarker: boolean;
markerText: string;
// Font table
FontTable: array of string;
IsFontTable: boolean;
FontTableDepth: integer;
FontTableText: string;
function IsOnlyWhitespaceHtml(const S: string): boolean;
var
i: integer;
inTag: boolean;
begin
Result := True;
inTag := False;
for i := 1 to Length(S) do
begin
if S[i] = '<' then inTag := True
else if S[i] = '>' then inTag := False
else if not inTag then
if not (S[i] in [' ', #9, #10, #13]) then
begin
Result := False;
Exit;
end;
end;
end;
function IsIgnorableGroupStart(const RtfStr: string; pos: integer): boolean;
var
p: integer;
wordStart: integer;
word: string;
begin
Result := False;
if pos > Length(RtfStr) then Exit;
p := pos;
while (p <= Length(RtfStr)) and (RtfStr[p] in [#9, #10, #13, ' ']) do Inc(p);
if p > Length(RtfStr) then Exit;
if RtfStr[p] = '\' then
begin
Inc(p);
if p <= Length(RtfStr) then
begin
if RtfStr[p] = '*' then
begin
Result := True;
Exit;
end;
if RtfStr[p] in ['a'..'z', 'A'..'Z'] then
begin
wordStart := p;
while (p <= Length(RtfStr)) and (RtfStr[p] in ['a'..'z', 'A'..'Z']) do Inc(p);
word := LowerCase(Copy(RtfStr, wordStart, p - wordStart));
if (word = 'colortbl') or (word = 'stylesheet') or (word = 'info') or (word = 'generator') or
(word = 'mmathpr') or (word = 'viewkind') or (word = 'nouicompat') or (word = 'mwrapindent') or
(word = 'mmathfont') then
Result := True;
end;
end;
end;
end;
procedure FlushRawBytes;
var
converted: string;
begin
if rawBytes <> '' then
begin
converted := LConvEncoding.ConvertEncoding(rawBytes, codepage, 'utf8');
currentRunText := currentRunText + converted;
rawBytes := '';
end;
end;
procedure FlushRun;
begin
FlushRawBytes;
if currentRunText <> '' then
begin
paragraphText := paragraphText + FormatText(currentRunText, currentRunFormat);
currentRunText := '';
end;
end;
procedure CloseCurrentListItem;
begin
if inListItem then
begin
html := html + '<li>' + currentListItemContent + '</li>' + LineEnding;
inListItem := False;
currentListItemContent := '';
end;
end;
procedure CloseListLevelsAbove(NewLevel: integer);
begin
while listLevel > NewLevel do
begin
CloseCurrentListItem;
html := html + '</' + listStack[listLevel].ListType + '>' + LineEnding;
Dec(listLevel);
end;
end;
procedure UpdateListLevel(Indent: integer; ListType: string);
begin
// Close levels with deeper indent
while (listLevel > 0) and (listStack[listLevel].Indent > Indent) do
begin
CloseCurrentListItem;
html := html + '</' + listStack[listLevel].ListType + '>' + LineEnding;
Dec(listLevel);
end;
if listLevel = 0 then
begin
// Start a new list at level 1
Inc(listLevel);
listStack[listLevel].ListType := ListType;
listStack[listLevel].Indent := Indent;
html := html + '<' + ListType + '>' + LineEnding;
end
else if listStack[listLevel].Indent = Indent then
begin
// Same indent level, check list type
if listStack[listLevel].ListType <> ListType then
begin
// Close current list and start a new one of different type
CloseCurrentListItem;
html := html + '</' + listStack[listLevel].ListType + '>' + LineEnding;
listStack[listLevel].ListType := ListType;
html := html + '<' + ListType + '>' + LineEnding;
end;
end
else if listStack[listLevel].Indent < Indent then
begin
// Deeper level
if listLevel < MaxListLevel then
begin
Inc(listLevel);
listStack[listLevel].ListType := ListType;
listStack[listLevel].Indent := Indent;
html := html + '<' + ListType + '>' + LineEnding;
end;
end;
end;
procedure EndParagraph;
var
trimmed: string;
begin
FlushRun;
trimmed := Trim(paragraphText);
paragraphText := '';
if trimmed = '' then Exit;
if IsOnlyWhitespaceHtml(trimmed) then Exit;
if inListItem then
begin
// Continuation of current list item
currentListItemContent := currentListItemContent + '<br>' + trimmed;
end
else
begin
// Regular paragraph outside list
CloseCurrentListItem;
CloseListLevelsAbove(0);
html := html + '<p>' + trimmed + '</p>' + LineEnding;
end;
end;
procedure ProcessMarkerGroup;
var
marker, listType: string;
begin
marker := Trim(markerText);
if marker = '' then Exit;
if (marker = '\bullet') or (marker = '•') or (marker = '·') or (marker = '◦') then
listType := 'ul'
else if (Length(marker) > 1) and (marker[1] in ['0'..'9']) and (marker[Length(marker)] in ['.', ')', ':']) then
listType := 'ol'
else
Exit;
// Close previous list item if any
CloseCurrentListItem;
// Update list level based on currentIndent
UpdateListLevel(currentIndent, listType);
// Start accumulating new list item
currentListItemContent := '';
inListItem := True;
end;
procedure ParseFontTable(const S: string);
var
i, j, p, nameStart: integer;
num: integer;
Name: string;
begin
SetLength(FontTable, 0);
i := 1;
while i <= Length(S) do
begin
if (i + 1 <= Length(S)) and (S[i] = '\') and (S[i + 1] = 'f') then
begin
j := i + 2;
while (j <= Length(S)) and (S[j] in ['0'..'9']) do Inc(j);
if j > i + 2 then
begin
num := StrToIntDef(Copy(S, i + 2, j - (i + 2)), -1);
if num >= 0 then
begin
p := j;
while p <= Length(S) do
begin
if S[p] = '\' then
begin
Inc(p);
if (p <= Length(S)) and (S[p] in ['a'..'z', 'A'..'Z']) then
begin
while (p <= Length(S)) and (S[p] in ['a'..'z', 'A'..'Z']) do Inc(p);
while (p <= Length(S)) and (S[p] in ['0'..'9']) do Inc(p);
if (p <= Length(S)) and (S[p] = ' ') then Inc(p);
end
else
begin
Inc(p, 2);
end;
end
else if (S[p] = ';') or (S[p] = '}') then
begin
break;
end
else if S[p] = '{' then
begin
Inc(p);
while (p <= Length(S)) and (S[p] <> '}') do Inc(p);
if p <= Length(S) then Inc(p);
end
else
begin
nameStart := p;
while (p <= Length(S)) and (S[p] <> ';') and (S[p] <> '}') do Inc(p);
Name := Trim(Copy(S, nameStart, p - nameStart));
if num >= Length(FontTable) then
SetLength(FontTable, num + 1);
FontTable[num] := Name;
i := p;
break;
end;
end;
end;
end;
if i < j then i := j;
end
else
Inc(i);
end;
end;
begin
// Initialize variables
state.Bold := False;
state.Italic := False;
state.Underline := False;
state.FontName := '';
state.FontSize := 0;
rawBytes := '';
html := '';
groupDepth := 0;
skipGroupDepth := 0;
inSkipGroup := False;
codepage := 'cp1252';
unicodeSkip := 1;
currentRunText := '';
currentRunFormat := state;
paragraphText := '';
listLevel := 0;
for i := 0 to MaxListLevel do
begin
listStack[i].ListType := '';
listStack[i].Indent := 0;
end;
inListItem := False;
currentListItemContent := '';
currentIndent := 0;
inListItemMarker := False;
markerText := '';
SetLength(groupStates, 1);
groupStates[0] := state;
SetLength(FontTable, 0);
IsFontTable := False;
FontTableDepth := 0;
FontTableText := '';
i := 1;
while i <= Length(Rtf) do
begin
ch := Rtf[i];
if inSkipGroup then
begin
if ch = '{' then
Inc(skipGroupDepth)
else if ch = '}' then
begin
Dec(skipGroupDepth);
if skipGroupDepth = 0 then
inSkipGroup := False;
end;
Inc(i);
continue;
end;
if IsFontTable then
begin
if ch = '{' then
Inc(FontTableDepth)
else if ch = '}' then
begin
Dec(FontTableDepth);
if FontTableDepth = 0 then
begin
ParseFontTable(FontTableText);
IsFontTable := False;
Inc(i);
continue;
end;
end
else
FontTableText := FontTableText + ch;
Inc(i);
continue;
end;
if ch = '{' then
begin
if (i + 8 <= Length(Rtf)) and (LowerCase(Copy(Rtf, i + 1, 8)) = '\fonttbl') then
begin
FlushRun;
IsFontTable := True;
FontTableDepth := 1;
FontTableText := '';
Inc(i);
continue;
end;
// Detect list marker group \pntext or \listtext
if (i + 8 <= Length(Rtf)) and (LowerCase(Copy(Rtf, i + 1, 7)) = '\pntext') then
begin
FlushRun;
inListItemMarker := True;
markerText := '';
Inc(i);
continue;
end
else if (i + 9 <= Length(Rtf)) and (LowerCase(Copy(Rtf, i + 1, 8)) = '\listtext') then
begin
FlushRun;
inListItemMarker := True;
markerText := '';
Inc(i);
continue;
end;
if IsIgnorableGroupStart(Rtf, i + 1) then
begin
inSkipGroup := True;
skipGroupDepth := 1;
Inc(i);
continue;
end;
FlushRun;
Inc(groupDepth);
SetLength(groupStates, groupDepth + 1);
groupStates[groupDepth] := state;
Inc(i);
continue;
end
else if ch = '}' then
begin
FlushRun;
if inListItemMarker then
begin
inListItemMarker := False;
ProcessMarkerGroup;
end
else if groupDepth > 0 then
begin
state := groupStates[groupDepth];
Dec(groupDepth);
SetLength(groupStates, groupDepth + 1);
currentRunFormat := state;
end;
Inc(i);
continue;
end
else if ch = '\' then
begin
if i < Length(Rtf) then
begin
if Rtf[i + 1] = '{' then
begin
rawBytes := rawBytes + ansichar('{');
Inc(i, 2);
continue;
end
else if Rtf[i + 1] = '}' then
begin
rawBytes := rawBytes + ansichar('}');
Inc(i, 2);
continue;
end
else if Rtf[i + 1] = '\' then
begin
rawBytes := rawBytes + ansichar('\');
Inc(i, 2);
continue;
end
else if Rtf[i + 1] in ['a'..'z', 'A'..'Z'] then
begin
Inc(i);
startPos := i;
while (i <= Length(Rtf)) and (Rtf[i] in ['a'..'z', 'A'..'Z']) do
Inc(i);
controlWord := LowerCase(Copy(Rtf, startPos, i - startPos));
param := 0;
hasParam := False;
if (i <= Length(Rtf)) and (Rtf[i] = '-') then
begin
Inc(i);
while (i <= Length(Rtf)) and (Rtf[i] in ['0'..'9']) do Inc(i);
hasParam := True;
end
else if (i <= Length(Rtf)) and (Rtf[i] in ['0'..'9']) then
begin
startPos := i;
while (i <= Length(Rtf)) and (Rtf[i] in ['0'..'9']) do Inc(i);
param := StrToIntDef(Copy(Rtf, startPos, i - startPos), 0);
hasParam := True;
end;
// Skip only one delimiter space if present
if (i <= Length(Rtf)) and (Rtf[i] = ' ') then
Inc(i);
if controlWord = 'b' then
begin
FlushRun;
state.Bold := (not hasParam) or (param <> 0);
currentRunFormat := state;
end
else if controlWord = 'i' then
begin
FlushRun;
state.Italic := (not hasParam) or (param <> 0);
currentRunFormat := state;
end
else if controlWord = 'ul' then
begin
FlushRun;
state.Underline := (not hasParam) or (param <> 0);
currentRunFormat := state;
end
else if controlWord = 'fs' then
begin
FlushRun;
state.FontSize := param;
currentRunFormat := state;
end
else if controlWord = 'pard' then
begin
currentIndent := 0;
end
else if controlWord = 'li' then
begin
if hasParam then
currentIndent := param
else
currentIndent := 0;
end
else if controlWord = 'par' then
begin
EndParagraph;
end
else if controlWord = 'line' then
begin
FlushRun;
paragraphText := paragraphText + '<br>';
end
else if controlWord = 'tab' then
begin
FlushRawBytes;
currentRunText := currentRunText + ' ';
end
else if controlWord = 'bullet' then
begin
FlushRawBytes;
if inListItemMarker then
markerText := markerText + '\bullet'
else
currentRunText := currentRunText + '•';
end
else if controlWord = 'endash' then
begin
FlushRawBytes;
currentRunText := currentRunText + '–';
end
else if controlWord = 'emdash' then
begin
FlushRawBytes;
currentRunText := currentRunText + '—';
end
else if controlWord = 'lquote' then
begin
FlushRawBytes;
currentRunText := currentRunText + '‘';
end
else if controlWord = 'rquote' then
begin
FlushRawBytes;
currentRunText := currentRunText + '’';
end
else if controlWord = 'ldblquote' then
begin
FlushRawBytes;
currentRunText := currentRunText + '“';
end
else if controlWord = 'rdblquote' then
begin
FlushRawBytes;
currentRunText := currentRunText + '”';
end
else if controlWord = 'ansicpg' then
begin
if hasParam then
begin
case param of
1251: codepage := 'cp1251';
1252: codepage := 'cp1252';
65001: codepage := 'utf8';
else
codepage := 'cp1252';
end;
end;
end
else if controlWord = 'uc' then
begin
if hasParam then
unicodeSkip := param;
end
else if controlWord = 'u' then
begin
FlushRawBytes;
if hasParam then
currentRunText := currentRunText + UTF8Encode(widechar(param));
for startPos := 1 to unicodeSkip do
begin
if (i <= Length(Rtf)) and (Rtf[i] <> ' ') then
Inc(i);
end;
end
else if controlWord = 'f' then
begin
FlushRun;
if hasParam and (param >= 0) and (param < Length(FontTable)) then
state.FontName := FontTable[param]
else
state.FontName := '';
currentRunFormat := state;
end
else if controlWord = 'lang' then
begin
FlushRun;
currentRunFormat := state;
end;
continue;
end
else
begin
case Rtf[i + 1] of
#39:
begin
if i + 2 <= Length(Rtf) then
begin
hexStr := Copy(Rtf, i + 2, 2);
try
rawBytes := rawBytes + ansichar(StrToInt('$' + hexStr));
except
end;
Inc(i, 4);
end;
end;
'~':
begin
rawBytes := rawBytes + ansichar(' ');
Inc(i, 2);
end;
'-':
begin
rawBytes := rawBytes + ansichar('-');
Inc(i, 2);
end;
else
Inc(i, 2);
end;
continue;
end;
end
else
begin
rawBytes := rawBytes + ansichar('\');
Inc(i);
continue;
end;
end
else
begin
rawBytes := rawBytes + ansichar(ch);
Inc(i);
end;
end;
// Finalize any remaining paragraph
EndParagraph;
// Close any open list item
CloseCurrentListItem;
// Close all open lists
CloseListLevelsAbove(0);
Result := html;
end;
end.