---
title: "rubyonrails: rtf"
author: "PBFox"
date: "2007-11-16T11:19:00Z"
tags: []
slug: "rubyonrails-rtf"
draft: false
lastmod: "2007-11-16T11:19:00Z"
id: 479254
url: "https://developerwork.iteye.com/blog/479254"
---

首先是安装：  
gem install rtf

代码：

#!/usr/bin/env ruby

require 'rubygems'  
require 'rtf'

include RTF

\# Create required styles.  
styles = {}  
styles\['HEADER'] = CharacterStyle.new  
styles\['HEADER'].bold = true  
styles\['HEADER'].font\_size = 28  
styles\['NORMAL'] = ParagraphStyle.new  
styles\['NORMAL'].justification = ParagraphStyle::FULL\_JUSTIFY  
styles\['INDENTED'] = ParagraphStyle.new  
styles\['INDENTED'].left\_indent = 400

document = Document.new(Font.new(Font::ROMAN, 'Arial'))  
document.paragraph do |p|  
p.apply(styles\['HEADER']) do |s|  
s &lt;&lt; '1.0 Introduction'  
end  
end  
document.paragraph(styles\['NORMAL']) do |p|  
p &lt;&lt; 'Here is a short example program in the Ruby programming '  
p &lt;&lt; 'language that demonstrates writing a single line of text '  
p &lt;&lt; 'to a file created in the current working directory...'  
end

c = 1  
document.paragraph(styles\['INDENTED']) do |n1|  
n1.line\_break  
n1.font(Font.new(Font::MODERN, 'Courier New')) do |n2|  
n2 &lt;&lt; "#{sprintf('%02d', c)} File.open('output.txt', 'w') do |file|"  
c += 1  
n2.line\_break  
n2 &lt;&lt; "#{sprintf('%02d', c)} file.write('Some text.')"  
c += 1  
n2.line\_break  
n2 &lt;&lt; "#{sprintf('%02d', c)} end"  
end  
end

document.line\_break  
document.paragraph(styles\['NORMAL']) do |p|  
p &lt;&lt; "And there you have it. A simple example indeed."  
end

File.open('example01.rtf', 'w') do |file|  
file.write(document.to\_rtf)  
end