Class: Pdf::Utility::ImageCreator

Inherits:
Object
  • Object
show all
Defined in:
app/services/pdf/utility/image_creator.rb

Instance Method Summary collapse

Instance Method Details

#process(pdf_path:, name:, base_name: nil) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/services/pdf/utility/image_creator.rb', line 2

def process(pdf_path:, name:, base_name: nil)
  image = nil
  base_name ||= name.downcase.parameterize.tr('_', '-')
  begin
    # Sanitize PDFs that may have HTTP headers prepended (user upload issue)
    sanitize_pdf_if_needed(pdf_path)

    # Load up a VIPS image
    a = Vips::Image.new_from_file pdf_path, access: :sequential, dpi: 400
    # Write it to a jpg temp file
    file = Tempfile.new([base_name, '.jpeg'])
    file_path = file.path
    a.write_to_file(file_path)
    file&.flush
    file&.fsync
    # Now we will open the file just to make sure
    vips_image = Vips::Image.new_from_file(file_path)
    # Test that the vips_image is sound
    if vips_image.width&.positive? && vips_image.height.positive?
      new_filename = "#{base_name}-#{SecureRandom.base58(6).downcase}"
      image = Image.create!(new_filename:,
                            title: "Cover for #{name}".first(134),
                            new_image: file_path,
                            skip_notify: true,
                            tags: ['pdf-thumbnail'])
    else
      logger.error "Could not generate thumbnail for #{name} from #{pdf_path}, file is empty"
    end
  rescue StandardError => e
    ErrorReporting.error(e, { pdf_path:, name:, base_name: })
  end
  image
ensure
  file&.close
  file&.unlink
end