Skip to content

Commit d5fdc90

Browse files
committed
Document handles a docx file without styles.xml
1 parent 8095309 commit d5fdc90

3 files changed

Lines changed: 23 additions & 2 deletions

File tree

lib/docx/document.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,7 @@ def initialize(path, &block)
2525
@zip = Zip::File.open(path)
2626
@document_xml = @zip.read('word/document.xml')
2727
@doc = Nokogiri::XML(@document_xml)
28-
@styles_xml = @zip.read('word/styles.xml')
29-
@styles = Nokogiri::XML(@styles_xml)
28+
load_styles
3029
if block_given?
3130
yield self
3231
@zip.close
@@ -70,6 +69,8 @@ def tables
7069
# Some documents have this set, others don't.
7170
# Values are returned as half-points, so to get points, that's why it's divided by 2.
7271
def font_size
72+
return nil unless @styles
73+
7374
size_tag = @styles.xpath('//w:docDefaults//w:rPrDefault//w:rPr//w:sz').first
7475
size_tag ? size_tag.attributes['val'].value.to_i / 2 : nil
7576
end
@@ -123,6 +124,14 @@ def replace_entry(entry_path, file_contents)
123124

124125
private
125126

127+
def load_styles
128+
@styles_xml = @zip.read('word/styles.xml')
129+
@styles = Nokogiri::XML(@styles_xml)
130+
rescue Errno::ENOENT => e
131+
warn e.message
132+
nil
133+
end
134+
126135
#--
127136
# TODO: Flesh this out to be compatible with other files
128137
# TODO: Method to set flag on files that have been edited, probably by inserting something at the

spec/docx/document_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,18 @@
3939
end
4040
end
4141
end
42+
43+
describe '#font_size' do
44+
context 'When a docx files has no styles.xml' do
45+
before do
46+
@doc = Docx::Document.new(@fixtures_path + '/no_styles.docx')
47+
end
48+
49+
it 'should raise an error' do
50+
expect(@doc.font_size).to be_nil
51+
end
52+
end
53+
end
4254
end
4355

4456
describe 'read tables' do

spec/fixtures/no_styles.docx

3.46 KB
Binary file not shown.

0 commit comments

Comments
 (0)