Skip to content

Instantly share code, notes, and snippets.

@angelf
Created April 15, 2010 10:44
Show Gist options
  • Select an option

  • Save angelf/366963 to your computer and use it in GitHub Desktop.

Select an option

Save angelf/366963 to your computer and use it in GitHub Desktop.
require 'nokogiri'
require 'rtf'
# ampliamos RTF::Node con métodos para parsear HTML
# tiene que hacerse añadiendo métodos a la clase existente
# porque cuando ahcemos node.apply(..){|n| } el objeto n
# (que puede ser cualquier subclase de RTF::Node) tiene que tenerlo
class RTF::Node
# los estilos disponibles
# ¿debería ser una constante?
def styles
return @styles if @styles
@styles = {}
@styles['STRONG'] = RTF::CharacterStyle.new
@styles['STRONG'].bold = true
@styles['H2'] = RTF::CharacterStyle.new
@styles['H2'].bold = false
@styles['H2'].font_size = 30
@styles['EM'] = RTF::CharacterStyle.new
@styles['EM'].italic = true
@styles
end
# añade un nodo HTML al documento
def add_html_node(html_node)
case html_node.name
when "h2"
self.line_break
self.apply(self.styles["H2"]) do |n|
n.add_children(html_node)
end
self.line_break
when "br"
self.line_break
when "p"
self.line_break
add_children(html_node)
when "strong"
self.apply(self.styles["STRONG"]) do |n|
n.add_children(html_node)
end
when "em"
self.apply(self.styles["EM"]) do |n|
n.add_children(html_node)
end
when "img"
self << rtf_image(html_node)
when "style"
# un ejemplo: si hay un tag que en HTML es invisible, simplemente ignoramos
# su contenido
else
# ignoramos los tags que no sabemos que son, simplemente añadimos
# sus sub-elementos
add_children(html_node)
end
end
# si el nodo tiene hijos itera sobre ellos y los añade al documento
# si no tiene hijos, añade el contenido en si
def add_children(html_node)
if html_node.children.any?
html_node.children.each{|n| self.add_html_node(n) }
else
self << html_node.to_s
end
end
end
class HTMLGenerator < RTF::Document
def initialize()
fonts = [RTF::Font.new(RTF::Font::ROMAN, 'Times New Roman'),
RTF::Font.new(RTF::Font::MODERN, 'Courier'),
RTF::Font.new(RTF::Font::MODERN, 'Helvetica')]
style_doc = RTF::DocumentStyle.new
style_doc.bottom_margin = 1250#1440
style_doc.top_margin = 1100#1440
style_doc.right_margin = 900#1800
style_doc.left_margin = 900#1800
super(fonts, style_doc)
end
end
html_doc = Nokogiri::HTML::Document.parse("
<h2>Hola</h2>
Buenos Dias
<p>Tenga <strong>Usted <em>Hoy</em> y el dia siguiente</strong> </p>
<br><br>Ups
")
rtf_document = HTMLGenerator.new() # sería el documento
rtf_document.add_html_node(html_doc)
File.open("my_document.rtf",'w') {|file| file << rtf_document.to_rtf}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment