Back to Home
Ruby RTF Tools
What are they
Always looking for a programming challenge I have undertaken to create a library of RTF tools for Ruby. At the moment it consists of just two classes. One to take a file apart and another to put it back together again. Not much of a start and not all that usefull. However they are the classes that I will need when I start to process the RTF Document Model. The plan is that you can either create an RTF document programmatically and then write it out or you could read an RTF document into the Document Model and then convert it into something else, HTML, XML or whatever. Anyhow thats the plan once I've read the 300+ page RTF specification.
And the code?
So here's a little archive to play with and get a feel of what can be done. Hardly any documentation but then there is hardly any functionality so it is rather well matched.
In use
Reading data in from a string of RTF...
require 'reader'
line = '{\pard \qc \b\f3\fs40 Section 1: The Larch \par}'
r = RTFReader.new(line)
type, value, extra = r.get_token
while type != 'eof' do
puts "[#{type},#{value},#{extra}]\n"
type, value, extra = r.get_token
end
get turned into this...
[group,{,]
[control,\pard, ]
[control,\qc, ]
[control,\b,]
[control,\f,3]
[control,\fs,40 ]
[text,Section 1: The Larch ,]
[control,\par,]
[group,},]
Which can be fed into the writer...
require 'writer'
w = RTFWriter.new()
x = ''
x << w.process('group', '{')
x << w.process('control', '\pard')
x << w.process('control', '\qc')
x << w.process('control', '\b')
x << w.process('control', '\f', '3')
x << w.process('control', '\fs', '40 ')
x << w.process('text', 'Section 1: The Larch')
x << w.process('control', '\par')
x << w.process('group', '}')
puts x
get turned back into this...
{\pard\qc\b\f3\fs40 Section 1: The Larch\par}
You are impressed I can tell. Well I have some reading to get on with
Back to Home