Skip to content

Commit

Permalink
Allow access to other XML docs in docx file like the header and footer
Browse files Browse the repository at this point in the history
  • Loading branch information
yjukaku committed Oct 16, 2019
1 parent 8c40b4c commit ad67fc8
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
26 changes: 21 additions & 5 deletions lib/docx/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,22 @@ module Docx
# puts d.text
# end
class Document
attr_reader :xml, :doc, :zip, :styles

DOCUMENT_PATHS = {
doc: "word/document.xml",
styles: "word/styles.xml",
header: "word/header1.xml",
footer: "word/footer1.xml",
numbering: "word/numbering.xml"
}

attr_reader :xml, :doc, :zip, :styles, :header, :footer, :numbering

def initialize(path, &block)
@replace = {}
@zip = Zip::File.open(path)
@document_xml = @zip.read('word/document.xml')
@doc = Nokogiri::XML(@document_xml)
@styles_xml = @zip.read('word/styles.xml')
@styles = Nokogiri::XML(@styles_xml)
extract_documents

if block_given?
yield self
@zip.close
Expand Down Expand Up @@ -123,6 +130,15 @@ def replace_entry(entry_path, file_contents)

private

def extract_documents
DOCUMENT_PATHS.each do |attr_name, path|
if @zip.find_entry(path)
xml_doc = @zip.read(path)
self.instance_variable_set(:"@#{attr_name}", Nokogiri::XML(xml_doc))
end
end
end

#--
# TODO: Flesh this out to be compatible with other files
# TODO: Method to set flag on files that have been edited, probably by inserting something at the
Expand Down
16 changes: 16 additions & 0 deletions spec/docx/document_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,22 @@
end
end

describe 'multiple documents' do
before do
@doc = Docx::Document.open(@fixtures_path + '/multi_doc.docx')
end

it 'should extract all inner documents' do
expect(@doc.doc).to_not be_nil
expect(@doc.styles).to_not be_nil
expect(@doc.header).to_not be_nil
expect(@doc.header.text).to eq "Hello from the header."
expect(@doc.footer).to_not be_nil
expect(@doc.footer.text).to eq "Hello from the footer."
expect(@doc.numbering).to_not be_nil
end
end

describe 'saving' do
before do
@doc = Docx::Document.open(@fixtures_path + '/saving.docx')
Expand Down
Binary file added spec/fixtures/multi_doc.docx
Binary file not shown.

0 comments on commit ad67fc8

Please sign in to comment.