Method: HexaPDF::CLI::Merge#execute

Defined in:
lib/hexapdf/cli/merge.rb

#executeObject

:nodoc:



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/hexapdf/cli/merge.rb', line 94

def execute #:nodoc:
  if !@initial_empty && @files.empty?
    error = OptionParser::ParseError.new("At least one FILE or --empty is needed")
    error.reason = "Missing argument"
    raise error
  elsif (@initial_empty && @files.empty?) || (!@initial_empty && @files.length < 2)
    error = OptionParser::ParseError.new("Output file is needed")
    error.reason = "Missing argument"
    raise error
  end

  output_file = @files.pop.file
  maybe_raise_on_existing_file(output_file)

  # Create PDF documents for each input file
  cache = {}
  @files.each do |spec|
    cache[spec.file] ||=
      begin
        io = if spec.file == output_file
               StringIO.new(File.binread(spec.file))
             else
               File.open(spec.file)
             end
        HexaPDF::Document.new(io: io, **pdf_options(spec.password))
      end
    spec.file = cache[spec.file]
  end

  # Assemble pages
  target = (@initial_empty ? HexaPDF::Document.new : @files.first.file)
  page_tree = target.add({Type: :Pages})
  import_pages(page_tree)
  target.catalog[:Pages] = page_tree
  remove_unused_pages(target)
  target.pages.add unless target.pages.count > 0

  apply_encryption_options(target)
  apply_optimization_options(target)

  write_document(target, output_file)
end