diff --git a/README.md b/README.md index e779291..28b8354 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,16 @@ require 'docx' # Create a Docx::Document object for our existing docx file doc = Docx::Document.open('example.docx') +# Read Header from docx file +doc.header.xpath('//w:t').each do |node| +.... +end + +# Read Footer from docx file +doc.footer.xpath('//w:t').each do |node| +.... +end + # Retrieve and display paragraphs doc.paragraphs.each do |p| puts p diff --git a/lib/docx/document.rb b/lib/docx/document.rb index a5722d3..08b96b3 100755 --- a/lib/docx/document.rb +++ b/lib/docx/document.rb @@ -18,12 +18,25 @@ module Docx # puts d.text # end class Document - attr_reader :xml, :doc, :zip, :styles + attr_reader :xml, :doc, :zip, :styles, :header, :footer def initialize(path, &block) @replace = {} @zip = Zip::File.open(path) @document_xml = @zip.read('word/document.xml') + header_path = 'word/header1.xml' + footer_path = 'word/footer1.xml' + + if @zip.find_entry(header_path) + @header_xml = @zip.read(header_path) + @header = Nokogiri::XML(@header_xml) + end + + if @zip.find_entry(footer_path) + @footer_xml = @zip.read(footer_path) + @footer = Nokogiri::XML(@footer_xml) + end + @doc = Nokogiri::XML(@document_xml) @styles_xml = @zip.read('word/styles.xml') @styles = Nokogiri::XML(@styles_xml) @@ -103,7 +116,6 @@ def save(path) Zip::OutputStream.open(path) do |out| zip.each do |entry| out.put_next_entry(entry.name) - if @replace[entry.name] out.write(@replace[entry.name]) else @@ -129,6 +141,8 @@ def replace_entry(entry_path, file_contents) #++ def update replace_entry "word/document.xml", doc.serialize(:save_with => 0) + replace_entry "word/header1.xml", header.serialize(:save_with => 0) if header + replace_entry "word/footer1.xml", footer.serialize(:save_with => 0) if footer end # generate Elements::Containers::Paragraph from paragraph XML node