Itextsharp渐变背景

时间:2011-10-07 06:58:33

标签: c# .net pdf itextsharp

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

2 个答案:

答案 0 :(得分:6)

是的,iText和iTextSharp支持渐变色。 PdfShading对象有几个静态方法,可以为您创建不同类型的PdfShading对象。您可能最感兴趣的两个是SimpleAxialSimpleRadial。我还没有探讨过其他三个名为Type1Type2Type3的内容。

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

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

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

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);
            }
        }
    }
}

答案 1 :(得分:3)

如果其他人仍然感兴趣 我正在寻找如何使用渐变为整个背景着色 你可以这样做....

    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();