paper_docx_templater 0.1.1
Sign up to get free protection for your applications and to get access to all the features.
- data/.gitignore +4 -0
- data/Gemfile +7 -0
- data/LICENSE.txt +176 -0
- data/README.rdoc +40 -0
- data/Rakefile +16 -0
- data/docx_templater.gemspec +42 -0
- data/lib/VERSION +1 -0
- data/lib/docx_templater/docx_creator.rb +72 -0
- data/lib/docx_templater/image.rb +16 -0
- data/lib/docx_templater/template_processor.rb +230 -0
- data/lib/docx_templater.rb +18 -0
- data/script/ci.sh +48 -0
- data/spec/example_input/2.docx +0 -0
- data/spec/example_input/3.docx +0 -0
- data/spec/example_input/9/[Content_Types].xml +2 -0
- data/spec/example_input/9/docProps/app.xml +2 -0
- data/spec/example_input/9/docProps/core.xml +2 -0
- data/spec/example_input/9/word/_rels/document.xml.rels +2 -0
- data/spec/example_input/9/word/document.xml +2 -0
- data/spec/example_input/9/word/endnotes.xml +2 -0
- data/spec/example_input/9/word/fontTable.xml +2 -0
- data/spec/example_input/9/word/footnotes.xml +2 -0
- data/spec/example_input/9/word/media/image1.jpeg +0 -0
- data/spec/example_input/9/word/media/image2.jpeg +0 -0
- data/spec/example_input/9/word/media/image3.jpeg +0 -0
- data/spec/example_input/9/word/settings.xml +2 -0
- data/spec/example_input/9/word/styles.xml +2 -0
- data/spec/example_input/9/word/theme/theme1.xml +2 -0
- data/spec/example_input/9/word/webSettings.xml +2 -0
- data/spec/example_input/ExampleTemplate.docx +0 -0
- data/spec/example_input/tmp/IntegrationTestOutput.docx +0 -0
- data/spec/example_input/word/document.xml +1122 -0
- data/spec/example_input/~$3.docx +0 -0
- data/spec/example_input/~$/351/253/230/350/200/203/346/250/241/346/213/237/345/215/267.doc +0 -0
- data/spec/example_input//351/253/230/350/200/203/346/250/241/346/213/237/345/215/267.doc +0 -0
- data/spec/integration_spec.rb +49 -0
- data/spec/spec.opts +1 -0
- data/spec/spec_helper.rb +12 -0
- data/spec/template_processor_spec.rb +269 -0
- metadata +177 -0
data/.gitignore
ADDED
data/Gemfile
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
source "http://rubygems.org"
|
2
|
+
gemspec
|
3
|
+
|
4
|
+
# Forked to make zipruby play nicely with rubyzip if your project already uses it.
|
5
|
+
gem "zipruby-compat", :require => 'zipruby', :git => "https://github.com/TimLang/zipruby-compatibility-with-rubyzip-fork", :tag => "v0.3.7"
|
6
|
+
gem 'mini_magick', '1.3.2'
|
7
|
+
gem 'debugger'
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,176 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
data/README.rdoc
ADDED
@@ -0,0 +1,40 @@
|
|
1
|
+
= Roughly, this takes a .docx file and uses it as a template to create a new docx, with your data
|
2
|
+
|
3
|
+
== Features
|
4
|
+
|
5
|
+
* All manipulation in memory (great if you have sensitive data)
|
6
|
+
* Global key/value substitutions by entering a `$KEY$` anywhere in the word document, with whatever formatting you want.
|
7
|
+
* Multi-row loops inside tables, also with whatever your formatting you wish. `#BEGIN_ROW:XYZ#`... `#END_ROW:XYZ#` see tests/example
|
8
|
+
* Summation formula for row count `#SUM:XYZ_LIST#`
|
9
|
+
|
10
|
+
== Usage
|
11
|
+
* Create your docx "template" in Word
|
12
|
+
* Install rvm and bundler
|
13
|
+
* Your bundle needs to pull in zipruby-compat gem, which is not on rubyforge. Gemfile: `gem "zipruby-compat", :require => 'zipruby', :git => "git@github.com:jawspeak/zipruby-compatibility-with-rubyzip-fork.git", :tag => "v0.3.7"`
|
14
|
+
* Run `bundle install`.
|
15
|
+
* Render new docx files from the template, ex: `ruby render_docx_template.rb`. Look for an output_*.docx file.
|
16
|
+
* Sample output with tests: `rake spec` (unit tests) `rake integration` (opens word)
|
17
|
+
|
18
|
+
__TECHNICAL NOTE:__ You will probably need to extract and edit the xml template manually after creating in Word, to prepare the ruby script template with it. This is very fiddly / hacky. You can’t have Word’s ugly markup around the fields to template. It will try to break up fields with markup. Test the template, fixing it until the extracted word/document.xml as needed.
|
19
|
+
|
20
|
+
I frequently use this workflow:
|
21
|
+
`rm -rf word/; unzip ExampleTemplate.docx word/document.xml; mate word/document.xml`
|
22
|
+
Grep/search for all $ and # lines and ensure no templating is split with xml markup.
|
23
|
+
And then re-add the edited document:
|
24
|
+
`zip ExampleTemplate.docx word/document.xml`
|
25
|
+
|
26
|
+
__PRO TIP:__ You don’t want any grammar errors on the template Keys, or they will not substitute. (Grammar suggestion markup splits up the tokens in the xml). Right click and choose Ignore each grammar error.
|
27
|
+
|
28
|
+
|
29
|
+
== Development
|
30
|
+
* Install any missing dependencies, then run the test suite: `script/ci`
|
31
|
+
* Run the integration test suite (on mac, with word installed): `rake integration`
|
32
|
+
* Build the gem file: `gem build docx_templater.gemspec`
|
33
|
+
|
34
|
+
|
35
|
+
== Future ideas
|
36
|
+
* We could in the future use Word's MailMerge fields instead of using our own style `$KEY_ABC$` keys. We would then not have to worry about Word munging our text by inserting XML markup in-between parts of a template key #BEGIN_ROW:BLAH#. This is probably a really good idea. Also we would need to delete these other nodes that get added when Fields are added.
|
37
|
+
** See also: {http://tomasvarsavsky.com/2009/04/04/simple-word-document-templating-using-ruby-and-xml/} and {https://github.com/bagilevi/docx_builder/tree/master/example/plan_report_template},
|
38
|
+
* Possibly, also use Fields to create the looping constructs. That would be a big win for preventing word adding markup between words in by text.
|
39
|
+
* Make rendering from the template more efficient.
|
40
|
+
* Try templating header/footer (I haven't attempted that yet because I do not have a need for it.)
|
data/Rakefile
ADDED
@@ -0,0 +1,16 @@
|
|
1
|
+
require 'rubygems'
|
2
|
+
require 'bundler'
|
3
|
+
Bundler.setup
|
4
|
+
|
5
|
+
require 'rake'
|
6
|
+
require 'rspec/core/rake_task'
|
7
|
+
|
8
|
+
RSpec::Core::RakeTask.new do |spec|
|
9
|
+
spec.rspec_opts = ["--options", "spec/rspec.opts", "--tag", '~integration']
|
10
|
+
end
|
11
|
+
|
12
|
+
RSpec::Core::RakeTask.new(:integration) do |spec|
|
13
|
+
spec.rspec_opts = ["--options", "spec/rspec.opts", "--tag", 'integration']
|
14
|
+
end
|
15
|
+
|
16
|
+
task :default => :spec
|
@@ -0,0 +1,42 @@
|
|
1
|
+
# encoding: utf-8
|
2
|
+
|
3
|
+
Gem::Specification.new do |s|
|
4
|
+
s.name = "paper_docx_templater"
|
5
|
+
s.version = File.read("lib/VERSION").strip
|
6
|
+
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
|
7
|
+
s.rubygems_version = "1.3.7"
|
8
|
+
|
9
|
+
s.authors = ["Tim Lang"]
|
10
|
+
|
11
|
+
s.email = "langyong135@gmail.com"
|
12
|
+
|
13
|
+
s.date = "2013-10-23"
|
14
|
+
s.description = "A Ruby library to template Microsoft Word .docx files."
|
15
|
+
s.summary = "Generates new Word .docx files based on a template file."
|
16
|
+
s.homepage = "https://github.com/TimLang/ruby-docx-templater"
|
17
|
+
|
18
|
+
s.rdoc_options = ["--charset=UTF-8"]
|
19
|
+
s.extra_rdoc_files = ["README.rdoc"]
|
20
|
+
|
21
|
+
s.require_paths = ["lib"]
|
22
|
+
root_files = %w(docx_templater.gemspec LICENSE.txt Rakefile README.rdoc .gitignore Gemfile)
|
23
|
+
s.files = Dir['{lib,script,spec}/**/*'] + root_files
|
24
|
+
s.test_files = Dir['spec/**/*']
|
25
|
+
|
26
|
+
s.add_dependency("nokogiri")
|
27
|
+
# zipruby specifically because:
|
28
|
+
# - rubyzip does not support in-memory zip file modification (in you process sensitive info
|
29
|
+
# that can't hit the filesystem).
|
30
|
+
# - people report errors opening in word docx files when altered with rubyzip (search stackoverflow)
|
31
|
+
|
32
|
+
# zipruby-compat, which is my fork of zipruby that changes the module Zip::* to ZipRuby::*,
|
33
|
+
# so it does not collide with rubyzip in same project.
|
34
|
+
# - see https://github.com/jawspeak/zipruby-compatibility-with-rubyzip-fork
|
35
|
+
# THIS gem is not installed to rubyforge. Thus, you MUST on your own, in your Gemspec, add a dependency
|
36
|
+
# to zipruby-compat. Example:
|
37
|
+
# gem "zipruby-compat", :git => "git@github.com:jawspeak/zipruby-compatibility-with-rubyzip-fork.git", :tag => "v0.3.7"
|
38
|
+
s.add_dependency("zipruby-compat", "~> 0.3.7")
|
39
|
+
|
40
|
+
s.add_development_dependency("rake")
|
41
|
+
s.add_development_dependency("rspec", "~> 2.7.0")
|
42
|
+
end
|
data/lib/VERSION
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
0.1.1
|
@@ -0,0 +1,72 @@
|
|
1
|
+
# -*- encoding : utf-8 -*-
|
2
|
+
module DocxTemplater
|
3
|
+
class DocxCreator
|
4
|
+
attr_reader :template_path, :template_processor, :cached_images
|
5
|
+
|
6
|
+
def initialize(template_path, data, cached_images, escape_html=true)
|
7
|
+
@template_path = template_path
|
8
|
+
@template_processor = TemplateProcessor.new(data, cached_images, escape_html)
|
9
|
+
@cached_images = cached_images
|
10
|
+
end
|
11
|
+
|
12
|
+
def generate_docx_file(file_name = "output_#{Time.now.strftime("%Y-%m-%d_%H%M")}.docx")
|
13
|
+
buffer = generate_docx_bytes
|
14
|
+
File.open(file_name, 'w') { |f| f.write(buffer) }
|
15
|
+
end
|
16
|
+
|
17
|
+
def generate_docx_bytes
|
18
|
+
buffer = ''
|
19
|
+
read_existing_template_docx do |template|
|
20
|
+
create_new_zip_in_memory(buffer, template)
|
21
|
+
end
|
22
|
+
buffer
|
23
|
+
end
|
24
|
+
|
25
|
+
private
|
26
|
+
|
27
|
+
def copy_or_template(entry_name, f)
|
28
|
+
# Inside the word document archive is one file with contents of the actual document. Modify it.
|
29
|
+
return template_processor.render(f.read) if entry_name == 'word/document.xml'
|
30
|
+
return template_processor.process_media(f.read, @cached_images) if entry_name == 'word/_rels/document.xml.rels'
|
31
|
+
f.read
|
32
|
+
end
|
33
|
+
|
34
|
+
def read_existing_template_docx
|
35
|
+
ZipRuby::Archive.open(template_path) do |template|
|
36
|
+
yield template
|
37
|
+
end
|
38
|
+
end
|
39
|
+
|
40
|
+
def create_new_zip_in_memory(buffer, template)
|
41
|
+
n_entries = template.num_files
|
42
|
+
ZipRuby::Archive.open_buffer(buffer, ZipRuby::CREATE) do |archive|
|
43
|
+
|
44
|
+
generate_images_on_word(archive)
|
45
|
+
|
46
|
+
n_entries.times do |i|
|
47
|
+
entry_name = template.get_name(i)
|
48
|
+
template.fopen(entry_name) do |f|
|
49
|
+
archive.add_buffer(entry_name, copy_or_template(entry_name, f))
|
50
|
+
end
|
51
|
+
end
|
52
|
+
end
|
53
|
+
end
|
54
|
+
|
55
|
+
def generate_images_on_word archive
|
56
|
+
@cached_images.each do |k, img|
|
57
|
+
archive.add_buffer("word/media/#{img.name}", convert_img_format_to_jpeg(img.base64_str, img))
|
58
|
+
end
|
59
|
+
end
|
60
|
+
|
61
|
+
def convert_img_format_to_jpeg(base64_str, img)
|
62
|
+
image = MiniMagick::Image.from_blob(Base64.decode64(base64_str))
|
63
|
+
|
64
|
+
img.width = image['width']
|
65
|
+
img.height = image['height']
|
66
|
+
|
67
|
+
image.format 'jpeg'
|
68
|
+
image.to_blob
|
69
|
+
end
|
70
|
+
|
71
|
+
end
|
72
|
+
end
|
@@ -0,0 +1,230 @@
|
|
1
|
+
# -*- encoding : utf-8 -*-
|
2
|
+
require 'debugger'
|
3
|
+
|
4
|
+
module DocxTemplater
|
5
|
+
class TemplateProcessor
|
6
|
+
attr_reader :data, :escape_html
|
7
|
+
|
8
|
+
LOOP_PLACE_HOLDER = :items
|
9
|
+
# data is expected to be a hash of symbols => string or arrays of hashes.
|
10
|
+
def initialize(data, cached_images, escape_html=true)
|
11
|
+
@data = data
|
12
|
+
@cached_images = cached_images
|
13
|
+
@escape_html = escape_html
|
14
|
+
@items_cache = {}
|
15
|
+
end
|
16
|
+
|
17
|
+
def render(document)
|
18
|
+
# in order to sloved encoding bugs
|
19
|
+
document = Nokogiri::XML(document, nil, 'utf-8').to_s
|
20
|
+
#document.encoding = 'utf-8'
|
21
|
+
#document = document.to_s
|
22
|
+
data.each do |key, value|
|
23
|
+
if value.class == Array
|
24
|
+
document = enter_multiple_values(document, key)
|
25
|
+
else
|
26
|
+
generate_paragraph(document, key, value)
|
27
|
+
end
|
28
|
+
end
|
29
|
+
document
|
30
|
+
end
|
31
|
+
|
32
|
+
def process_media document, images
|
33
|
+
document = Nokogiri::XML(document)
|
34
|
+
|
35
|
+
relationships = document.search('Relationships').first
|
36
|
+
max_index = relationships.search('Relationship').map{|r| r['Id'].gsub!(/rId(\d+)/, '\1')}.max
|
37
|
+
|
38
|
+
images.each_with_index do |(k, img), i|
|
39
|
+
node = Nokogiri::XML::Node.new('Relationship', document)
|
40
|
+
node['Id'] = "rId#{max_index.to_i + i + 1}"
|
41
|
+
node['Type'] = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'
|
42
|
+
node['Target'] = "media/#{img.name}"
|
43
|
+
|
44
|
+
relationships.add_child(node)
|
45
|
+
@cached_images[k].embed_id = node['Id']
|
46
|
+
end
|
47
|
+
document.to_s
|
48
|
+
end
|
49
|
+
|
50
|
+
private
|
51
|
+
|
52
|
+
def generate_paragraph document, key, value
|
53
|
+
document.gsub!("$#{key.to_s.upcase}$", excute_newline(value).join)
|
54
|
+
end
|
55
|
+
|
56
|
+
def generate_each_paragraph document, key, value
|
57
|
+
document.gsub("$EACH:#{key.to_s.upcase}$", excute_newline(value).join)
|
58
|
+
end
|
59
|
+
|
60
|
+
|
61
|
+
def excute_newline value
|
62
|
+
if value =~ /\\n/
|
63
|
+
value.split(/\\n/).inject([]) do |result, str|
|
64
|
+
result << PARAGRAPH_ROW.gsub(/\$text\$/, (excute_nested_image_with_text(str)).join)
|
65
|
+
end
|
66
|
+
else
|
67
|
+
[excute_nested_image_with_text(value)]
|
68
|
+
end
|
69
|
+
end
|
70
|
+
|
71
|
+
def excute_nested_image_with_text value
|
72
|
+
value.split(/(\${image\d+})/).inject([]) do |result, str|
|
73
|
+
unless str =~ /\${image\d+}/
|
74
|
+
result << TEXT_ROW.gsub('$text$', safe(str))
|
75
|
+
else
|
76
|
+
img = @cached_images[str.gsub(/\${(\w+)}/, '\1').to_sym]
|
77
|
+
result << DRAWING_ROW.gsub(/\$embed_id\$/, img.embed_id)
|
78
|
+
.gsub(/\$image_width\$/, get_word_image_dimension(img.width))
|
79
|
+
.gsub(/\$image_height\$/, get_word_image_dimension(img.height))
|
80
|
+
.gsub(/\$image_name\$/, 'tim') if img
|
81
|
+
end
|
82
|
+
end
|
83
|
+
end
|
84
|
+
|
85
|
+
def get_word_image_dimension unit
|
86
|
+
(unit * (1/28.to_f) * 270000).round.to_s
|
87
|
+
end
|
88
|
+
|
89
|
+
def safe(text)
|
90
|
+
if escape_html
|
91
|
+
text.to_s.gsub('&', '&').gsub('>', '>').gsub('<', '<')
|
92
|
+
else
|
93
|
+
text.to_s
|
94
|
+
end
|
95
|
+
end
|
96
|
+
|
97
|
+
def enter_multiple_values(document, key)
|
98
|
+
DocxTemplater::log("enter_multiple_values for: #{key}")
|
99
|
+
# TODO ideally we would not re-parse xml doc every time
|
100
|
+
xml = Nokogiri::XML(document)
|
101
|
+
begin_row = "#BEGIN_ROW:#{key.to_s.upcase}#"
|
102
|
+
end_row = "#END_ROW:#{key.to_s.upcase}#"
|
103
|
+
begin_row_template = xml.xpath("//w:tr[contains(., '#{begin_row}')]", xml.root.namespaces).first
|
104
|
+
end_row_template = xml.xpath("//w:tr[contains(., '#{end_row}')]", xml.root.namespaces).first
|
105
|
+
#DocxTemplater::log("begin_row_template: #{begin_row_template.to_s}")
|
106
|
+
#DocxTemplater::log("end_row_template: #{end_row_template.to_s}")
|
107
|
+
raise "unmatched template markers: #{begin_row} nil: #{begin_row_template.nil?}, #{end_row} nil: #{end_row_template.nil?}. This could be because word broke up tags with it's own xml entries. See README." unless begin_row_template && end_row_template
|
108
|
+
|
109
|
+
row_templates = []
|
110
|
+
row = begin_row_template.next_sibling
|
111
|
+
while (row != end_row_template)
|
112
|
+
row_templates.unshift(row)
|
113
|
+
row = row.next_sibling
|
114
|
+
end
|
115
|
+
#DocxTemplater::log("row_templates: (#{row_templates.count}) #{row_templates.map(&:to_s).inspect}")
|
116
|
+
|
117
|
+
# for each data, reversed so they come out in the right order
|
118
|
+
data[key].reverse.each do |each_data|
|
119
|
+
#DocxTemplater::log("each_data: #{each_data.inspect}")
|
120
|
+
|
121
|
+
# dup so we have new nodes to append
|
122
|
+
row_templates.map(&:dup).each do |new_row|
|
123
|
+
#DocxTemplater::log(" new_row: #{new_row}")
|
124
|
+
innards = new_row.inner_html
|
125
|
+
if !(matches = innards.scan(/\$EACH:([^\$]+)\$/)).empty?
|
126
|
+
#DocxTemplater::log(" matches: #{matches.inspect}")
|
127
|
+
matches.map(&:first).each do |each_key|
|
128
|
+
#DocxTemplater::log(" each_key: #{each_key}")
|
129
|
+
if each_key =~ /items_(.+)/i
|
130
|
+
cache_key = each_key.to_sym
|
131
|
+
@items_cache[cache_key] = innards
|
132
|
+
each_data[LOOP_PLACE_HOLDER].reverse.each_with_index do |e, i|
|
133
|
+
innards = [] if i == 0
|
134
|
+
obj_key = (each_key =~ /items_(.+)/i) ? each_key.gsub(/items_(.+)/i, $1).downcase : ''
|
135
|
+
#innards << BLANK_ROW
|
136
|
+
if e[:choice]
|
137
|
+
if e[:choice].class == Array
|
138
|
+
e[:choice].reverse.each do |c|
|
139
|
+
innards << generate_each_paragraph(@items_cache[cache_key].gsub(/(<w:t>.+<\/w:t>)/, "#{SPACE_TEXT}#{$1}"), each_key, safe(c))
|
140
|
+
end
|
141
|
+
else
|
142
|
+
innards << generate_each_paragraph(@items_cache[cache_key].gsub(/(<w:t>.+<\/w:t>)/, "#{SPACE_TEXT}#{$1}"), each_key, safe(e[:choice]))
|
143
|
+
end
|
144
|
+
end
|
145
|
+
innards << generate_each_paragraph(@items_cache[cache_key], each_key, safe(e[obj_key.to_sym]))
|
146
|
+
end if each_data[LOOP_PLACE_HOLDER]
|
147
|
+
else
|
148
|
+
innards = generate_each_paragraph(innards, each_key, safe(each_data[each_key.downcase.to_sym]))
|
149
|
+
end
|
150
|
+
end
|
151
|
+
end
|
152
|
+
# change all the internals of the new node, even if we did not template
|
153
|
+
if innards.class == Array
|
154
|
+
innards.each do |inn|
|
155
|
+
begin_row_template.add_next_sibling(inn)
|
156
|
+
end
|
157
|
+
else
|
158
|
+
begin_row_template.add_next_sibling(innards)
|
159
|
+
end
|
160
|
+
#DocxTemplater::log("new_row new innards: #{new_row.inner_html}")
|
161
|
+
end
|
162
|
+
end
|
163
|
+
(row_templates + [begin_row_template, end_row_template]).map(&:unlink)
|
164
|
+
xml.to_s
|
165
|
+
end
|
166
|
+
|
167
|
+
# hard coding, my god!
|
168
|
+
|
169
|
+
SPACE_TEXT = '<w:t xml:space="preserve"> </w:t>'
|
170
|
+
|
171
|
+
BLANK_ROW = "<w:tr w:rsidR=\"00D779AB\" w:rsidTr=\"00B812D2\">\n <w:tc>\n <w:tcPr>\n <w:tcW w:w=\"8522\" w:type=\"dxa\"/>\n </w:tcPr>\n <w:p w:rsidR=\"00D779AB\" w:rsidRDefault=\"00D779AB\" w:rsidP=\"00C44DF6\">\n <w:pPr>\n <w:rPr>\n <w:rFonts w:hint=\"eastAsia\"/>\n </w:rPr>\n </w:pPr>\n <w:r>\n <w:rPr>\n <w:rFonts w:hint=\"eastAsia\"/>\n </w:rPr>\n <w:t></w:t>\n </w:r>\n </w:p>\n </w:tc>\n </w:tr>"
|
172
|
+
|
173
|
+
TEXT_ROW = '<w:r>
|
174
|
+
<w:rPr>
|
175
|
+
<w:rFonts w:hint="eastAsia"/>
|
176
|
+
</w:rPr>
|
177
|
+
<w:t>$text$</w:t>
|
178
|
+
</w:r>'
|
179
|
+
|
180
|
+
PARAGRAPH_ROW = '<w:p w:rsidR="0019258A" w:rsidRDefault="00214805">
|
181
|
+
<w:pPr>
|
182
|
+
<w:rPr>
|
183
|
+
<w:rFonts w:hint="eastAsia"/>
|
184
|
+
</w:rPr>
|
185
|
+
</w:pPr>$text$</w:p>'
|
186
|
+
|
187
|
+
DRAWING_ROW = '<w:r>
|
188
|
+
<w:rPr>
|
189
|
+
<w:rFonts w:hint="eastAsia"/>
|
190
|
+
<w:noProof/>
|
191
|
+
</w:rPr>
|
192
|
+
<w:drawing>
|
193
|
+
<wp:inline distT="0" distB="0" distL="0" distR="0">
|
194
|
+
<wp:extent cx="$image_width$" cy="$image_height$"/>
|
195
|
+
<wp:effectExtent l="19050" t="0" r="7990" b="0"/>
|
196
|
+
<wp:docPr id="2" name="图片" descr="$image_name$"/>
|
197
|
+
<wp:cNvGraphicFramePr>
|
198
|
+
<a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/>
|
199
|
+
</wp:cNvGraphicFramePr>
|
200
|
+
<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
|
201
|
+
<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
|
202
|
+
<pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
|
203
|
+
<pic:nvPicPr>
|
204
|
+
<pic:cNvPr id="0" name="$image_name$"/>
|
205
|
+
<pic:cNvPicPr/>
|
206
|
+
</pic:nvPicPr>
|
207
|
+
<pic:blipFill>
|
208
|
+
<a:blip r:embed="$embed_id$" cstate="print"/>
|
209
|
+
<a:stretch>
|
210
|
+
<a:fillRect/>
|
211
|
+
</a:stretch>
|
212
|
+
</pic:blipFill>
|
213
|
+
<pic:spPr>
|
214
|
+
<a:xfrm>
|
215
|
+
<a:off x="0" y="0"/>
|
216
|
+
<a:ext cx="$image_width$" cy="$image_height$"/>
|
217
|
+
</a:xfrm>
|
218
|
+
<a:prstGeom prst="rect">
|
219
|
+
<a:avLst/>
|
220
|
+
</a:prstGeom>
|
221
|
+
</pic:spPr>
|
222
|
+
</pic:pic>
|
223
|
+
</a:graphicData>
|
224
|
+
</a:graphic>
|
225
|
+
</wp:inline>
|
226
|
+
</w:drawing>
|
227
|
+
</w:r>'
|
228
|
+
|
229
|
+
end
|
230
|
+
end
|
@@ -0,0 +1,18 @@
|
|
1
|
+
# -*- encoding : utf-8 -*-
|
2
|
+
require 'rubygems'
|
3
|
+
require 'nokogiri'
|
4
|
+
require 'zipruby'
|
5
|
+
require 'mini_magick'
|
6
|
+
require 'base64'
|
7
|
+
|
8
|
+
module DocxTemplater
|
9
|
+
def log(str)
|
10
|
+
# braindead logging
|
11
|
+
# puts str
|
12
|
+
end
|
13
|
+
extend self
|
14
|
+
end
|
15
|
+
|
16
|
+
require 'docx_templater/template_processor'
|
17
|
+
require 'docx_templater/docx_creator'
|
18
|
+
require 'docx_templater/image'
|