残念ながら、現時点では画像をバウンディング ボックスにトリミングする適切な方法はないようです。この問題に直面して、私はこの美しさを理解しました:
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
それは基本的にPrawn::Images#image
方法を適応させますが、画像の寸法とスケーリングの計算をそれぞれスキップします。
それは正確にはきれいな解決策ではありません。より良いものを見つけたら、私に知らせてください。
ただし、このスニペットは、Prawn のパブリック API の一部ではなく、いつでも変更できるいくつかの実装の詳細を利用していることに注意してください。
執筆時点では、Prawn 2.0.1 が最新バージョンでした。