Class: DocPDF::Watermarker

Inherits:
Object
  • Object
show all
Defined in:
lib/docpdf/watermarker.rb

Constant Summary collapse

POSITIONS =
%i[center top bottom left right top_left top_right bottom_left bottom_right].freeze
STAMP_DEFAULTS =
{
  opacity: 0.1,
  position: :center,
  width: 250,
  offset_x: 0,
  offset_y: 0,
  pages: :all,
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pdf_bytes, stamps) ⇒ Watermarker

Returns a new instance of Watermarker.



88
89
90
91
# File 'lib/docpdf/watermarker.rb', line 88

def initialize(pdf_bytes, stamps)
  @pdf_bytes = pdf_bytes
  @stamps = stamps
end

Class Method Details

.calculate_position(position, page_w, page_h, img_w, img_h, offset_x, offset_y) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/docpdf/watermarker.rb', line 15

def calculate_position(position, page_w, page_h, img_w, img_h, offset_x, offset_y)
  x, y = case position
          when :center       then [(page_w - img_w) / 2, (page_h - img_h) / 2]
          when :top          then [(page_w - img_w) / 2, page_h - img_h]
          when :bottom       then [(page_w - img_w) / 2, 0]
          when :left         then [0, (page_h - img_h) / 2]
          when :right        then [page_w - img_w, (page_h - img_h) / 2]
          when :top_left     then [0, page_h - img_h]
          when :top_right    then [page_w - img_w, page_h - img_h]
          when :bottom_left  then [0, 0]
          when :bottom_right then [page_w - img_w, 0]
          else                    [(page_w - img_w) / 2, (page_h - img_h) / 2]
          end
  [x + offset_x, y + offset_y]
end

.call(source = nil, *stamps, filename: nil, **input_options) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/docpdf/watermarker.rb', line 31

def call(source = nil, *stamps, filename: nil, **input_options)
  pdf_bytes, resolved_filename = resolve_input(source, filename, input_options)

  if stamps.empty?
    return Result.new(data: pdf_bytes, filename: resolved_filename)
  end

  normalized = stamps.map { |s| normalize_stamp(s) }
  stamped = new(pdf_bytes, normalized).call
  Result.new(data: stamped, filename: resolved_filename)
end

Instance Method Details

#call ⇒ Object



93
94
95
96
97
98
99
100
101
# File 'lib/docpdf/watermarker.rb', line 93

def call
  stamper = StamperResolver.resolve

  if all_stamps_target_all_pages?
    stamper.stamp(@pdf_bytes, @stamps)
  else
    stamp_per_page(stamper)
  end
end