This commit is contained in:
66
lib/notare/xml/styles_xml.rb
Normal file
66
lib/notare/xml/styles_xml.rb
Normal file
@@ -0,0 +1,66 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Notare
|
||||
module Xml
|
||||
class StylesXml
|
||||
NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
||||
|
||||
ALIGNMENT_MAP = {
|
||||
left: "left",
|
||||
center: "center",
|
||||
right: "right",
|
||||
justify: "both"
|
||||
}.freeze
|
||||
|
||||
def initialize(styles)
|
||||
@styles = styles
|
||||
end
|
||||
|
||||
def to_xml
|
||||
builder = Nokogiri::XML::Builder.new(encoding: "UTF-8") do |xml|
|
||||
xml.styles("xmlns:w" => NAMESPACE) do
|
||||
xml.parent.namespace = xml.parent.namespace_definitions.find { |ns| ns.prefix == "w" }
|
||||
|
||||
@styles.each_value do |style|
|
||||
render_style(xml, style)
|
||||
end
|
||||
end
|
||||
end
|
||||
builder.to_xml
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def render_style(xml, style)
|
||||
style_type = style.paragraph_properties? ? "paragraph" : "character"
|
||||
|
||||
xml["w"].style("w:type" => style_type, "w:styleId" => style.style_id) do
|
||||
xml["w"].name("w:val" => style.display_name)
|
||||
|
||||
render_paragraph_properties(xml, style) if style.paragraph_properties?
|
||||
render_run_properties(xml, style) if style.text_properties?
|
||||
end
|
||||
end
|
||||
|
||||
def render_paragraph_properties(xml, style)
|
||||
xml["w"].pPr do
|
||||
xml["w"].jc("w:val" => ALIGNMENT_MAP[style.align]) if style.align
|
||||
xml["w"].ind("w:left" => style.indent.to_s) if style.indent
|
||||
xml["w"].spacing("w:before" => style.spacing_before.to_s) if style.spacing_before
|
||||
xml["w"].spacing("w:after" => style.spacing_after.to_s) if style.spacing_after
|
||||
end
|
||||
end
|
||||
|
||||
def render_run_properties(xml, style)
|
||||
xml["w"].rPr do
|
||||
xml["w"].rFonts("w:ascii" => style.font, "w:hAnsi" => style.font) if style.font
|
||||
xml["w"].sz("w:val" => style.size_half_points.to_s) if style.size
|
||||
xml["w"].color("w:val" => style.color) if style.color
|
||||
xml["w"].b if style.bold
|
||||
xml["w"].i if style.italic
|
||||
xml["w"].u("w:val" => "single") if style.underline
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user