Skip to content

Commit a435144

Browse files
Ian NorrisIan Norris
authored andcommitted
[32] allow access to header
inspired from ruby-docx#73 but stripped down to just the header to see if that might be more amenable to get in. Also because of the TODO note in the update function, only supports reading these files, not updating them.
1 parent 564a364 commit a435144

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

lib/docx/document.rb

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ module Docx
1818
# puts d.text
1919
# end
2020
class Document
21-
attr_reader :xml, :doc, :zip, :styles
21+
attr_reader :xml, :doc, :zip, :styles, :headers
2222

2323
def initialize(path_or_io, options = {})
2424
@replace = {}
@@ -37,6 +37,7 @@ def initialize(path_or_io, options = {})
3737
@document_xml = document.get_input_stream.read
3838
@doc = Nokogiri::XML(@document_xml)
3939
load_styles
40+
load_headers
4041
yield(self) if block_given?
4142
ensure
4243
@zip.close unless @zip.nil?
@@ -170,6 +171,15 @@ def replace_entry(entry_path, file_contents)
170171

171172
private
172173

174+
def load_headers
175+
header_files = @zip.glob("word/header*.xml").map{|h| h.name}
176+
filename_and_contents_pairs = header_files.map do |file|
177+
simple_file_name = file.sub(/^word\//, "").sub(/\.xml$/, "")
178+
[simple_file_name, Nokogiri::XML(@zip.read(file))]
179+
end
180+
@headers = Hash[filename_and_contents_pairs]
181+
end
182+
173183
def load_styles
174184
@styles_xml = @zip.read('word/styles.xml')
175185
@styles = Nokogiri::XML(@styles_xml)

spec/docx/document_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,18 @@
5454
end
5555
end
5656

57+
describe 'read headers' do
58+
before do
59+
@doc = Docx::Document.open(@fixtures_path + '/multi_doc.docx')
60+
end
61+
62+
it 'can extract headers' do
63+
expect(@doc.headers).to_not be_nil
64+
expect(@doc.headers.keys).to eq ["header1"]
65+
expect(@doc.headers["header1"].text).to eq "Hello from the header."
66+
end
67+
end
68+
5769
describe 'read tables' do
5870
before do
5971
@doc = Docx::Document.open(@fixtures_path + '/tables.docx')

spec/fixtures/multi_doc.docx

6.13 KB
Binary file not shown.

0 commit comments

Comments
 (0)