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