Itextsharp 渐变背景

发布于 2024-12-08 18:22:38 字数 40 浏览 0 评论 0原文

有没有办法为pdfcell或段落设置渐变背景?或者我必须使用图像?

Is there way to set gradient background to pdfcell or paragraph? Or do I have to use image?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

划一舟意中人 2024-12-15 18:22:38

是的,iText 和 iTextSharp 支持渐变颜色。 PdfShading 对象有几个静态方法,可以为您创建不同类型的 PdfShading 对象。您可能最感兴趣的两个是 SimpleAxialSimpleRadial。还有另外三个名为 Type1Type2Type3 我尚未探索。

一旦您拥有了 PdfShading 对象,您就可以直接从它创建一个 PdfShadingPattern,一旦您拥有了该对象,您就可以从它创建一个 ShadingColorShadingColor 最终派生自 BaseColor,因此您应该能够在任何使用它的地方使用它。在您的情况下,您想将其分配给 BackgroundColor

下面是一个针对 iTextSharp 5.1.1.0 的完整工作 WinForms 应用程序,它显示了创建的包含两列的表格,每列都有自己的渐变背景颜色。

注意PdfShading 静态方法的 (x,y) 坐标是文档级别的,而不是单元格级别的。这意味着您可能无法重复使用 PdfShading 对象,具体取决于渐变的大小。在下面的示例之后,我将向您展示如何使用单元事件克服此限制。

using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Test file name
            string TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");

            //Standard iTextSharp setup
            using (FileStream fs = new FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
                    {
                        //Open the document for writing
                        doc.Open();

                        //Create a shading object. The (x,y)'s appear to be document-level instead of cell-level so they need to be played with
                        PdfShading shading = PdfShading.SimpleAxial(w, 0, 700, 300, 700, BaseColor.BLUE, BaseColor.RED);

                        //Create a pattern from our shading object
                        PdfShadingPattern pattern = new PdfShadingPattern(shading);

                        //Create a color from our patter
                        ShadingColor color = new ShadingColor(pattern);

                        //Create a standard two column table
                        PdfPTable t = new PdfPTable(2);

                        //Add a text cell setting the background color through object initialization
                        t.AddCell(new PdfPCell(new Phrase("Hello")) { BackgroundColor = color });

                        //Add another cell with everything inline. Notice that the (x,y)'s have been updated
                        t.AddCell(new PdfPCell(new Phrase("World")) { BackgroundColor = new ShadingColor(new PdfShadingPattern(PdfShading.SimpleAxial(w, 400, 700, 600, 700, BaseColor.PINK, BaseColor.CYAN))) });



                        //Add the table to the document
                        doc.Add(t);

                        //Close the document
                        doc.Close();
                    }
                }
            }

            this.Close();
        }

    }
}

示例 2

如上所述,上述方法使用文档级位置,这通常不够好。为了克服这个问题,您需要使用单元格级定位,并且为此您需要使用单元格事件,因为在呈现表格本身之前单元格位置是未知的。要使用单元格事件,您需要创建一个实现 IPdfPCellEvent 的新类并处理 CellLayout 方法。下面是完成所有这些操作的更新代码:

using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Test file name
            string TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");

            //Standard iTextSharp setup
            using (FileStream fs = new FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
                    {
                        //Open the document for writing
                        doc.Open();

                        //Create a standard two column table
                        PdfPTable t = new PdfPTable(2);

                        //Create an instance of our custom cell event class, passing in our main writer which is needed by the PdfShading object
                        var CE = new GradientBackgroundEvent(w);

                        //Set the default cell's event to our handler
                        t.DefaultCell.CellEvent = CE;

                        //Add cells normally
                        t.AddCell("Hello");
                        t.AddCell("World");


                        //Add the table to the document
                        doc.Add(t);

                        //Close the document
                        doc.Close();
                    }
                }
            }

            this.Close();
        }

        public class GradientBackgroundEvent : IPdfPCellEvent
        {
            //Holds pointer to main PdfWriter object
            private PdfWriter w;

            //Constructor
            public GradientBackgroundEvent(PdfWriter w)
            {
                this.w = w;
            }

            public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
            {
                //Create a shading object with cell-specific coords
                PdfShading shading = PdfShading.SimpleAxial(w, position.Left, position.Bottom, position.Right, position.Top, BaseColor.BLUE, BaseColor.RED);

                //Create a pattern from our shading object
                PdfShadingPattern pattern = new PdfShadingPattern(shading);

                //Create a color from our patter
                ShadingColor color = new ShadingColor(pattern);

                //Get the background canvas. NOTE, If using an older version of iTextSharp (4.x) you might need to get the canvas in a different way
                PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];

                //Set the background color of the given rectable to our shading pattern
                position.BackgroundColor = color;

                //Fill the rectangle
                cb.Rectangle(position);
            }
        }
    }
}

