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

will able to read or update header and footer #42

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 16 additions & 2 deletions lib/docx/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down