Please check back soon for explanation and a screen cast review of the code below – an overview of dynamic Microsoft Word document generation in Rails.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | def update_document_xml_for_user(user) file = File.open("#{Rails.root}/docxfiles/#{docx}/word/document.xml", "rb") contents = file.read contents.force_encoding('utf-8').encode Doc.mergefields.each do |field| if user.send("#{field}").nil? || user.send("#{field}")=='' contents = contents.gsub("Z#{field}Z", self.class.escape_for_xml("[#{field}]")) else contents = contents.gsub("Z#{field}Z", self.class.escape_for_xml(user.send("#{field}"))) end end if File.exists?("#{Rails.root}/docxworkingfiles/#{docx}/word/document.xml") File.delete("#{Rails.root}/docxworkingfiles/#{docx}/word/document.xml") end open("#{Rails.root}/docxworkingfiles/#{docx}/word/document.xml", 'w') { |f| f.print contents } system "cd #{Rails.root}/docxworkingfiles/#{docx}; zip -r #{Rails.root}/tmp/docxfiles/#{user.id}-#{docx}.zip *" File.rename("#{Rails.root}/tmp/docxfiles/#{user.id}-#{docx}.zip", "#{Rails.root}/tmp/docxfiles/#{user.id}-#{docx}.docx") return nil end |