From c508af254f3170644e453808f50feac8c233e962 Mon Sep 17 00:00:00 2001 From: Jawad Ahmad Date: Fri, 26 Jul 2024 16:42:19 +0500 Subject: [PATCH 1/2] ability to extract headers and footers --- lib/docx/document.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/docx/document.rb b/lib/docx/document.rb index 4fe0ee1..113694c 100755 --- a/lib/docx/document.rb +++ b/lib/docx/document.rb @@ -75,6 +75,20 @@ def bookmarks bkmrks_hsh end + def headers + @zip.glob('word/header*.xml').map do |entry| + header_xml = entry.get_input_stream.read + Nokogiri::XML(header_xml) + end + end + + def 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 From 9a39e71de4aa998f035a0db3ea601bab107e42e1 Mon Sep 17 00:00:00 2001 From: Jawad Ahmad Date: Tue, 30 Jul 2024 13:12:38 +0500 Subject: [PATCH 2/2] persisting headers and footers after fetch --- lib/docx/document.rb | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/lib/docx/document.rb b/lib/docx/document.rb index 113694c..8d7833c 100755 --- a/lib/docx/document.rb +++ b/lib/docx/document.rb @@ -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 = {} @@ -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 @@ -75,14 +77,14 @@ def bookmarks bkmrks_hsh end - def headers + 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 footers + def fetch_footers @zip.glob('word/footer*.xml').map do |entry| footer_xml = entry.get_input_stream.read Nokogiri::XML(footer_xml) @@ -224,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