Class: HexaPDF::CLI::Files

Inherits:
Command
  • Object
show all
Defined in:
lib/hexapdf/cli/files.rb

Overview

Lists or extracts embedded files from a PDF file or attaches them.

See: HexaPDF::Type::EmbeddedFile

Instance Method Summary collapse

Methods included from Command::Extensions

#help, #help_banner

Constructor Details

#initializeFiles

:nodoc:



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
# File 'lib/hexapdf/cli/files.rb', line 47

def initialize #:nodoc:
  super('files', takes_commands: false)
  short_desc("List and extract embedded files from a PDF or attach files")
  long_desc(<<~EOF)
    If neither the option --attach nor the option --extract is given, the available
    files are listed with their names and indices. The --extract option can then be
    used to extract one or more files. Or the --attach option can be used to attach
    files to the PDF.
  EOF

  options.on("--attach FILE", "-a FILE", String,
             "The file that should be attached. Can be used multiple times.") do |file|
    @attach_files << [file, nil]
  end
  options.on("--description DESC", "-d DESC", String,
             "Adds a description to the last file to be attached.") do |description|
    @attach_files[-1][1] = description
  end
  options.on("--extract [a,b,c,...]", "-e [a,b,c,...]", Array,
             "The indices of the files that should be extracted. Use 0 or no argument to " \
             "extract all files.") do |indices|
    @indices = (indices ? indices.map(&:to_i) : [0])
  end
  options.on("--[no-]search", "-s", "Search the whole PDF instead of the " \
             "standard locations (default: false)") do |search|
    @search = search
  end
  options.on("--password PASSWORD", "-p", String,
             "The password for decryption. Use - for reading from standard input.") do |pwd|
    @password = (pwd == '-' ? read_password : pwd)
  end

  @attach_files = []
  @indices = []
  @password = nil
  @search = false
end

Instance Method Details

#execute(pdf, output = nil) ⇒ Object

:nodoc:



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/hexapdf/cli/files.rb', line 85

def execute(pdf, output = nil) #:nodoc:
  if @indices.empty? && !@attach_files.empty?
    raise Error, "Missing output file" unless output
    maybe_raise_on_existing_file(output)
  end
  with_document(pdf, password: @password, out_file: output) do |doc|
    if @indices.empty? && @attach_files.empty?
      list_files(doc)
    elsif !@indices.empty? && !@attach_files.empty?
      raise Error, "Use either --attach or --extract but not both"
    elsif !@attach_files.empty?
      attach_files(doc)
    else
      extract_files(doc)
    end
  end
end