不幸的是,目前似乎没有合适的方法将图像裁剪为边界框。面对这个问题我想出了这个美:
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方法,但分别跳过了图像尺寸和缩放的计算。
这不是一个干净的解决方案。如果您找到更好的,请随时通知我。
您应该记住,虽然这个 sn-p 利用了一些不属于 Prawn 的公共 API 的实现细节,并且可以随时更改。
在撰写本文时,Prawn 2.0.1 是最新版本。