updating delete and add blank image/page from backend for pdf too

pull/150/merge^2
iozeey 2 years ago
parent 18b14a9230
commit 9cad047bfb

@ -26,11 +26,11 @@ module Api
def del_image def del_image
template = Template.find(params[:template_id]) template = Template.find(params[:template_id])
attachment_id = params[:attachment_id] document = template.documents.find(params[:documentId])
document_id = params[:documentId] img_attachment_id = params[:attachment_id]
page_number = template.documents.find(document_id).preview_images.find_index { |pic| pic.id == attachment_id } page_number = document.preview_images.find_index { |pic| pic.id == img_attachment_id }
if page_number if page_number
Templates::ProcessDocument.delete_picture(template, attachment_id, page_number) Templates::ProcessDocument.delete_picture(template, document, img_attachment_id, page_number)
render json: { success: true, message: 'image deleted successfully' } render json: { success: true, message: 'image deleted successfully' }
else else
page_number = "No image found for deletion" page_number = "No image found for deletion"

@ -1,15 +1,17 @@
document.addEventListener("DOMContentLoaded", function () { document.addEventListener('DOMContentLoaded', function () {
function showLoading() { function showLoading () {
document.getElementById("loader").style.display = "block"; document.getElementById('loader').style.display = 'block'
} }
var editTemplateLink = document.getElementById("edit-template-link"); const editTemplateLink = document.getElementById('edit-template-link')
editTemplateLink.addEventListener("click", function (event) { if (editTemplateLink) {
event.preventDefault(); editTemplateLink.addEventListener('click', function (event) {
showLoading(); event.preventDefault()
showLoading()
var template = this.getAttribute("data-template"); const template = this.getAttribute('data-template')
setTimeout(function () { setTimeout(function () {
window.location.href = template; window.location.href = template
}, 3000); }, 3000)
}); })
}); }
})

