Skip to content

Commit

Permalink
added headers and footers to docx
Browse files Browse the repository at this point in the history
Grab from this PR: ruby-docx#153
  • Loading branch information
pzgz committed Oct 7, 2024
1 parent c5bcb57 commit dd7922d
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions lib/docx/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ module Docx
class Document
include Docx::SimpleInspect

attr_reader :xml, :doc, :zip, :styles
attr_reader :xml, :doc, :zip, :styles, :headers, :footers

def initialize(path_or_io, options = {})
@replace = {}
Expand All @@ -40,6 +40,8 @@ def initialize(path_or_io, options = {})

@document_xml = document.get_input_stream.read
@doc = Nokogiri::XML(@document_xml)
@headers = fetch_headers
@footers = fetch_footers
load_styles
yield(self) if block_given?
ensure
Expand Down Expand Up @@ -75,6 +77,20 @@ def bookmarks
bkmrks_hsh
end

def fetch_headers
@zip.glob('word/header*.xml').map do |entry|
header_xml = entry.get_input_stream.read
Nokogiri::XML(header_xml)
end
end

def fetch_footers
@zip.glob('word/footer*.xml').map do |entry|
footer_xml = entry.get_input_stream.read
Nokogiri::XML(footer_xml)
end
end

def to_xml
Nokogiri::XML(@document_xml)
end
Expand Down Expand Up @@ -210,6 +226,12 @@ def load_rels
def update
replace_entry 'word/document.xml', doc.serialize(save_with: 0)
replace_entry 'word/styles.xml', styles_configuration.serialize(save_with: 0)
headers.each_with_index do |header, index|
replace_entry "word/header#{index + 1}.xml", header.serialize(:save_with => 0) if header
end
footers.each_with_index do |footer, index|
replace_entry "word/footer#{index + 1}.xml", footer.serialize(:save_with => 0) if footer
end
end

# generate Elements::Containers::Paragraph from paragraph XML node
Expand All @@ -226,4 +248,4 @@ def parse_table_from(t_node)
Elements::Containers::Table.new(t_node)
end
end
end
end

0 comments on commit dd7922d

Please sign in to comment.