Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to extract headers and footers #153

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion 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 Down