Skip to content

Commit a930ea2

Browse files
author
miko53
committed
add method to read the paragraph style
1 parent dbac211 commit a930ea2

2 files changed

Lines changed: 34 additions & 3 deletions

File tree

lib/docx/containers/paragraph.rb

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ def initialize(node, document_properties = {})
2222
@font_size = @document_properties[:font_size]
2323
end
2424

25+
def document=(doc)
26+
@document = doc
27+
end
28+
2529
# Set text of paragraph
2630
def text=(content)
2731
if text_runs.size == 1
@@ -79,17 +83,30 @@ def font_size
7983
size_tag = @node.xpath('w:pPr//w:sz').first
8084
size_tag ? size_tag.attributes['val'].value.to_i / 2 : @font_size
8185
end
82-
86+
87+
def style
88+
return nil unless @document
89+
90+
if style_property.nil?
91+
@document.default_paragraph_style
92+
else
93+
@document.style_name(style_property.attributes['val'].value)
94+
end
95+
end
96+
8397
alias_method :text, :to_s
8498

8599
private
86100

101+
def style_property
102+
properties&.at_xpath('w:pStyle')
103+
end
104+
87105
# Returns the alignment if any, or nil if left
88106
def alignment
89107
alignment_tag = @node.xpath('.//w:jc').first
90108
alignment_tag ? alignment_tag.attributes['val'].value : nil
91109
end
92-
93110
end
94111
end
95112
end

lib/docx/document.rb

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,18 @@ def replace_entry(entry_path, file_contents)
168168
@replace[entry_path] = file_contents
169169
end
170170

171+
def default_paragraph_style
172+
s = @styles.at_xpath("w:styles/w:style[@w:type='paragraph' and @w:default='1']")
173+
s = s.at_xpath('w:name')
174+
s.attributes['val'].value
175+
end
176+
177+
def style_name(style_id)
178+
s = @styles.at_xpath("w:styles/w:style[@w:styleId='#{style_id}']")
179+
s = s.at_xpath('w:name')
180+
s.attributes['val'].value
181+
end
182+
171183
private
172184

173185
def load_styles
@@ -198,7 +210,9 @@ def update
198210

199211
# generate Elements::Containers::Paragraph from paragraph XML node
200212
def parse_paragraph_from(p_node)
201-
Elements::Containers::Paragraph.new(p_node, document_properties)
213+
p = Elements::Containers::Paragraph.new(p_node, document_properties)
214+
p.document = self
215+
p
202216
end
203217

204218
# generate Elements::Bookmark from bookmark XML node

0 commit comments

Comments
 (0)