Skip to content

Commit ad67fc8

Browse files
committed
Allow access to other XML docs in docx file like the header and footer
1 parent 8c40b4c commit ad67fc8

File tree

3 files changed

+37
-5
lines changed

3 files changed

+37
-5
lines changed

lib/docx/document.rb

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,22 @@ module Docx
1818
# puts d.text
1919
# end
2020
class Document
21-
attr_reader :xml, :doc, :zip, :styles
21+
22+
DOCUMENT_PATHS = {
23+
doc: "word/document.xml",
24+
styles: "word/styles.xml",
25+
header: "word/header1.xml",
26+
footer: "word/footer1.xml",
27+
numbering: "word/numbering.xml"
28+
}
29+
30+
attr_reader :xml, :doc, :zip, :styles, :header, :footer, :numbering
2231

2332
def initialize(path, &block)
2433
@replace = {}
2534
@zip = Zip::File.open(path)
26-
@document_xml = @zip.read('word/document.xml')
27-
@doc = Nokogiri::XML(@document_xml)
28-
@styles_xml = @zip.read('word/styles.xml')
29-
@styles = Nokogiri::XML(@styles_xml)
35+
extract_documents
36+
3037
if block_given?
3138
yield self
3239
@zip.close
@@ -123,6 +130,15 @@ def replace_entry(entry_path, file_contents)
123130

124131
private
125132

133+
def extract_documents
134+
DOCUMENT_PATHS.each do |attr_name, path|
135+
if @zip.find_entry(path)
136+
xml_doc = @zip.read(path)
137+
self.instance_variable_set(:"@#{attr_name}", Nokogiri::XML(xml_doc))
138+
end
139+
end
140+
end
141+
126142
#--
127143
# TODO: Flesh this out to be compatible with other files
128144
# TODO: Method to set flag on files that have been edited, probably by inserting something at the

spec/docx/document_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,22 @@
279279
end
280280
end
281281

282+
describe 'multiple documents' do
283+
before do
284+
@doc = Docx::Document.open(@fixtures_path + '/multi_doc.docx')
285+
end
286+
287+
it 'should extract all inner documents' do
288+
expect(@doc.doc).to_not be_nil
289+
expect(@doc.styles).to_not be_nil
290+
expect(@doc.header).to_not be_nil
291+
expect(@doc.header.text).to eq "Hello from the header."
292+
expect(@doc.footer).to_not be_nil
293+
expect(@doc.footer.text).to eq "Hello from the footer."
294+
expect(@doc.numbering).to_not be_nil
295+
end
296+
end
297+
282298
describe 'saving' do
283299
before do
284300
@doc = Docx::Document.open(@fixtures_path + '/saving.docx')

spec/fixtures/multi_doc.docx

6.13 KB
Binary file not shown.

0 commit comments

Comments
 (0)