Grim Ruby Gem

repository·master·Indexed 42 days ago

https://github.com/jonmagic/grim

A Ruby gem that acts as a high-level wrapper around GhostScript, ImageMagick, and xpdf to 'reap' PDF files. It allows developers to extract specific pages as images or extract page text as strings using the Grim.reap(path) entry point.

Tokens
3.2K
Snippets
19
Records
21
Agent score
53%

What's inside Grim

  1. Extract pages and text from a PDF

    master

    Use Grim.reap(path) to create a Grim::Pdf instance. From there, you can access individual pages, count pages, extract text, or save pages as images.

    Note: Page indexing is 0-based (e.g., pdf[0] is the first page).

    pdf   = Grim.reap("/path/to/pdf")         # returns Grim::Pdf instance
    count = pdf.count                         # returns number of pages
    png   = pdf[3].save('/path/to/image.png') # returns true if saved, false otherwise
    text  = pdf[3].text                       # returns text as a String
    
    # Iterate through all pages
    pdf.each do |page|
      puts page.text
    end
  2. Install Grim

    master

    Grim requires ghostscript, imagemagick, and xpdf to be installed on your system. On macOS, you can install these using Homebrew:

    brew install ghostscript imagemagick xpdf

    Once the system dependencies are met, install the gem via:

    gem install grim
    gem install grim
  3. Configure image save options

    master

    When calling Grim::ImageMagickProcessor#save, you can pass an options hash to customize the output image.

    Available options:

    • :width (Integer, default: 1024)
    • :density (Integer, default: 300)
    • :quality (Integer, default: 90)
    • :colorspace (String, default: "RGB")
    • :alpha (String, e.g., "Activate" - not used when not set)
    pdf = Grim.reap("/path/to/pdf")
    pdf[0].save('/path/to/image.png', {
      :width => 600,
      :density => 72,
      :quality => 60,
      :colorspace => "CMYK",
      :alpha => "Activate"
    })
  4. Configure Grim logging

    master

    Grim uses Grim::NullLogger by default. To see debug information (like the actual ImageMagick commands being executed), you can assign a standard Ruby Logger to Grim.logger.

    require "logger"
    Grim.logger = Logger.new($stdout).tap { |logger| logger.progname = 'Grim' }
  5. Use multiple processors with fallback

    master

    If you need to support multiple versions of convert or gs, you can use Grim::MultiProcessor. It will attempt to use the processors in the order provided and fall back to the next one if the previous one fails.

    Grim.processor = Grim::MultiProcessor.new([
      Grim::ImageMagickProcessor.new({:imagemagick_path => "/path/to/6.7/convert", :ghostscript_path => "/path/to/9.04/gs"}),
      Grim::ImageMagickProcessor.new({:imagemagick_path => "/path/to/6.6/convert", :ghostscript_path => "/path/to/9.02/gs"})
    ])
  6. Configure custom ImageMagick and GhostScript paths

    master

    By default, Grim uses the versions of ImageMagick and GhostScript found in your system PATH. You can override this by assigning a new Grim::ImageMagickProcessor to Grim.processor.

    Grim.processor = Grim::ImageMagickProcessor.new({
      :imagemagick_path => "/path/to/convert", 
      :ghostscript_path => "/path/to/gs"
    })
  7. Configure the pdftotext binary path

    master

    When initializing a Grim::Page (typically via a parent Grim::PDF object), you can specify the location of the pdftotext executable using the :pdftotext_path option. This is useful if the binary is not in your system's PATH.

    Default value: 'pdftotext'.

    # Example configuration passed during PDF/Page initialization
    options = { pdftotext_path: '/usr/local/bin/pdftotext' }
    # Note: This option is typically passed to the parent PDF object which then propagates it to Page instances
  8. Extract text from a PDF page with Page#text

    master

    The text method extracts text content from a specific PDF page using the pdftotext binary.

    You can pass an optional hash of options to include specific command-line flags for the pdftotext utility. The most common option is :flags, which accepts an array of strings.

    Returns a String containing the extracted text.

    # Basic text extraction
    pdf[1].text
    
    # Extraction with specific pdftotext flags (e.g., for tables)
    pdf[1].text({flags: ["-table"]})
  9. Configure ImageMagick and GhostScript paths in ImageMagickProcessor

    master

    When initializing Grim::ImageMagickProcessor, you can provide custom paths for the convert (ImageMagick) and gs (GhostScript) executables via an options hash. This is useful if these tools are not in your system PATH or if you need to use specific versions.

    If a custom @ghostscript_path is provided, the processor will automatically prepend the directory containing that executable to the PATH environment variable during the save operation to ensure GhostScript dependencies are resolvable.

    processor = Grim::ImageMagickProcessor.new(
      imagemagick_path: '/usr/local/bin/convert',
      ghostscript_path: '/opt/homebrew/bin/gs'
    )
  10. Save a PDF page as an image with Page#save

    master

    The save method extracts a specific PDF page and converts it into an image file. It is tested with png and jpeg formats.

    To use it, provide the destination file path and an optional hash of options to customize the image output (such as width, density, or quality).

    Returns a File object on success.

    # Example: Saving the second page of a PDF to a PNG file
    pdf[1].save('/path/to/save/image.png')
  11. Initialize a Grim::Pdf instance

    master

    To work with a PDF document, instantiate Grim::Pdf with the file path. If the file does not exist at the provided path, it will raise a Grim::PdfNotFound error. You can optionally provide an options hash to configure the text extraction binary.

    Options:

    • :pdftotext_path (String): The path to the pdftotext binary used for text extraction. Defaults to 'pdftotext'.
    # Basic initialization
    pdf = Grim::Pdf.new('/path/to/document.pdf')
    
    # Initialization with custom pdftotext path
    pdf = Grim::Pdf.new('/path/to/document.pdf', pdftotext_path: '/usr/local/bin/pdftotext')
  12. Configure the Grim logger

    master

    Grim allows you to set a custom logger to capture internal library logs. The object passed must follow the standard Ruby Logger interface. If no logger is set, it defaults to Grim::NullLogger.

    require 'logger'
    
    # Set a standard Ruby logger
    Grim.logger = Logger.new(STDOUT)