lib/alego_pdf/merging.rb in alego_pdf-2.0.1 vs lib/alego_pdf/merging.rb in alego_pdf-3.0.0

- old
+ new

@@ -1,22 +1,50 @@ require 'hexapdf' require 'open-uri' module AlegoPdf class Merging - attr_reader :ids, :model, :attribute, :filename + attr_reader :ids, :model, :attribute, :filename, :urls, :orderize, :target - def initialize(ids, model, attribute, filename = 'tmp/merge_files.pdf') + 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) - target = HexaPDF::Document.new array.each do |object| file = object[attribute] filepath = file.try(:url) || object.try(:arquivo_url) @@ -28,10 +56,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