Sha256: 68648a71943d944a05c6add9cf3d186a549b562f6531949d4f5728f28f0a789d

Contents?: true

Size: 1.38 KB

Versions: 4

Compression:

Stored size: 1.38 KB

Contents

# encoding: UTF-8
module Grim
  class Pdf
    include Enumerable

    attr_reader :path

    # ghostscript prints out a warning, this regex matches it
    WarningRegex = /\*\*\*\*.*\n/

    # Raises an error if pdf not found and sets some instance
    # variables if pdf is found.
    #
    # path - A String or Path to the pdf
    #
    def initialize(path)
      raise Grim::PdfNotFound unless File.exists?(path)
      @path = path
    end

    # Shells out to ghostscript to read the pdf with the pdf_info.ps script
    # as a filter, returning the number of pages in the pdf as an integer.
    #
    # For example:
    #
    #   pdf.count
    #   # => 4
    #
    # Returns an Integer.
    #
    def count
      @count ||= begin
        result = SafeShell.execute("gs", "-dNODISPLAY", "-q", "-sFile=#{@path}", File.expand_path('../../../lib/pdf_info.ps', __FILE__))
        result.gsub(WarningRegex, '').to_i
      end
    end

    # Creates an instance Grim::Page for the index passed in.
    #
    # index - accepts Integer for position in array
    #
    # For example:
    #
    #   pdf[4]  # returns 5th page
    #
    # Returns an instance of Grim::Page.
    #
    def [](index)
      raise Grim::PageNotFound unless index >= 0 && index < count
      Grim::Page.new(self, index)
    end

    def each
      (0..(count-1)).each do |index|
        yield Grim::Page.new(self, index)
      end
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
grim-0.2.4 lib/grim/pdf.rb
grim-0.2.3 lib/grim/pdf.rb
grim-0.2.2 lib/grim/pdf.rb
grim-0.2.1 lib/grim/pdf.rb