module HexaPDF::Filter::FlateDecode

Implements the Deflate filter using the Zlib library.

See: HexaPDF::Filter, PDF1.7 s7.4.4

Public Class Methods

decoder(source, options = nil) click to toggle source

See HexaPDF::Filter

The decoder also handles the case of an empty string not deflated to a correct flate stream but just output as an empty string.

# File lib/hexapdf/filter/flate_decode.rb, line 54
def self.decoder(source, options = nil)
  fib = Fiber.new do
    inflater = Zlib::Inflate.new
    while source.alive? && (data = source.resume)
      next if data.empty?
      begin
        data = inflater.inflate(data)
      rescue StandardError => e
        raise FilterError, "Problem while decoding Flate encoded stream: #{e}"
      end
      Fiber.yield(data)
    end
    begin
      data = inflater.total_in == 0 || (data = inflater.finish).empty? ? nil : data
      inflater.close
      data
    rescue StandardError => e
      raise FilterError, "Problem while decoding Flate encoded stream: #{e}"
    end
  end

  if options && options[:Predictor]
    Predictor.decoder(fib, options)
  else
    fib
  end
end
encoder(source, options = nil) click to toggle source

See HexaPDF::Filter

# File lib/hexapdf/filter/flate_decode.rb, line 83
def self.encoder(source, options = nil)
  if options && options[:Predictor]
    source = Predictor.encoder(source, options)
  end

  Fiber.new do
    deflater = Zlib::Deflate.new(HexaPDF::GlobalConfiguration['filter.flate_compression'],
                                 Zlib::MAX_WBITS,
                                 HexaPDF::GlobalConfiguration['filter.flate_memory'])
    while source.alive? && (data = source.resume)
      data = deflater.deflate(data)
      Fiber.yield(data)
    end
    data = deflater.finish
    deflater.close
    data
  end
end