Class: Shipping::PreProcessCanadaPostLabel

Inherits:
Object
  • Object
show all
Defined in:
app/services/shipping/pre_process_canada_post_label.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.testObject



38
39
40
41
# File 'app/services/shipping/pre_process_canada_post_label.rb', line 38

def self.test
  path = Rails.root.join('extras', 'samples', 'shipping_labels', 'canada_post_test_label_multiple.pdf')
  new.process(path)
end

Instance Method Details

#process(original_file_path, out_file_path: nil) ⇒ Object

Canada Post labels need cropping from a specific offset



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'app/services/shipping/pre_process_canada_post_label.rb', line 6

def process(original_file_path, out_file_path: nil)
  require 'vips'

  directory_path = File.dirname(original_file_path)
  base_name = File.basename(original_file_path, '.pdf')
  out_file_path ||= "#{directory_path}/#{base_name}_out.pdf"

  # Load PDF at 150 DPI (matching the original density)
  image = Vips::Image.new_from_file(original_file_path, dpi: 150, page: 0)

  # Crop to 612x918 starting at offset (970, 148)
  # Equivalent to crop('612x918+970+148')
  left = [970, image.width - 1].min
  top = [148, image.height - 1].min
  width = [612, image.width - left].min
  height = [918, image.height - top].min
  image = image.crop(left, top, width, height)

  # Flatten alpha channel with white background
  if image.has_alpha?
    image = image.flatten(background: [255, 255, 255])
  end

  # Resize to 612x918 (letter size at 72 DPI)
  image = image.thumbnail_image(612, height: 918, size: :force)

  # Write as PDF
  image.write_to_file(out_file_path)

  out_file_path
end