How to edit docx with nokogiri and rubyzip

后端 未结 3 1029
走了就别回头了
走了就别回头了 2021-02-01 10:27

I\'m using a combination of rubyzip and nokogiri to edit a .docx file. I\'m using rubyzip to unzip the .docx file and then using nokogiri to parse and change the body of the wo

3条回答
  •  粉色の甜心
    2021-02-01 11:12

    I ran into the same corruption problem with rubyzip last night. I solved it by copying everything to a new zip file, replacing files as necessary.

    Here's my working proof of concept:

    #!/usr/bin/env ruby
    
    require 'rubygems'
    require 'zip/zip' # rubyzip gem
    require 'nokogiri'
    
    class WordXmlFile
      def self.open(path, &block)
        self.new(path, &block)
      end
    
      def initialize(path, &block)
        @replace = {}
        if block_given?
          @zip = Zip::ZipFile.open(path)
          yield(self)
          @zip.close
        else
          @zip = Zip::ZipFile.open(path)
        end
      end
    
      def merge(rec)
        xml = @zip.read("word/document.xml")
        doc = Nokogiri::XML(xml) {|x| x.noent}
        (doc/"//w:fldSimple").each do |field|
          if field.attributes['instr'].value =~ /MERGEFIELD (\S+)/
            text_node = (field/".//w:t").first
            if text_node
              text_node.inner_html = rec[$1].to_s
            else
              puts "No text node for #{$1}"
            end
          end
        end
        @replace["word/document.xml"] = doc.serialize :save_with => 0
      end
    
      def save(path)
        Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |out|
          @zip.each do |entry|
            out.get_output_stream(entry.name) do |o|
              if @replace[entry.name]
                o.write(@replace[entry.name])
              else
                o.write(@zip.read(entry.name))
              end
            end
          end
        end
        @zip.close
      end
    end
    
    if __FILE__ == $0
      file = ARGV[0]
      out_file = ARGV[1] || file.sub(/\.docx/, ' Merged.docx')
      w = WordXmlFile.open(file) 
      w.force_settings
      w.merge('First_Name' => 'Eric', 'Last_Name' => 'Mason')
      w.save(out_file)
    end
    

提交回复
热议问题