Skip to content
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
18 changes: 15 additions & 3 deletions lib/docx_replace.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class Doc
def initialize(path, temp_dir=nil)
@zip_file = Zip::File.new(path)
@temp_dir = temp_dir
@document_file_path = get_document_file_path()
read_docx_file
end

Expand Down Expand Up @@ -40,9 +41,20 @@ def commit(new_path=nil)

private
DOCUMENT_FILE_PATH = 'word/document.xml'
def get_document_file_path
content_types_entry = @zip_file.find_entry '[Content_Types].xml'
raise 'Not an Open XML Document' unless content_types_entry

content_types = content_types_entry.get_input_stream.read
if m = content_types.match(/word\/document\d*\.xml/)
@document_file_path = m[0]
else
raise 'Not a Word document'
end
end

def read_docx_file
@document_content = @zip_file.read(DOCUMENT_FILE_PATH)
@document_content = @zip_file.read(@document_file_path)
end

def write_back_to_file(new_path=nil)
Expand All @@ -53,13 +65,13 @@ def write_back_to_file(new_path=nil)
end
Zip::OutputStream.open(temp_file.path) do |zos|
@zip_file.entries.each do |e|
unless e.name == DOCUMENT_FILE_PATH
unless e.name == @document_file_path
zos.put_next_entry(e.name)
zos.print e.get_input_stream.read
end
end

zos.put_next_entry(DOCUMENT_FILE_PATH)
zos.put_next_entry(@document_file_path)
zos.print @document_content
end

Expand Down
2 changes: 1 addition & 1 deletion lib/docx_replace/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module DocxReplace
VERSION = "1.2.1"
VERSION = "1.2.2"
end