Class: Pdfh::Services::PdfTextExtractor

Inherits:
Object
  • Object
show all
Defined in:
lib/pdfh/services/pdf_text_extractor.rb

Overview

Extracts text from a PDF using pdftotext command

Class Method Summary collapse

Class Method Details

.call(pdf_path) ⇒ String

Parameters:

  • pdf_path (String)

Returns:

  • (String)

Raises:

  • (ArgumentError)

    if file doesn't exist or is not a PDF

  • (RuntimeError)

    if extraction fails



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/pdfh/services/pdf_text_extractor.rb', line 14

def self.call(pdf_path)
  validate_file!(pdf_path)

  # Use Shellwords to properly escape the path for shell execution
  safe_path = Shellwords.escape(pdf_path)
  cmd = "pdftotext -enc UTF-8 -layout #{safe_path} - 2>/dev/null"

  text = `#{cmd}`
  exit_status = $CHILD_STATUS

  # Check if command executed successfully
  if exit_status.nil? || !exit_status.success?
    Pdfh.logger.debug "Failed to extract text from: #{pdf_path}"
    return ""
  end

  text
end

.validate_file!(pdf_path) ⇒ void

This method returns an undefined value.

Parameters:

  • pdf_path (String)

Raises:

  • (ArgumentError)

    if validation fails



36
37
38
39
40
41
42
# File 'lib/pdfh/services/pdf_text_extractor.rb', line 36

def self.validate_file!(pdf_path)
  raise ArgumentError, "PDF path cannot be nil" if pdf_path.nil?
  raise ArgumentError, "PDF path cannot be empty" if pdf_path.empty?
  raise ArgumentError, "File does not exist: #{pdf_path}" unless File.exist?(pdf_path)
  raise ArgumentError, "Not a file: #{pdf_path}" unless File.file?(pdf_path)
  raise ArgumentError, "Not a PDF file: #{pdf_path}" unless File.extname(pdf_path).casecmp?(".pdf")
end