Yes, iText and iTextSharp support gradient colors. The PdfShading object has several static methods that create different types of PdfShading objects for you. The two that you are probably most interested in are SimpleAxial and SimpleRadial. There's three others named Type1, Type2 and Type3 that I haven't explored yet.

Once you have a PdfShading object you can create a PdfShadingPattern directly from it and once you have that you can create a ShadingColor from it. ShadingColor is ultimately derived from BaseColor so you should be able to use it wherever that's used. In your case you want to assign it to a BackgroundColor.

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-use PdfShading ojbects depending on the gradient's size. After this sample below I'll show you how to overcome this limitation using cell events.

using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Test file name
            string TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");

            //Standard iTextSharp setup
            using (FileStream fs = new FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
                    {
                        //Open the document for writing
                        doc.Open();

                        //Create a shading object. The (x,y)'s appear to be document-level instead of cell-level so they need to be played with
                        PdfShading shading = PdfShading.SimpleAxial(w, 0, 700, 300, 700, BaseColor.BLUE, BaseColor.RED);

                        //Create a pattern from our shading object
                        PdfShadingPattern pattern = new PdfShadingPattern(shading);

                        //Create a color from our patter
                        ShadingColor color = new ShadingColor(pattern);

                        //Create a standard two column table
                        PdfPTable t = new PdfPTable(2);

                        //Add a text cell setting the background color through object initialization
                        t.AddCell(new PdfPCell(new Phrase("Hello")) { BackgroundColor = color });

                        //Add another cell with everything inline. Notice that the (x,y)'s have been updated
                        t.AddCell(new PdfPCell(new Phrase("World")) { BackgroundColor = new ShadingColor(new PdfShadingPattern(PdfShading.SimpleAxial(w, 400, 700, 600, 700, BaseColor.PINK, BaseColor.CYAN))) });



                        //Add the table to the document
                        doc.Add(t);

                        //Close the document
                        doc.Close();
                    }
                }
            }

            this.Close();
        }

    }
}

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 the CellLayout method. Below is updated code that does all of this:

using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Test file name
            string TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");

            //Standard iTextSharp setup
            using (FileStream fs = new FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
                    {
                        //Open the document for writing
                        doc.Open();

                        //Create a standard two column table
                        PdfPTable t = new PdfPTable(2);

                        //Create an instance of our custom cell event class, passing in our main writer which is needed by the PdfShading object
                        var CE = new GradientBackgroundEvent(w);

                        //Set the default cell's event to our handler
                        t.DefaultCell.CellEvent = CE;

                        //Add cells normally
                        t.AddCell("Hello");
                        t.AddCell("World");


                        //Add the table to the document
                        doc.Add(t);

                        //Close the document
                        doc.Close();
                    }
                }
            }

            this.Close();
        }

        public class GradientBackgroundEvent : IPdfPCellEvent
        {
            //Holds pointer to main PdfWriter object
            private PdfWriter w;

            //Constructor
            public GradientBackgroundEvent(PdfWriter w)
            {
                this.w = w;
            }

            public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
            {
                //Create a shading object with cell-specific coords
                PdfShading shading = PdfShading.SimpleAxial(w, position.Left, position.Bottom, position.Right, position.Top, BaseColor.BLUE, BaseColor.RED);

                //Create a pattern from our shading object
                PdfShadingPattern pattern = new PdfShadingPattern(shading);

                //Create a color from our patter
                ShadingColor color = new ShadingColor(pattern);

                //Get the background canvas. NOTE, If using an older version of iTextSharp (4.x) you might need to get the canvas in a different way
                PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];

                //Set the background color of the given rectable to our shading pattern
                position.BackgroundColor = color;

                //Fill the rectangle
                cb.Rectangle(position);
            }
        }
    }
}
╰沐子 2024-12-15 18:22:38

如果还有人感兴趣
我一直在寻找如何用渐变为整个背景着色
你可以这样做......

    PdfShading shading = PdfShading.simpleAxial(writer, 0, pageH, pageW, 0,
            BaseColor.WHITE, BaseColor.LIGHT_GRAY);
    PdfShadingPattern pattern = new PdfShadingPattern(shading);
    cb.setShadingFill(pattern);
    // cb.circle(500, 500, 500);
    cb.rectangle(0, 0, pageW, pageH);
    cb.fill();

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....

    PdfShading shading = PdfShading.simpleAxial(writer, 0, pageH, pageW, 0,
            BaseColor.WHITE, BaseColor.LIGHT_GRAY);
    PdfShadingPattern pattern = new PdfShadingPattern(shading);
    cb.setShadingFill(pattern);
    // cb.circle(500, 500, 500);
    cb.rectangle(0, 0, pageW, pageH);
    cb.fill();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文