Skip to content

Commit

Permalink
Allow URLs as images
Browse files Browse the repository at this point in the history
Using Prawn in an environment where assets are served
dynamically can be painful. This aims to solve it.

For instance, it is convenient to use Rails' ActionController
helper asset_path to retrieve a specific image. Trying to come
up with rules to assess the asset relative path looks brittle.
Precisely, frameworks like the Asset Pipeline solves this.
However, Prawn lacks support for these scenarios.
  • Loading branch information
bgvo committed Aug 8, 2023
1 parent 8ceaa10 commit 68d0ec3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/prawn/images.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

require 'digest/sha1'
require 'pathname'
require 'open-uri'

module Prawn
module Images
Expand Down Expand Up @@ -146,6 +147,15 @@ def verify_and_read_image(io_or_path)
io.binmode if io.respond_to?(:binmode)
return io.read
end

if io_or_path.to_s =~ URI::DEFAULT_PARSER.make_regexp
# Handle URL case
url_io = URI.parse(io_or_path.to_s).open
url_io.binmode if url_io.respond_to?(:binmode)

return url_io.read
end

# String or Pathname
io_or_path = Pathname.new(io_or_path)
raise ArgumentError, "#{io_or_path} not found" unless io_or_path.file?
Expand Down
Binary file added spec/fixtures/image_in_bytes
Binary file not shown.
13 changes: 13 additions & 0 deletions spec/prawn/images_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@
expect(info.height).to eq(453)
end

it 'accepts an image URL address' do
current_directory = File.dirname(__FILE__)
fixture_path = File.join(current_directory, '..', 'fixtures')
image_bin_data = File.open(File.join(fixture_path, 'image_in_bytes'), 'rb').read
tempfile_mock = double('Tempfile', binmode: nil, read: image_bin_data, rewind: nil)

allow(URI).to receive(:open).and_return(tempfile_mock)

info = pdf.image('https://github.com/prawnpdf/prawn/blob/master/data/images/ruport.png?raw=true')

expect(info.height).to eq(105)
end

it 'rewinds IO objects to be able to embed them multiply' do
info =
File.open(filename, 'rb') do |file|
Expand Down

0 comments on commit 68d0ec3

Please sign in to comment.