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