正如 Bruno 在评论中已经提到的,您必须使用单元格事件来执行自定义缩放和剪辑任务。
即单元格最初是在没有图像的情况下“布局”的,完成后,将使用单元格的位置和尺寸以及表格画布触发单元格事件。现在您可以随心所欲地绘制图像,缩放(或旋转,或倾斜,...)和任意剪裁。
这当然意味着您必须确保表格单元格不会折叠(毕竟在“布局”期间它是空的),例如通过设置 FixedHeight 或通过相邻单元格强制执行所需的高度。
例如,如果您拍摄这张图片:
并且想要将它放入一个宽度是它的高度的四倍的单元格中,在一个全宽的单列表中,应用您描述的缩放和剪辑,您可以这样做(假设 @ 987654326@ 是您的Document 实例):
Image itextImage = RETRIEVE YOUR IMAGE AS ITEXTSHARP IMAGE;
PdfPCell cell = new PdfPCell()
{
FixedHeight = (document.PageSize.Width - document.LeftMargin - document.RightMargin) / 4,
CellEvent = new ImageEvent(itextImage)
};
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
table.AddCell("Above the image");
table.AddCell(cell);
table.AddCell("Below the image");
document.Add(table);
使用单元格事件助手类
class ImageEvent : IPdfPCellEvent
{
Image image;
public ImageEvent(Image image)
{
this.image = image;
}
public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
{
PdfContentByte canvas = canvases[0];
float scaleX = position.Width / image.Width;
float scaleY = position.Height / image.Height;
float scale = Math.Max(scaleX, scaleY);
image.ScaleToFit(image.Width * scale, image.Height * scale);
image.SetAbsolutePosition((position.Left + position.Right - image.ScaledWidth) / 2, (position.Bottom + position.Top - image.ScaledHeight) / 2);
canvas.SaveState();
canvas.Rectangle(position.Left, position.Bottom, position.Width, position.Height);
canvas.Clip();
canvas.NewPath();
canvas.AddImage(image);
canvas.RestoreState();
}
}
(如您所见,scale 因子被选为您所需布局的 scaleX 和 scaleY 的最大值。如果您选择最小值,则结果将是 ScaleToFit 版本你原来的例子。或者如果你选择一个比最大值高一点的值,你会放大到图像的中心。)
结果如下: