Skip to content

Instantly share code, notes, and snippets.

@hdchinh
Created May 24, 2023 04:31
Show Gist options
  • Save hdchinh/f72f7e5ac526a2858e58c3a447d3e4ad to your computer and use it in GitHub Desktop.
Save hdchinh/f72f7e5ac526a2858e58c3a447d3e4ad to your computer and use it in GitHub Desktop.
require "prawn"
class AddWatermarkService
def initialize(cv)
@cv = cv
end
def perform
begin
return { cv: @cv, success: false } if File.extname(@cv.original_filename) != ".pdf"
@random_uid = SecureRandom.hex
pdf = @cv.read
save_path = Rails.root.join("tmp", "#{@random_uid}.pdf")
File.open(save_path, "wb") { |file| file << pdf }
# Get size of the CV
reader = PDF::Reader.new("#{Rails.root}/tmp/#{@random_uid}.pdf")
bbox = reader.pages.first.attributes[:MediaBox]
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
# Generate watermark
header_img = "#{Rails.root}/share/header.png"
watermark_img = "#{Rails.root}/share/center.png"
save_path = Rails.root.join("tmp", "watermark_#{@random_uid}.pdf")
Prawn::Document.generate(save_path, page_size: [width, height], margin: 0) do
image header_img, vposition: :top, position: :left, width: 130, height: 20
image watermark_img, vposition: :center, position: :center
end
# Add watermark
company_logo = CombinePDF.load("#{Rails.root}/tmp/watermark_#{@random_uid}.pdf").pages[0]
pdf = CombinePDF.load("#{Rails.root}/tmp/#{@random_uid}.pdf")
pdf.pages.each { |page| page << company_logo }
# Remove tmp file
File.delete("#{Rails.root}/tmp/watermark_#{@random_uid}.pdf")
File.delete("#{Rails.root}/tmp/#{@random_uid}.pdf")
return { cv: pdf, success: true }
rescue StandardError => e
return { cv: @cv, success: false }
end
end
private
def pt2mm(pt)
(pt2in(pt) * BigDecimal("25.4")).round(2)
end
def pt2in(pt)
(pt / BigDecimal("72")).round(2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment