Files
docuseal/lib/templates/process_document.rb
T

65 lines
2.0 KiB
Ruby
Raw Normal View History

2023-05-21 17:59:36 +03:00
# frozen_string_literal: true
2023-05-31 23:19:20 +03:00
module Templates
2023-05-21 17:59:36 +03:00
module ProcessDocument
DPI = 200
FORMAT = '.jpg'
ATTACHMENT_NAME = 'preview_images'
PDF_CONTENT_TYPE = 'application/pdf'
Q = 35
MAX_WIDTH = 1400
module_function
2023-09-01 01:27:13 +03:00
def call(attachment, data)
2023-05-21 17:59:36 +03:00
if attachment.content_type == PDF_CONTENT_TYPE
2023-09-01 01:27:13 +03:00
generate_pdf_preview_images(attachment, data)
2023-06-25 11:35:23 +03:00
elsif attachment.image?
2023-09-01 01:27:13 +03:00
generate_preview_image(attachment, data)
2023-05-21 17:59:36 +03:00
end
attachment
end
2023-09-01 01:27:13 +03:00
def generate_preview_image(attachment, data)
2023-05-21 17:59:36 +03:00
ActiveStorage::Attachment.where(name: ATTACHMENT_NAME, record: attachment).destroy_all
2023-09-01 01:27:13 +03:00
image = Vips::Image.new_from_buffer(data, '')
2023-07-07 00:54:32 +03:00
image = image.autorot.resize(MAX_WIDTH / image.width.to_f)
2023-05-21 17:59:36 +03:00
2023-06-09 01:43:43 +03:00
io = StringIO.new(image.write_to_buffer(FORMAT, Q: Q, interlace: true))
2023-05-21 17:59:36 +03:00
ActiveStorage::Attachment.create!(
blob: ActiveStorage::Blob.create_and_upload!(
io:, filename: "0#{FORMAT}",
metadata: { analyzed: true, identified: true, width: image.width, height: image.height }
),
name: ATTACHMENT_NAME,
record: attachment
)
end
2023-09-01 01:27:13 +03:00
def generate_pdf_preview_images(attachment, data)
2023-05-21 17:59:36 +03:00
ActiveStorage::Attachment.where(name: ATTACHMENT_NAME, record: attachment).destroy_all
2023-09-17 17:00:21 +03:00
number_of_pages = HexaPDF::Document.new(io: StringIO.new(data)).pages.size - 1
2023-05-21 17:59:36 +03:00
2023-06-09 01:43:43 +03:00
(0..number_of_pages).each do |page_number|
2023-09-01 01:27:13 +03:00
page = Vips::Image.new_from_buffer(data, '', dpi: DPI, page: page_number)
2023-05-21 17:59:36 +03:00
page = page.resize(MAX_WIDTH / page.width.to_f)
2023-06-09 01:43:43 +03:00
io = StringIO.new(page.write_to_buffer(FORMAT, Q: Q, interlace: true))
2023-05-21 17:59:36 +03:00
ActiveStorage::Attachment.create!(
blob: ActiveStorage::Blob.create_and_upload!(
io:, filename: "#{page_number}#{FORMAT}",
metadata: { analyzed: true, identified: true, width: page.width, height: page.height }
),
name: ATTACHMENT_NAME,
record: attachment
)
end
end
end
end