Class: SheetFiller::Doc::WordXmlFile

Inherits:
Object
  • Object
show all
Defined in:
lib/sheet_filler/doc/word_xml_file.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ WordXmlFile

Returns a new instance of WordXmlFile.



6
7
8
9
10
# File 'lib/sheet_filler/doc/word_xml_file.rb', line 6

def initialize(path)
  @zip = Zip::File.open(path)
  xml = @zip.read("word/document.xml")
  @doc = Nokogiri::XML(xml) { |xml| xml.noent }
end

Class Method Details

.replace_check_box(form_data, checkbox) ⇒ Object



47
48
49
50
51
52
# File 'lib/sheet_filler/doc/word_xml_file.rb', line 47

def self.replace_check_box(form_data, checkbox)
  name = checkbox.parent.children.detect { |child| child.name == "name" }
  if form_data["checkBox:#{name.attributes["val"].to_s}"]
    (checkbox/".//w:default")[0].attribute("val").value = "1"
  end
end

.replace_text_field(form_data, field) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/sheet_filler/doc/word_xml_file.rb', line 37

def self.replace_text_field(form_data, field)
  text_nodeset = (field/".//w:t")
  text = text_nodeset.inner_html
  if text_nodeset &&
    key = form_data.keys.detect { |key| text.include?(key) }
      text_nodeset.each { |node| node.inner_html = "" }
      text_nodeset.first.inner_html = text.gsub(key, form_data[key].to_s)
  end
end

Instance Method Details

#fill_form(form_data) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/sheet_filler/doc/word_xml_file.rb', line 12

def fill_form(form_data)
  (@doc/"//w:tr/w:tc").each do |field|
    if form_data_code = form_data[Doc::Parser.cell_code(field)].try(:to_s)
      checkbox = (field/".//w:checkBox")
      if checkbox.empty?
        if text_node = (field/".//w:t").first
          text_node.inner_html = form_data_code
        end
      else
        (checkbox/".//w:default")[0].attribute("val").value = form_data_code
      end
    end
  end
end

#replace(form_data) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/sheet_filler/doc/word_xml_file.rb', line 27

def replace(form_data)
  (@doc/"//w:checkBox").each do |checkbox|
    WordXmlFile.replace_check_box(form_data, checkbox)
  end

  (@doc/"//w:p").each do |field|
    WordXmlFile.replace_text_field(form_data, field)
  end
end

#save(path) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/sheet_filler/doc/word_xml_file.rb', line 54

def save(path)
  @replace = {"word/document.xml" => @doc.serialize(save_with: 0)}
  Zip::File.open(path, Zip::File::CREATE) do |zip_file|
    @zip.each do |entry|
      filename = entry.name
      zip_file.get_output_stream(filename) do |output|
        output.write(@replace[filename] || @zip.read(filename))
      end
    end
  end
  @zip.close
end