Class: Mapi::RTF::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/mapi/rtf.rb

Class Method Summary collapse

Class Method Details

.rtf2text(str, format = :text) ⇒ Object

this is pretty crap, its just to ensure there is always something readable if there is an rtf only body, with no html encapsulation.



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
# File 'lib/mapi/rtf.rb', line 65

def self.rtf2text str, format=:text
	group = 0
	text = ''
	text << "<html>\n<body>" if format == :html
	group_type = []
	group_tags = []
	RTF::Tokenizer.process(StringIO.new(str)) do |a, b, c|
		add_text = ''
		case a
		when :open_group; group += 1; group_type[group] = nil; group_tags[group] = []
		when :close_group; group_tags[group].reverse.each { |t| text << "</#{t}>" }; group -= 1;
		when :control_word; # ignore
			group_type[group] ||= b
			# maybe change this to use utf8 where possible
			add_text = if b == 'par' || b == 'line' || b == 'page'; "\n"
			elsif b == 'tab' || b == 'cell'; "\t"
			elsif b == 'endash' || b == 'emdash'; "-"
			elsif b == 'emspace' || b == 'enspace' || b == 'qmspace'; " "
			elsif b == 'ldblquote'; '"'
			else ''
			end
			if b == 'b' || b == 'i' and format == :html
				close = c == 0 ? '/' : ''
				text << "<#{close}#{b}>"
				if c == 0
					group_tags[group].delete b
				else
					group_tags[group] << b
				end
			end
			# lot of other ones belong in here.\
=begin
\bullet 	Bullet character.
\lquote 	Left single quotation mark.
\rquote 	Right single quotation mark.
\ldblquote 	Left double quotation mark.
\rdblquote
=end
		when :control_symbol; # ignore
			 group_type[group] ||= b
			add_text = ' ' if b == '~' # non-breakable space
			add_text = '-' if b == '_' # non-breakable hypen
		when :text
			add_text = b if group <= 1 or group_type[group] == 'rtlch' && !group_type[0...group].include?('*')
		end
		if format == :html
			text << add_text.gsub(/([<>&"'])/) do
				ent = { '<' => 'lt', '>' => 'gt', '&' => 'amp', '"' => 'quot', "'" => 'apos' }[$1]
				"&#{ent};"
			end
			text << '<br>' if add_text == "\n"
		else
			text << add_text
		end
	end
	text << "</body>\n</html>\n" if format == :html
	text
end