Class: Docx::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/docx/document.rb

Overview

The Document class wraps around a docx file and provides methods to interface with it.

# get a Docx::Document for a docx file in the local directory
doc = Docx::Document.open("test.docx")

# get the text from the document
puts doc.text

# do the same thing in a block
Docx::Document.open("test.docx") do |d|
  puts d.text
end

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, &block) ⇒ Document

Returns a new instance of Document.



21
22
23
24
25
26
27
28
# File 'lib/docx/document.rb', line 21

def initialize(path, &block)
  @replace = {}
  if block_given?
    @parser = Parser.new(File.expand_path(path), &block)
  else
    @parser = Parser.new(File.expand_path(path))
  end
end

Class Method Details

.open(path, &block) ⇒ Object

With no associated block, Docx::Document.open is a synonym for Docx::Document.new. If the optional code block is given, it will be passed the opened docx file as an argument and the Docx::Document oject will automatically be closed when the block terminates. The values of the block will be returned from Docx::Document.open. call-seq:

open(filepath) => file
open(filepath) {|file| block } => obj


34
35
36
# File 'lib/docx/document.rb', line 34

def self.open(path, &block)
  self.new(path, &block)
end

Instance Method Details

#each_paragraphObject

Deprecated

Iterates over paragraphs within document call-seq:

each_paragraph => Enumerator


44
45
46
# File 'lib/docx/document.rb', line 44

def each_paragraph
  paragraphs.each { |p| yield(p) }
end

#save(path) ⇒ Object

Save document to provided path call-seq:

save(filepath) => void


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/docx/document.rb', line 57

def save(path)
  update
  Zip::ZipOutputStream.open(path) do |out|
    zip.each do |entry|
      out.put_next_entry(entry.name)

      if @replace[entry.name]
        out.write(@replace[entry.name])
      else
        out.write(zip.read(entry.name))
      end
    end
  end
  zip.close
end

#to_sObject Also known as: text

call-seq:

to_s -> string


50
51
52
# File 'lib/docx/document.rb', line 50

def to_s
  paragraphs.map(&:to_s).join("\n")
end