Sha256: be1262f7f29db05cbaaeae2d07801e86dc61f29d63fd93fffd02af8bf02a5bf1

Contents?: true

Size: 1.55 KB

Versions: 1

Compression:

Stored size: 1.55 KB

Contents

require 'hexapdf'
require 'open-uri'

module AlegoPdf
  class Merging
    attr_reader :ids, :model, :attribute, :filename, :urls, :orderize, :target

    def initialize(ids, model, attribute, filename = 'tmp/merge_files.pdf', urls = [], orderize = 'url')
      @ids = ids
      @model = model
      @attribute = attribute
      @filename = filename
      @urls = urls
      @orderize = orderize
      @target = HexaPDF::Document.new
    end

    def call
      if orderize == 'url'
        join_urls
        join_array
      else
        join_array
        join_urls
      end

      target.write(filename, optimize: true)
    end

    def join_urls
      urls.each do |filepath|
        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 
    end

    def join_array
      array = model.is_a?(String) ? model.camelize.constantize.where(id: ids) : model.where(id: ids)

      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
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
alego_pdf-3.0.0 lib/alego_pdf/merging.rb