Class: PDFUtilities::PDFValidator::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/pdf_utilities/pdf_validator.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  size_limit_in_bytes: 100_000_000, # 100 MB
  check_page_dimensions: true,
  check_encryption: true,
  # Height/width limits are ignored if the check_page_dimensions option is false.
  width_limit_in_inches: 21,
  height_limit_in_inches: 21
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, options = {}) ⇒ Validator

‘file’ can be a File, Tempfile, or a String file path



58
59
60
61
# File 'lib/pdf_utilities/pdf_validator.rb', line 58

def initialize(file, options = {})
  @file = file
  @options = DEFAULT_OPTIONS.merge(options)
end

Instance Attribute Details

#pdf_metadataObject

Returns the value of attribute pdf_metadata.



55
56
57
# File 'lib/pdf_utilities/pdf_validator.rb', line 55

def 
  @pdf_metadata
end

#resultObject

Returns the value of attribute result.



55
56
57
# File 'lib/pdf_utilities/pdf_validator.rb', line 55

def result
  @result
end

Instance Method Details

#check_encryptionObject (private)



95
96
97
# File 'lib/pdf_utilities/pdf_validator.rb', line 95

def check_encryption
  @result.add_error(OWNER_PASSWORD_MSG) if @pdf_metadata.present? && @pdf_metadata.encrypted?
end

#check_file_sizeObject (private)



77
78
79
80
81
82
83
# File 'lib/pdf_utilities/pdf_validator.rb', line 77

def check_file_size
  size_limit = @options[:size_limit_in_bytes].to_i
  if File.size(@file) > size_limit
    message = "#{FILE_SIZE_LIMIT_EXCEEDED_MSG} of #{PDFUtilities.formatted_file_size(size_limit)}"
    @result.add_error(message)
  end
end

#check_page_sizeObject (private)



99
100
101
102
103
104
105
106
107
108
109
# File 'lib/pdf_utilities/pdf_validator.rb', line 99

def check_page_size
  if @pdf_metadata.present?
    dimensions = @pdf_metadata.page_size_inches
    width_limit = @options[:width_limit_in_inches]
    height_limit = @options[:height_limit_in_inches]

    if dimensions[:width] > width_limit || dimensions[:height] > height_limit
      @result.add_error("#{PAGE_SIZE_LIMIT_EXCEEDED_MSG} of #{width_limit} in. x #{height_limit} in.")
    end
  end
end

#set_pdf_metadataObject (private)



85
86
87
88
89
90
91
92
93
# File 'lib/pdf_utilities/pdf_validator.rb', line 85

def 
  @pdf_metadata = PdfInfo::Metadata.read(@file)
rescue PdfInfo::MetadataReadError => e
  if e.message.include?('Incorrect password')
    @result.add_error(USER_PASSWORD_MSG)
  else
    @result.add_error(INVALID_PDF_MSG)
  end
end

#validateObject



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/pdf_utilities/pdf_validator.rb', line 63

def validate
  @result = ValidationResult.new
  @pdf_metadata = nil

  check_file_size
  
  check_encryption if @options[:check_encryption]
  check_page_size if @options[:check_page_dimensions]

  @result
end