2011-10-07 4 views

Répondre

6

Oui, iText et iTextSharp prennent en charge les couleurs dégradées. L'objet PdfShading possède plusieurs méthodes statiques qui créent différents types d'objets PdfShading pour vous. Les deux qui vous intéressent le plus sont SimpleAxial et SimpleRadial. Il y a trois autres noms nommés Type1, Type2 et Type3 que je n'ai pas encore explorés.

Une fois que vous avez un objet PdfShading, vous pouvez créer un PdfShadingPattern directement à partir de celui-ci et une fois que vous en avez, vous pouvez en créer un ShadingColor. ShadingColor est finalement dérivé de BaseColor donc vous devriez être capable de l'utiliser partout où c'est utilisé. Dans votre cas, vous souhaitez l'affecter à un BackgroundColor. Ci-dessous, une application WinForms complète qui cible iTextSharp 5.1.1.0 qui affiche une table avec deux colonnes, chacune avec ses propres couleurs de fond dégradées.

NOTE: Les coordonnées (x, y) des méthodes statiques PdfShading sont au niveau du document et non au niveau de la cellule. Cela signifie que vous ne pourrez peut-être pas réutiliser les objets PdfShading en fonction de la taille du dégradé. Après cet exemple ci-dessous, je vais vous montrer comment surmonter cette limitation en utilisant des événements cellulaires.

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

    } 
} 

Exemple 2

Comme il est indiqué ci-dessus, la méthode ci-dessus utilise la position au niveau du document qui est souvent pas assez bon. Pour surmonter cela, vous devez utiliser le positionnement au niveau de la cellule et, pour ce faire, vous devez utiliser des événements de cellule car les positions de cellule ne sont pas connues tant que la table n'est pas restituée. Pour utiliser un événement de cellule, vous devez créer une nouvelle classe qui implémente IPdfPCellEvent et gère la méthode CellLayout. Ci-dessous le code mis à jour qui fait tout cela:

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

Bonne réponse. La documentation de Frite itext devrait se lire comme ceci. – Paddy

+0

@ChirsAvez-vous une chance de m'aider à remplir un cercle avec un dégradé radial commençant au centre? jolie s'il-vous-plaît – Ben

3

Si quelqu'un d'autre est toujours intéressé que je cherchais à savoir comment colorer tout le fond avec un gradient vous pouvez le faire comme ça ....

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