forked from ashigirl96/ruby-docx-templater
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docx_creator.rb
43 lines (37 loc) · 1.28 KB
/
docx_creator.rb
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
require 'zip'
DOCUMENT_XML = 'word/document.xml'
module DocxTemplater
class DocxCreator
attr_reader :template_path, :template_processor
def initialize(template_path, data, escape_html = true)
@template_path = template_path
@template_processor = TemplateProcessor.new(data, escape_html)
end
def generate_docx_file(file_name = "output_#{Time.now.strftime('%Y-%m-%d_%H%M')}.docx")
File.open(file_name, 'wb') do |f|
f.write(generate_docx_bytes.string)
end
end
def generate_docx_bytes
Zip::OutputStream.write_buffer(StringIO.new) do |out|
Zip::File.open(template_path).each do |entry|
entry_name = entry.name
out.put_next_entry(entry_name)
if entry.get_input_stream.is_a?(Zip::NullInputStream)
raise ::DocxTemplater::InvalidInputError, "stream is Zip::NullInputStream"
end
out.write(copy_or_template(entry_name, entry.get_input_stream.read))
end
end
end
private
def copy_or_template(entry_name, entry_bytes)
# Inside the word document archive is one file with contents of the actual document. Modify it.
if entry_name == DOCUMENT_XML
template_processor.render(entry_bytes)
else
entry_bytes
end
end
end
end