Itextsharp 渐变背景
有没有办法为pdfcell或段落设置渐变背景?或者我必须使用图像?
Is there way to set gradient background to pdfcell or paragraph? Or do I have to use image?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,iText 和 iTextSharp 支持渐变颜色。
PdfShading
对象有几个静态方法,可以为您创建不同类型的PdfShading
对象。您可能最感兴趣的两个是SimpleAxial
和SimpleRadial
。还有另外三个名为Type1
、Type2
和Type3
我尚未探索。一旦您拥有了
PdfShading
对象,您就可以直接从它创建一个PdfShadingPattern
,一旦您拥有了该对象,您就可以从它创建一个ShadingColor
。ShadingColor
最终派生自BaseColor
,因此您应该能够在任何使用它的地方使用它。在您的情况下,您想将其分配给BackgroundColor
。下面是一个针对 iTextSharp 5.1.1.0 的完整工作 WinForms 应用程序,它显示了创建的包含两列的表格,每列都有自己的渐变背景颜色。
注意:
PdfShading
静态方法的 (x,y) 坐标是文档级别的,而不是单元格级别的。这意味着您可能无法重复使用PdfShading
对象,具体取决于渐变的大小。在下面的示例之后,我将向您展示如何使用单元事件克服此限制。示例 2
如上所述,上述方法使用文档级位置,这通常不够好。为了克服这个问题,您需要使用单元格级定位,并且为此您需要使用单元格事件,因为在呈现表格本身之前单元格位置是未知的。要使用单元格事件,您需要创建一个实现
IPdfPCellEvent
的新类并处理CellLayout
方法。下面是完成所有这些操作的更新代码:Yes, iText and iTextSharp support gradient colors. The
PdfShading
object has several static methods that create different types ofPdfShading
objects for you. The two that you are probably most interested in areSimpleAxial
andSimpleRadial
. There's three others namedType1
,Type2
andType3
that I haven't explored yet.Once you have a
PdfShading
object you can create aPdfShadingPattern
directly from it and once you have that you can create aShadingColor
from it.ShadingColor
is ultimately derived fromBaseColor
so you should be able to use it wherever that's used. In your case you want to assign it to aBackgroundColor
.Below is a complete working WinForms app targeting iTextSharp 5.1.1.0 that shows created a table with two columns, each with their own gradient background colors.
NOTE: The (x,y) coordinates of the
PdfShading
static methods are document-level and not cell-level. What this means is that you might not be able to re-usePdfShading
ojbects depending on the gradient's size. After this sample below I'll show you how to overcome this limitation using cell events.Example 2
As noted above, the method above uses document-level position which often isn't good enough. To overcome this you need to use cell-level positioning and to do that you need to use cell events because cell positions aren't known until the table itself is rendered. To use a cell event you need to create a new class that implements
IPdfPCellEvent
and handle theCellLayout
method. Below is updated code that does all of this:如果还有人感兴趣
我一直在寻找如何用渐变为整个背景着色
你可以这样做......
If anyone else is still interested
I was looking to find out how to color the whole background with a gradient
you can do it like this....