Prawn: css like overflow: hidden for bounding boxes with images

1.4k Views Asked by At

I want to clip an image if it goes beyond the dimensions of a bounding box. Just like how CSS overflow: hidden would do it. Eg.

pdf.grid([0, 0], [3, 27]).bounding_box do
 pdf.image image_file
end

Now currently, this image would overflow outside the bounding box if its larger than it. Is there any way to clip the image when it goes beyond the bounding box. ? I know this is possible for text when using text_box.

2

There are 2 best solutions below

0
On BEST ANSWER

you can set the size of the image or get the image to scale so it fits within a certain area while maintaining proportions, do not believe you can crop an image.

If your page is not dynamic, that is the image area will always be the same this should be OK.

pdf.image "image_file_path_&_name", :position => :center, :fit => [100,450];

This is based on v0.8.4.

0
On

Unfortunately, there seems to exist no proper way to crop an image to a bounding box at the moment. Faced with this problem I figured out this beauty:

class SamplePdf

  include Prawn::View

  def initialize

    crop_width = 100 # your width here
    crop_height = 50 # your height here
    image_path = '/path/to/your_image.jpg'

    bounding_box [0, 0], width: crop_width, height: crop_height do

      pdf_obj, _ = build_image_object(image_path)

      x, y = document.send(:image_position, crop_width, crop_height, {})
      document.send(:move_text_position, crop_height)

      label = "I#{document.send(:next_image_id)}"
      document.state.page.xobjects.merge!(label => pdf_obj)

      cm_params = PDF::Core.real_params([crop_width, 0, 0, crop_height, x, y - crop_height])
      document.renderer.add_content("\nq\n#{cm_params} cm\n/#{label} Do\nQ")
    end
  end
end

It basically adapts the Prawn::Images#image method, but skips the calculation of the image's dimensions and the scaling respectively.

It's not exactly a clean solution. Please keep me posted if you find a better one.

You should keep in mind though that this snippet leverages some implementation details which are not part of Prawn's public API and can change anytime.

At the time of writing Prawn 2.0.1 was the most recent version.