2017-07-25 127 views
0

我试图将图像放在使用ItextSharp的PdfPCell中。我想将图像放置在垂直/水平中心,并且图像适合中心裁剪(以隐藏图像的其余部分),我发现的唯一方法是ScaleAbsolute,它使图像变形,看起来很糟糕,另一种是ScaleToFit它不填补单元格的所有空间。有没有办法在单元格中显示图像(如overflor:hidden html)enter image description here在PdfPCell中心放置图像,并溢出到单元格iTextSharp

@mkl你好。我尝试你的解决方案,并且...... WOWW看起来像是以正确的方式工作。唯一的一点是,代码与肖像图像很好地工作,并与风景图像差不多。我能做些什么来解决这个问题? (其只与方形区域景观形象出现,代码上或高度方面

enter image description here

+1

使用电池事件添加图像。 –

+0

@Elidotnet您可以使用Bruno的提示来实施解决方案吗?还是需要帮助? – mkl

+0

@mkl仍然需要帮助 – Elidotnet

回答

1

布鲁诺在评论已经提到伟大的工作,你必须使用电池事件自定义缩放和裁剪工作。

也就是说,单元格最初是没有图像的“布局”,当单元格完成后,单元格事件触发单元格和表格的位置和尺寸。现在,您可以绘制图像,缩放(或旋转,或倾斜,...)并任意裁剪。

这当然确实意味着您必须确保表格单元格不会折叠(毕竟在“布局”期间它是空的),例如,通过设置FixedHeight或者通过相邻单元强制实现期望的高度。


例如,如果你把这个图片:

Willi, a CKCS

,并希望把它变成一个细胞是一样宽,它是高的,在全宽度的四倍,单列表,应用缩放和剪裁你所描述的,你可以这样做(假设document是你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因子选定为所需布局的最大的scaleXscaleY。如果您选择最小值,结果将是您的原始示例的ScaleToFit版本。或者,如果你选择的值高于最大一点,你甚至更多的放大到您的图像的中心)

,结果是这样的:

Screenshot of the table

+0

我上传了一些图片和代码到您的解决方案(抱歉张贴我的图片作为答案,我不知道如何评论使用图像和代码) – Elidotnet

+0

*抱歉发布我的图像作为答案,我不知道如何评论使用图像和代码* - 你应该编辑你的问题来添加额外的信息。 – mkl

+0

非常感谢您的解决方案。你有一些想法如何完成这个问题?当在横向模式下的图像需要一点帮助的方形区域 – Elidotnet