@ -452,7 +452,6 @@ export default {
scrollIntoDocument (item, page) { scrollIntoDocument (item, page) {
const documentRef = this.documentRefs.find((e) => e.document.uuid === item.attachment_uuid) const documentRef = this.documentRefs.find((e) => e.document.uuid === item.attachment_uuid)
documentRef.scrollIntoDocument(page) documentRef.scrollIntoDocument(page)
// pageRef.$el.scrollIntoView({ behavior: 'smooth', block: 'start' })
}, },
onKeyUp (e) { onKeyUp (e) {
if (e.code === 'Escape') { if (e.code === 'Escape') {
@ -648,7 +647,7 @@ export default {
this.save() this.save()
}, },
onDocumentRemove (item) { onDocumentRemove (item) {
if (window.confirm('Are you sure?')) { if (window.confirm('Are you sure you want to delete the document?')) {
this.template.schema.splice(this.template.schema.indexOf(item), 1) this.template.schema.splice(this.template.schema.indexOf(item), 1)
} }
@ -744,58 +743,46 @@ export default {
}) })
}, },
removeImage (item, imageId) { removeImage (item, imageId) {
// console.log(this.template.documents[0].preview_secured_images) const document = this.template.documents.find((e) => e.uuid === item.attachment_uuid)
// output: 0: {id: 26, name: 'preview_images', uuid: 'db2de68e-c52f-41e0-a743-550a5ba26ec0', record_type: 'ActiveStorage::Attachment', record_id: 25, } 1 : {id: 27, name: 'preview_images', uuid: '4f2cd882-95fb-4344-8571-78c9bb5a20aa', record_type: 'ActiveStorage::Attachment', record_id: 25, } 2: {id: 28, name: 'preview_images', uuid: '28bb656a-0799-4a73-b665-692aab2c690b', record_type: 'ActiveStorage::Attachment', record_id: 25, } length: 3, imageId: 27 if (Array.isArray(document.preview_images)) {
// const indexToRemove = this.template.documents.findIndex(item => item.id === imageId) const indexToRemove = document.preview_images.findIndex((previewImage) => previewImage.id === imageId)
this.template.documents.forEach((document) => { console.log(indexToRemove)
// Check if the document has a preview_images array if (indexToRemove !== -1) {
if (Array.isArray(document.preview_images)) { const confirmed = window.confirm('Are you sure you want to delete this image?')
// Find the index of the preview image with the matching id if (confirmed) {
const indexToRemove = document.preview_images.findIndex( const documentId = document.id
(previewImage) => previewImage.id === imageId const apiUrl = `/api/templates/${this.template.id}/documents/${documentId}/del_image`
) fetch(apiUrl, {
// console.log('simple preview', document.preview_images, ': secured', document.preview_secured_images) method: 'POST',
console.log(indexToRemove) headers: {
if (indexToRemove !== -1) { 'Content-Type': 'application/json'
const confirmed = window.confirm('Are you sure you want to delete this image?') },
if (confirmed) { body: JSON.stringify({
const documentId = document.id template: this.template.id,
const apiUrl = `/api/templates/${this.template.id}/documents/${documentId}/del_image` attachment_id: imageId,
fetch(apiUrl, { documentId
method: 'POST', })
headers: { })
'Content-Type': 'application/json' .then((response) => {
}, if (!response.ok) {
body: JSON.stringify({ throw new Error(`HTTP error! Status: ${response.status}`)
template: this.template.id, }
attachment_id: imageId, return response.json()
documentId })
// page_number: document.preview_images.find(x => x.id === imageId).name .then((data) => {
}) document.preview_images.splice(indexToRemove, 1)
window.location.reload()
console.log('Success:', data)
})
.catch((error) => {
console.error('Error:', error)
}) })
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
return response.json()
})
.then((data) => {
// remove from frontend
document.preview_images.splice(indexToRemove, 1)
console.log('Success:', data)
})
.catch((error) => {
console.error('Error:', error)
})
}
} }
} }
}) }
}, },
addBlankPage (item) { addBlankPage (item) {
const documentRef = this.documentRefs.find( const documentRef = this.documentRefs.find((e) => e.document.uuid === item.attachment_uuid)
(e) => e.document.uuid === item.attachment_uuid
)
const confirmed = window.confirm('Are you sure you want to create new image?') const confirmed = window.confirm('Are you sure you want to create new image?')
if (confirmed) { if (confirmed) {
const documentId = documentRef.document.id const documentId = documentRef.document.id
@ -817,6 +804,7 @@ export default {
return response.json() return response.json()
}) })
.then((data) => { .then((data) => {
window.location.reload()
console.log('Success: ---', data) console.log('Success: ---', data)
}) })
.catch((error) => { .catch((error) => {

@ -19,7 +19,18 @@
v-if="editable && index==0" v-if="editable && index==0"
class="flex justify-between w-full" class="flex justify-between w-full"
> >
<div style="width: 26px" /> <div
v-if="sortedPreviewImages.length != 1"
class="flex flex-col justify-between opacity-0 group-hover:opacity-100"
>
<button
class="btn border-base-200 bg-white text-base-content btn-xs rounded hover:text-base-100 hover:bg-base-content hover:border-base-content w-full transition-colors"
style="width: 24px; height: 24px"
@click.stop="$emit('remove-image', item, previewImage.id)"
>
&times;
</button>
</div>
<div class=""> <div class="">
<ReplaceButton <ReplaceButton
:is-direct-upload="isDirectUpload" :is-direct-upload="isDirectUpload"

@ -104,22 +104,6 @@ module Templates
io io
end end
def modify_pdf_data(original_pdf_data, excluded_page_number)
pdf = HexaPDF::Document.new(io: StringIO.new(original_pdf_data))
pdf.pages.delete_at(excluded_page_number)
modified_pdf_data = StringIO.new
pdf.write(modified_pdf_data)
modified_pdf_data.string
end
def create_blob_from_data(data, original_blob)
original_blob.tap do |blob|
blob.io = StringIO.new(data)
blob.filename = original_blob.filename
blob.save!
end
end
def generate_pdf_secured_preview_images(template, attachment, data) def generate_pdf_secured_preview_images(template, attachment, data)
ActiveStorage::Attachment.where(name: SECURED_ATTACHMENT_NAME, record: attachment).destroy_all ActiveStorage::Attachment.where(name: SECURED_ATTACHMENT_NAME, record: attachment).destroy_all
number_of_pages = PDF::Reader.new(StringIO.new(data)).pages.size - 1 number_of_pages = PDF::Reader.new(StringIO.new(data)).pages.size - 1
@ -127,14 +111,6 @@ module Templates
pdf = Vips::Image.new_from_buffer(data, '', dpi: DPI, page: page_number) pdf = Vips::Image.new_from_buffer(data, '', dpi: DPI, page: page_number)
pdf = pdf.resize(MAX_WIDTH / pdf.width.to_f) pdf = pdf.resize(MAX_WIDTH / pdf.width.to_f)
redacted_boxes = template.fields.select { |field| field['type'] == 'redact' && field['areas'][0]['page'] == page_number } redacted_boxes = template.fields.select { |field| field['type'] == 'redact' && field['areas'][0]['page'] == page_number }
deleted_page_field = template.fields.select { |field| field['type'] == 'deleted_page' && field['areas'][0]['page'] == page_number }
if !deleted_page_field.empty?
modified_pdf_data = modify_pdf_data(data, page_number)
attachment.blob = create_blob_from_data(modified_pdf_data, attachment.blob)
template.fields.delete(deleted_page_field)
template.save!
next
end
if !redacted_boxes.empty? if !redacted_boxes.empty?
redacted_boxes.each do |box| redacted_boxes.each do |box|
x = (box['areas'][0]['x'] * pdf.width).to_i x = (box['areas'][0]['x'] * pdf.width).to_i
@ -159,62 +135,115 @@ module Templates
end end
end end
def delete_picture(template, attachment_id, page_number) def delete_picture(template, document, image_attachment_id, page_number)
attachment = ActiveStorage::Attachment.find_by(id: attachment_id) image_attachment = ActiveStorage::Attachment.find_by(id: image_attachment_id)
return unless attachment return unless image_attachment
# attachment.purge file_path =
deleted_page_field = { if document.service.name == :disk
'type' => 'deleted_page', ActiveStorage::Blob.service.path_for(document.key)
'areas' => [{ end
'x' => 0, temp_dir = "#{Rails.root}/tmp/"
'y' => 0, FileUtils.mkdir_p(temp_dir)
'w' => 1, temp_file_path = "#{temp_dir}#{SecureRandom.uuid}.pdf"
'h' => 1, File.open(temp_file_path, 'wb') do |file|
'attachment_uuid' => SecureRandom.uuid, document.download { |chunk| file.write(chunk) }
'page' => page_number, end
}] pdf = HexaPDF::Document.open(temp_file_path)
} pdf.pages.delete_at(page_number)
template.fields << deleted_page_field pdf.write(temp_file_path)
template.save! document.reload
document.metadata[:pdf]['number_of_pages'] -= 1
temp_doc = document.metadata
new_attachment = document.attachments.update!(
name: document.name,
uuid: document.uuid,
blob: ActiveStorage::Blob.create_and_upload!(
io: File.open(temp_file_path),
filename: document.blob.filename,
content_type: document.blob.content_type,
metadata: temp_doc
)
)
document.blob.purge
image_attachment.purge
document.reload
File.delete(temp_file_path)
remaining_images = document.preview_images
remaining_images.each_with_index do |image, index|
new_filename = "#{index}.jpeg"
image.blob.update!(filename: new_filename)
end
rescue StandardError => e
Rails.logger.error("Error uploading new blank image: #{e.message}")
ensure
File.delete(temp_file_path) if File.exist?(temp_file_path)
end end
def upload_new_blank_image(template, document) def upload_new_blank_image(template, document)
file_path =
blank_image = generate_blank_image if document.service.name == :disk
blank_blob = create_blob_from_image(blank_image, document ) ActiveStorage::Blob.service.path_for(document.key)
# upload_new_attachment(template, blank_blob, ATTACHMENT_NAME) end
# puts '-----New blank image uploaded successfully!-----' temp_dir = "#{Rails.root}/tmp/"
if blank_blob FileUtils.mkdir_p(temp_dir)
Rails.logger.info('New blank image uploaded successfully!') temp_file_path = "#{temp_dir}#{SecureRandom.uuid}.pdf"
else File.open(temp_file_path, 'wb') do |file|
Rails.logger.info('Blank image not uploaded') document.download { |chunk| file.write(chunk) }
end end
end pdf = HexaPDF::Document.open(temp_file_path)
pdf.pages.add
pdf.write(temp_file_path)
def generate_blank_image document.reload
height = 2000 document.metadata[:pdf]['number_of_pages'] += 1
Vips::Image.new_from_array([[255]* MAX_WIDTH] * height, 255) temp_doc = document.metadata
end new_attachment = document.attachments.update!(
name: document.name,
uuid: document.uuid,
def create_blob_from_image(image, attachment)
begin
previews_count = attachment.preview_images.count
ActiveStorage::Attachment.create!(
blob: ActiveStorage::Blob.create_and_upload!( blob: ActiveStorage::Blob.create_and_upload!(
io: StringIO.new(image.write_to_buffer(FORMAT, Q: Q, interlace: true)), io: File.open(temp_file_path),
filename: "#{previews_count}#{FORMAT}", filename: document.blob.filename,
metadata: { analyzed: true, identified: true, width: image.width, height: image.height } content_type: document.blob.content_type,
), metadata: temp_doc
name: ATTACHMENT_NAME, )
record: attachment
) )
rescue => e document.blob.purge
Rails.logger.error("Error creating blob from image: #{e.message}") document.reload
end
# to update pdf images in storage blob
self.generate_pdf_preview_images(document, document.blob.download)
File.delete(temp_file_path)
rescue StandardError => e
Rails.logger.error("Error uploading new blank image: #{e.message}")
ensure
File.delete(temp_file_path) if File.exist?(temp_file_path)
end end
# def generate_blank_image
# # here height and width should be equal to height and width from existing pdf pages
# height = 2000
# width = MAX_WIDTH
# Vips::Image.new_from_array([[255]* width] * height, 255)
# end
# # def create_blob_from_image(image, attachment)
# def create_image_blob(image, attachment)
# begin
# previews_count = attachment.preview_images.count
# ActiveStorage::Attachment.create!(
# blob: ActiveStorage::Blob.create_and_upload!(
# io: StringIO.new(image.write_to_buffer(FORMAT, Q: Q, interlace: true)),
# filename: "#{previews_count}#{FORMAT}",
# metadata: { analyzed: true, identified: true, width: image.width, height: image.height }
# ),
# name: ATTACHMENT_NAME,
# record: attachment
# )
# rescue => e
# Rails.logger.error("Error creating blob from image: #{e.message}")
# end
# end
end end
end end

Loading…
Cancel
Save