Skip to content

Instantly share code, notes, and snippets.

@bnagy
Created June 8, 2015 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bnagy/b2b7670714ae35f5eac3 to your computer and use it in GitHub Desktop.
Save bnagy/b2b7670714ae35f5eac3 to your computer and use it in GitHub Desktop.
docx.rb
# Abstract access to internal files in docx format. Right now this uses system
# zip and tempfiles because the available ruby zip libraries don't seem to be
# able to produce files that Word will read.
#
# Author: Ben Nagy
# Copyright: Copyright (c) Ben Nagy, 2006-2013.
# License: The MIT License
# (See http://www.opensource.org/licenses/mit-license.php for details.)
require 'tempfile'
class Docx
def initialize( source_fname, tmpdir=Dir.tmpdir )
if `which zip`.empty? or `which unzip`.empty?
raise "#{__FILE__}: Unable to find system zip / unzip binaries."
end
@file_copy=Tempfile.new ['foo','.docx'], tmpdir, 'wb+'
File.open( File.expand_path( source_fname ), 'rb') {|io|
@file_copy.write io.read
}
@file_copy.rewind
@unzipped_dirname="#{@file_copy.path}.unzipped"
`unzip #{@file_copy.path} -d #{@unzipped_dirname}`
end
def files
Dir["#{@unzipped_dirname}/**/*"].reject {|fname|
File.directory? fname
}
end
# Add or replace
def write( fname, replace_str )
@unzipped_dirname_hackycrap||=@unzipped_dirname + '/'
relname=fname.rpartition( @unzipped_dirname_hackycrap ).last
old=Dir.pwd
Dir.chdir @unzipped_dirname
File.open( relname, 'wb+' ) {|io| io.write replace_str}
`zip -r #{@file_copy.path} #{relname}`
Dir.chdir old
end
def read
File.open( @file_copy.path, 'rb' ) {|io| io.read}
end
def close
@file_copy.close
@file_copy.unlink
`rm -rf #{@unzipped_dirname}`
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment