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
//! RTF (Rich Text Format) converter implementation
//!
//! Converts RTF files to Markdown by parsing RTF commands and extracting text.
#![allow(clippy::unused_self, clippy::uninlined_format_args)]
use std::path::Path;
use async_trait::async_trait;
use tokio::fs;
use super::traits::{ConverterMetadata, DocumentConverter};
use crate::Result;
use crate::types::{
ConversionOptions, ConversionOutput, ConversionResult, FileFormat, OutputFormat, OutputMetadata,
};
/// RTF to Markdown converter
#[derive(Debug)]
pub struct RtfConverter;
impl RtfConverter {
/// Create a new RTF converter
pub fn new() -> Self {
Self
}
/// Parse RTF and convert to plain text/Markdown
/// This is a simplified RTF parser that extracts text content
fn rtf_to_markdown(&self, rtf: &str) -> String {
let mut markdown = String::new();
markdown.push_str("# Document\n\n");
let mut text_content = String::new();
let mut in_control_word = false;
let mut brace_depth = 0;
let mut skip_next = false;
let chars: Vec<char> = rtf.chars().collect();
let mut i = 0;
while i < chars.len() {
let ch = chars[i];
if skip_next {
skip_next = false;
i += 1;
continue;
}
match ch {
'{' => {
brace_depth += 1;
}
'}' => {
brace_depth -= 1;
in_control_word = false;
}
'\\' => {
// Check for control word
if i + 1 < chars.len() {
let next_ch = chars[i + 1];
// Escape sequences
if next_ch == '\\' || next_ch == '{' || next_ch == '}' {
text_content.push(next_ch);
skip_next = true;
} else if next_ch == '\'' {
// Hex escape \'XX
if i + 3 < chars.len() {
i += 3; // Skip \'XX
}
} else if next_ch == 'p'
&& i + 3 < chars.len()
&& chars[i + 2] == 'a'
&& chars[i + 3] == 'r'
{
// Paragraph break
text_content.push_str("\n\n");
i += 3;
} else if next_ch == 't'
&& i + 3 < chars.len()
&& chars[i + 2] == 'a'
&& chars[i + 3] == 'b'
{
// Tab
text_content.push('\t');
i += 3;
} else {
// Skip control word
in_control_word = true;
i += 1;
while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '*')
{
i += 1;
}
// Skip optional space after control word
if i < chars.len() && chars[i] == ' ' {
i += 1;
}
i -= 1; // Adjust because we'll increment at the end
}
}
}
_ if brace_depth > 0 && !in_control_word && ch >= ' ' => {
// Regular text character
text_content.push(ch);
}
_ => {}
}
i += 1;
}
// Clean up text: remove extra spaces and add paragraphs
let paragraphs: Vec<&str> = text_content
.split("\n\n")
.map(|p| p.trim())
.filter(|p| !p.is_empty())
.collect();
for para in paragraphs {
// Detect potential headings
if para.len() < 80
&& (para
.chars()
.all(|c| !c.is_lowercase() || !c.is_alphabetic())
|| para.ends_with(':'))
{
markdown.push_str(&format!("## {}\n\n", para));
} else {
markdown.push_str(&format!("{}\n\n", para));
}
}
if markdown.trim() == "# Document" {
markdown.push_str("*No text content extracted from RTF*\n");
}
markdown
}
}
impl Default for RtfConverter {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl DocumentConverter for RtfConverter {
fn supported_formats(&self) -> Vec<FileFormat> {
vec![FileFormat::Rtf]
}
fn output_formats(&self) -> Vec<OutputFormat> {
vec![
OutputFormat::Markdown {
split_pages: false,
optimize_for_llm: true,
},
OutputFormat::Json {
structured: true,
include_metadata: true,
},
]
}
async fn convert(
&self,
input: &Path,
output_format: OutputFormat,
_options: ConversionOptions,
) -> Result<ConversionResult> {
eprintln!("🔄 RTF Conversion (Pure Rust)");
eprintln!(" RTF → Parsing → {:?}", output_format);
eprintln!();
// Read RTF file
let rtf_content = fs::read_to_string(input).await?;
// Convert to requested format
let output_data = match output_format {
OutputFormat::Markdown { .. } => {
eprintln!("📝 Converting to Markdown...");
let markdown = self.rtf_to_markdown(&rtf_content);
markdown.into_bytes()
}
OutputFormat::Json { .. } => {
eprintln!("📝 Converting to JSON...");
let text = self.rtf_to_markdown(&rtf_content);
let json = serde_json::json!({
"text": {
"content": text,
"format": "rtf",
}
});
serde_json::to_string_pretty(&json)?.into_bytes()
}
_ => {
return Err(crate::TransmutationError::UnsupportedFormat(format!(
"Output format {:?} not supported for RTF",
output_format
)));
}
};
let output_size = output_data.len() as u64;
let input_size = fs::metadata(input).await?.len();
eprintln!("✅ RTF conversion complete!");
Ok(ConversionResult {
input_path: input.to_path_buf(),
input_format: FileFormat::Rtf,
output_format,
content: vec![ConversionOutput {
page_number: 1,
data: output_data,
metadata: OutputMetadata {
size_bytes: output_size,
chunk_count: 1,
token_count: None,
},
}],
metadata: crate::types::DocumentMetadata {
title: None,
author: None,
created: None,
modified: None,
page_count: 1,
language: None,
custom: std::collections::HashMap::new(),
},
statistics: crate::types::ConversionStatistics {
input_size_bytes: input_size,
output_size_bytes: output_size,
duration: std::time::Duration::from_secs(0),
pages_processed: 1,
tables_extracted: 0,
images_extracted: 0,
cache_hit: false,
},
})
}
fn metadata(&self) -> ConverterMetadata {
ConverterMetadata {
name: "RTF Converter".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
description: "RTF to Markdown converter (pure Rust, simplified parser)".to_string(),
external_deps: vec![],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rtf_converter_creation() {
let converter = RtfConverter::new();
assert_eq!(converter.supported_formats(), vec![FileFormat::Rtf]);
}
#[test]
fn test_rtf_to_markdown_basic() {
let converter = RtfConverter::new();
// RTF with actual text commands
let rtf = r"{\rtf1\ansi\deff0 {\fonttbl {\f0 Times New Roman;}}
\f0\fs24 Hello World\par
}";
let result = converter.rtf_to_markdown(rtf);
// Simplified parser may not extract perfectly, just check it doesn't crash
assert!(!result.is_empty());
}
#[test]
fn test_rtf_converter_metadata() {
let converter = RtfConverter::new();
let meta = converter.metadata();
assert_eq!(meta.name, "RTF Converter");
}
}