Class: Htmltoword::Document

Inherits:
Object
  • Object
show all
Extended by:
HtmltowordHelper
Defined in:
lib/htmltoword/document.rb

Constant Summary collapse

DOC_XML_FILE =
"word/document.xml"
BASIC_PATH =
::Htmltoword.root
FILE_EXTENSION =
".docx"
XSLT_TEMPLATE =
File.join(BASIC_PATH, 'xslt', 'html_to_wordml.xslt')

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HtmltowordHelper

replace_values, template_file

Constructor Details

#initialize(template_path, file_name) ⇒ Document

Returns a new instance of Document.



26
27
28
29
30
# File 'lib/htmltoword/document.rb', line 26

def initialize(template_path, file_name)
  @file_name = file_name
  @replaceable_files = {}
  @template_path = template_path
end

Class Method Details

.create(content, file_name) ⇒ Object



12
13
14
15
16
# File 'lib/htmltoword/document.rb', line 12

def create content, file_name
  word_file = new(template_file, file_name)
  word_file.replace_file content
  word_file.save
end

.create_with_content(template, file_name, content, set = nil) ⇒ Object



18
19
20
21
22
23
# File 'lib/htmltoword/document.rb', line 18

def create_with_content template, file_name, content, set=nil
  word_file = new(template_file("#{template}#{FILE_EXTENSION}"), file_name)
  content = replace_values(content, set) if set
  word_file.replace_file content
  word_file.save
end

Instance Method Details

#file_nameObject



32
33
34
# File 'lib/htmltoword/document.rb', line 32

def file_name
  @file_name
end

#replace_file(html, file_name = DOC_XML_FILE) ⇒ Object



62
63
64
65
66
67
# File 'lib/htmltoword/document.rb', line 62

def replace_file html, file_name=DOC_XML_FILE
  source = Nokogiri::HTML(html.gsub(/>\s+</, "><"))
  xslt = Nokogiri::XSLT( File.read(XSLT_TEMPLATE) )
  source = xslt.transform( source ) unless (source/"/html").blank?
  @replaceable_files[file_name] = source.to_s
end

#saveObject

It creates missing folders if needed, creates a new zip/word file on the specified location, copies all the files from the template word document and replace the content of the ones to be replaced. It will create a tempfile and return it. The rails app using the gem should decide what to do with it.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/htmltoword/document.rb', line 44

def save
  Tempfile.open([file_name, FILE_EXTENSION], type: 'application/zip') do |output_file|
    Zip::File.open(@template_path) do |template_zip|
      Zip::OutputStream.open(output_file.path) do |out|
        template_zip.each do |entry|
          out.put_next_entry entry.name
          if @replaceable_files[entry.name]
            out.write(@replaceable_files[entry.name])
          else
            out.write(template_zip.read(entry.name))
          end
        end
      end
    end
    output_file
  end
end