add tool to merge pdf files

This commit is contained in:
Alex Turchyn
2024-07-10 01:42:10 +03:00
committed by Pete Matsyburka
parent 286b8d7067
commit ab49af9bcb
3 changed files with 36 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
# frozen_string_literal: true
module Api
class ToolsController < ApiBaseController
skip_authorization_check
def merge
files = params[:files] || []
return render json: { error: 'Files are required' }, status: :unprocessable_entity if files.blank?
return render json: { error: 'At least 2 files are required' }, status: :unprocessable_entity if files.size < 2
render json: {
data: Base64.encode64(PdfUtils.merge(files.map { |base64| StringIO.new(Base64.decode64(base64)) }).string)
}
end
end
end
+3
View File
@@ -41,6 +41,9 @@ Rails.application.routes.draw do
resources :clone, only: %i[create], controller: 'templates_clone'
resources :submissions, only: %i[index create]
end
resources :tools, only: %i[] do
post :merge, on: :collection
end
end
resources :verify_pdf_signature, only: %i[create]
+15
View File
@@ -26,4 +26,19 @@ module PdfUtils
decrypted_io.tap(&:rewind).read
end
def merge(files)
merged_pdf = HexaPDF::Document.new
files.each do |file|
pdf = HexaPDF::Document.new(io: file)
pdf.pages.each { |page| merged_pdf.pages << merged_pdf.import(page) }
end
merged_content = StringIO.new
merged_pdf.write(merged_content)
merged_content.rewind
merged_content
end
end