Class: HexaPDF::CLI::Watermark
- Defined in:
- lib/hexapdf/cli/watermark.rb
Overview
Uses one or more pages of one PDF and underlays/overlays it/them onto another.
Instance Method Summary collapse
-
#execute(in_file, out_file) ⇒ Object
:nodoc:.
-
#initialize ⇒ Watermark
constructor
:nodoc:.
Methods included from Command::Extensions
Constructor Details
#initialize ⇒ Watermark
:nodoc:
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/hexapdf/cli/watermark.rb', line 45 def initialize #:nodoc: super('watermark', takes_commands: false) short_desc("Put one or more PDF pages onto another PDF") long_desc(<<~EOF) This command uses one ore more pages from a PDF file and applies them as background or stamp on another PDF file. If multiple pages are selected from the watermark PDF, the --repeat option can be used to specify how they should be applied: 'last' (the default) will only repeat the last watermark page whereas 'all' will cyclically repeat all watermark pages. EOF .on("-w", "--watermark-file FILE", "The PDF used as watermark") do |watermark_file| @watermark_file = watermark_file end .on("-i", "--pages PAGES", "The pages of the watermark file that should be used " \ "(default: 1)") do |pages| @pages = pages end .on("-r", "--repeat REPEAT_MODE", [:last, :all], "Specifies how the watermark pages should be repeated. Either last or " \ "all (default: last)") do |repeat| @repeat = repeat end .on("-t", "--type WATERMARK_TYPE", [:background, :stamp], "Specifies how the watermark is applied: background applies it below the page " \ "contents and stamp applies it above. Default: background") do |type| @type = (type == :background ? :underlay : :overlay) end .on("--password PASSWORD", "-p", String, "The password for decrypting the input PDF. Use - for reading from " \ "standard input.") do |pwd| @password = (pwd == '-' ? read_password : pwd) end @watermark_file = nil @pages = "1" @repeat = :last @type = :underlay @password = nil end |
Instance Method Details
#execute(in_file, out_file) ⇒ Object
:nodoc:
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
# File 'lib/hexapdf/cli/watermark.rb', line 89 def execute(in_file, out_file) #:nodoc: maybe_raise_on_existing_file(out_file) watermark = HexaPDF::Document.open(@watermark_file) indices = page_index_generator(watermark) xobject_map = {} with_document(in_file, password: @password, out_file: out_file) do |doc| doc.pages.each do |page| index = indices.next xobject = xobject_map[index] ||= doc.import(watermark.pages[index].to_form_xobject) pw = page.box.width.to_f ph = page.box.height.to_f xw = xobject.width.to_f xh = xobject.height.to_f canvas = page.canvas(type: @type) ratio = [pw / xw, ph / xh].min xw, xh = xw * ratio, xh * ratio x, y = (pw - xw) / 2, (ph - xh) / 2 canvas.xobject(xobject, at: [x, y], width: xw, height: xh) end end end |