Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/docx/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ module Docx
# puts d.text
# end
class Document
attr_reader :xml, :doc, :zip, :styles
attr_reader :xml, :doc, :zip, :styles, :headers

def initialize(path_or_io, options = {})
@replace = {}
Expand All @@ -37,6 +37,7 @@ def initialize(path_or_io, options = {})
@document_xml = document.get_input_stream.read
@doc = Nokogiri::XML(@document_xml)
load_styles
load_headers
yield(self) if block_given?
ensure
@zip.close unless @zip.nil?
Expand Down Expand Up @@ -170,6 +171,15 @@ def replace_entry(entry_path, file_contents)

private

def load_headers
header_files = @zip.glob("word/header*.xml").map{|h| h.name}
filename_and_contents_pairs = header_files.map do |file|
simple_file_name = file.sub(/^word\//, "").sub(/\.xml$/, "")
[simple_file_name, Nokogiri::XML(@zip.read(file))]
end
@headers = Hash[filename_and_contents_pairs]
end

def load_styles
@styles_xml = @zip.read('word/styles.xml')
@styles = Nokogiri::XML(@styles_xml)
Expand Down
12 changes: 12 additions & 0 deletions spec/docx/document_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@
end
end

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

it 'can extract headers' do
expect(@doc.headers).to_not be_nil
expect(@doc.headers.keys).to eq ["header1"]
expect(@doc.headers["header1"].text).to eq "Hello from the header."
end
end

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