Class: Htmltoword::Document
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
replace_values, template_file
Constructor Details
#initialize(template_path, file_name) ⇒ Document
Returns a new instance of Document.
41
42
43
44
45
|
# File 'lib/htmltoword.rb', line 41
def initialize(template_path, file_name)
@file_name = file_name
@replaceable_files = {}
@template_zip = Zip::ZipFile.open(template_path)
end
|
Class Method Details
.create(content, file_name) ⇒ Object
27
28
29
30
31
|
# File 'lib/htmltoword.rb', line 27
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
33
34
35
36
37
38
|
# File 'lib/htmltoword.rb', line 33
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_name ⇒ Object
47
48
49
|
# File 'lib/htmltoword.rb', line 47
def file_name
@file_name
end
|
#replace_file(html, file_name = DOC_XML_FILE) ⇒ Object
76
77
78
79
80
81
|
# File 'lib/htmltoword.rb', line 76
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
|
#save ⇒ Object
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.
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# File 'lib/htmltoword.rb', line 59
def save
output_file = Tempfile.new([file_name, FILE_EXTENSION], type: 'application/zip')
Zip::ZipOutputStream.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
@template_zip.close
output_file.close
return output_file
end
|