rtf_parser_tt/
document.rs1use std::error::Error;
2use std::fs;
3use std::io::Read;
4
5use serde::{Deserialize, Serialize};
6#[cfg(feature = "jsbindings")]
7use wasm_bindgen::prelude::wasm_bindgen;
8
9use crate::header::RtfHeader;
10use crate::lexer::Lexer;
11use crate::parser::{Parser, StyleBlock};
12
13#[cfg_attr(feature = "jsbindings", wasm_bindgen)]
15pub fn parse_rtf(rtf: String) -> RtfDocument {
16 return RtfDocument::try_from(rtf).unwrap();
17}
18
19#[derive(Debug, Default, Clone, PartialEq, Deserialize, Serialize)]
20#[cfg_attr(feature = "jsbindings", wasm_bindgen(getter_with_clone))]
21pub struct RtfDocument {
22 pub header: RtfHeader,
23 pub body: Vec<StyleBlock>,
24}
25
26impl TryFrom<String> for RtfDocument {
28 type Error = Box<dyn Error>;
29 fn try_from(file_content: String) -> Result<Self, Self::Error> {
30 let tokens = Lexer::scan(file_content.as_str())?;
31 let document = Parser::new(tokens).parse()?;
32 return Ok(document);
33 }
34}
35
36impl TryFrom<&str> for RtfDocument {
38 type Error = Box<dyn Error>;
39 fn try_from(file_content: &str) -> Result<Self, Self::Error> {
40 let tokens = Lexer::scan(file_content)?;
41 let document = Parser::new(tokens).parse()?;
42 return Ok(document);
43 }
44}
45
46impl TryFrom<&mut fs::File> for RtfDocument {
48 type Error = Box<dyn Error>;
49 fn try_from(file: &mut fs::File) -> Result<Self, Self::Error> {
50 let mut file_content = String::new();
51 file.read_to_string(&mut file_content)?;
52 return Self::try_from(file_content);
53 }
54}
55
56impl RtfDocument {
57 pub fn from_filepath(filename: &str) -> Result<RtfDocument, Box<dyn Error>> {
59 let file_content = fs::read_to_string(filename)?;
60 return Self::try_from(file_content);
61 }
62
63 pub fn get_text(&self) -> String {
65 let mut result = String::new();
66 for style_block in &self.body {
67 result.push_str(&style_block.text);
68 }
69 return result;
70 }
71}
72
73#[cfg(test)]
74pub(crate) mod tests {
75 use super::*;
76 use crate::document::RtfDocument;
77
78 #[test]
79 fn get_text_from_document() {
80 let rtf = r#"{ \rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard Voici du texte en {\b gras}.\par }"#;
81 let document = RtfDocument::try_from(rtf).unwrap();
82 assert_eq!(document.get_text(), "Voici du texte en gras.")
83 }
84
85 #[test]
86 fn create_document_from_file() {
87 let mut file = fs::File::open("./resources/tests/test-file.rtf").unwrap();
88 let document = RtfDocument::try_from(&mut file).unwrap();
89 assert_eq!(document.header.font_table.get(&0).unwrap().name, String::from("Helvetica"));
90 }
91
92 #[test]
93 fn create_document_from_filepath() {
94 let filename = "./resources/tests/test-file.rtf";
95 let document = RtfDocument::from_filepath(filename).unwrap();
96 assert_eq!(document.header.font_table.get(&0).unwrap().name, String::from("Helvetica"));
97 }
98}