Class: SwarmSDK::Tools::DocumentConverters::PdfConverter

Inherits:
BaseConverter
  • Object
show all
Defined in:
lib/swarm_sdk/tools/document_converters/pdf_converter.rb

Overview

Converts PDF documents to text with image extraction

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseConverter

available?, gem_available?

Class Method Details

.extensionsObject



17
18
19
# File 'lib/swarm_sdk/tools/document_converters/pdf_converter.rb', line 17

def extensions
  [".pdf"]
end

.format_nameObject



13
14
15
# File 'lib/swarm_sdk/tools/document_converters/pdf_converter.rb', line 13

def format_name
  "PDF"
end

.gem_nameObject



9
10
11
# File 'lib/swarm_sdk/tools/document_converters/pdf_converter.rb', line 9

def gem_name
  "pdf-reader"
end

Instance Method Details

#convert(file_path) ⇒ String, RubyLLM::Content

Convert a PDF document to text/content

Parameters:

  • file_path (String)

    Path to the PDF file

Returns:

  • (String, RubyLLM::Content)

    Converted content or error message



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
# File 'lib/swarm_sdk/tools/document_converters/pdf_converter.rb', line 25

def convert(file_path)
  unless self.class.available?
    return unsupported_format_reminder(self.class.format_name, self.class.gem_name)
  end

  begin
    require "pdf-reader"
    require "tmpdir"
    require "fileutils"

    reader = PDF::Reader.new(file_path)
    output = []
    output << "PDF Document: #{File.basename(file_path)}"
    output << "=" * 60
    output << "Pages: #{reader.page_count}"
    output << ""

    # Extract images from the PDF
    image_paths = ImageExtractors::PdfImageExtractor.extract_images(reader, file_path)

    # Extract text from each page
    reader.pages.each_with_index do |page, index|
      output << "Page #{index + 1}:"
      output << "-" * 60
      text = page.text.strip
      output << (text.empty? ? "(No text content on this page)" : text)
      output << ""
    end

    text_content = output.join("\n")

    # If there are images, return Content with attachments
    if image_paths.any?
      content = RubyLLM::Content.new(text_content)
      image_paths.each do |image_path|
        content.add_attachment(image_path)
      end
      content
    else
      # No images, return just text
      text_content
    end
  rescue PDF::Reader::MalformedPDFError => e
    error("PDF file is malformed: #{e.message}")
  rescue PDF::Reader::UnsupportedFeatureError => e
    error("PDF contains unsupported features: #{e.message}")
  rescue StandardError => e
    error("Failed to parse PDF file: #{e.message}")
  end
end