Sha256: b049b19c398731e90a051723299613d7cff51a2253929376fa842849ffbe02cd

Contents?: true

Size: 958 Bytes

Versions: 2

Compression:

Stored size: 958 Bytes

Contents

require 'hexapdf'
require 'open-uri'

module AlegoPdf
  class Merging
    attr_reader :ids, :model, :attribute, :filename

    def initialize(ids, model, attribute, filename = 'tmp/merge_files.pdf')
      @ids = ids
      @model = model
      @attribute = attribute
      @filename = filename
    end

    def call
      array = model.is_a?(String) ? model.camelize.constantize.where(id: ids) : model.where(id: ids)
      target = HexaPDF::Document.new

      array.each do |object|
        file = object[attribute]
        filepath = file.try(:url) || object.try(:arquivo_url)

        next if filepath.blank?

        uri = URI.parse(filepath).open(&:read)
        tempfile = Tempfile.new
        tempfile.write(uri.force_encoding('UTF-8'))
        tempfile.close

        pdf = HexaPDF::Document.open(tempfile)
        pdf.pages.each { |page| target.pages << target.import(page) }
      end

      target.write(filename, optimize: true)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
alego_pdf-2.0.1 lib/alego_pdf/merging.rb
alego_pdf-2.0.0 lib/alego_pdf/merging.rb