2010-04-20 30 views

Respuesta

7

No agregaría realmente un 'campo de texto' a un PdfPCell, crearía un PdfPCell y agregaría texto (u otras cosas) a eso.

mikesdotnetting.com podría tener el clearest example y siempre está el iTextSharp tutorial.

+0

Conozco este enlace, pero ¿está seguro de que no puedo agregar un TextField en PdfPCell? Estoy mirando este enlace http://old.nabble.com/PdfPTable-TextField-in-PdfPCell:-questions-td17984107.html, pero no entiendo si debo hacer. Necesito agregar un TextField en PdfPCell, porque después de la creación del pdf necesito insertar una información en este campo. – gigiot

7

Dale una oportunidad. Esto funciona para mi.

Document doc = new Document(PageSize.LETTER, 18f, 18f, 18f, 18f); 
MemoryStream ms = new MemoryStream(); 
PdfWriter writer = PdfWriter.GetInstance(doc, ms); 
doc.Open(); 

// Create your PDFPTable here.... 

TextField tf = new TextField(writer, new iTextSharp.text.Rectangle(67, 585, 140, 800), "cellTextBox"); 
PdfPCell tbCell = new PdfPCell(); 
iTextSharp.text.pdf.events.FieldPositioningEvents events = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, tf.GetTextField()); 
tbCell.CellEvent = events; 

myTable.AddCell(tbCell); 

// More code... 

adapté el código de this post.

Editar:

Aquí es una aplicación de consola de trabajo completo que pone un cuadro de texto en una celda de la tabla. Traté de mantener el código al mínimo.

using System; 
using System.IO; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

namespace iTextSharpTextBoxInTableCell 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Create a PDF with a TextBox in a table cell 
      BaseFont bfHelvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false); 
      Font helvetica12 = new Font(bfHelvetica, 12, Font.NORMAL, Color.BLACK); 

      Document doc = new Document(PageSize.LETTER, 18f, 18f, 18f, 18f); 
      FileStream fs = new FileStream("TextBoxInTableCell.pdf", FileMode.Create); 
      PdfWriter writer = PdfWriter.GetInstance(doc, fs); 

      doc.Open(); 
      PdfPTable myTable = new PdfPTable(1); 
      myTable.TotalWidth = 568f; 
      myTable.LockedWidth = true; 
      myTable.HorizontalAlignment = 0; 

      TextField tf = new TextField(writer, new iTextSharp.text.Rectangle(67, 585, 140, 800), "cellTextBox"); 
      PdfPCell tbCell = new PdfPCell(new Phrase(" ", helvetica12)); 
      iTextSharp.text.pdf.events.FieldPositioningEvents events = 
       new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, tf.GetTextField()); 
      tbCell.CellEvent = events; 

      myTable.AddCell(tbCell); 

      doc.Add(myTable); 

      doc.Close(); 

      fs.Close(); 

      Console.WriteLine("End Of Program Execution"); 
      Console.ReadLine(); 
     } 
    } 
} 

Bon oportunidad

+0

Nada ... después de esta construcción myTable.AddCell (tbCell); comprobé con la depuración mi objeto tbCell, pero veo que el tamaño del rectángulo es 0x0 .. ¿es normal? – gigiot

+0

He actualizado mi respuesta. – DaveB

+0

Gracias Dave, ¡¡¡me has enamorado !!! Probé tu código y funciona perfectamente. Ahora intento fusionar 3 archivos PDF, pero después de fusionar todos los TextField desaparecen ... ¿hay una propiedad del documento que debo planear para evitar esto? – gigiot

2

obras respuesta de DaveB, pero el problema es que usted tiene que saber las coordenadas para colocar en el campo de texto, el (67, 585, 140, 800). El método más normal de hacer esto es crear la celda de la tabla y agregar un evento personalizado a la celda. Cuando la generación de la tabla llama al evento celllayout, le pasa las dimensiones y coordenadas de la celda que puede usar para colocar y dimensionar el campo de texto.

En primer lugar crear esta llamada, que es el evento personalizado

public class CustomCellLayout : IPdfPCellEvent 
{ 
    private string fieldname; 

    public CustomCellLayout(string name) 
    { 
     fieldname = name; 
    } 

    public void CellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases) 
    { 
     PdfWriter writer = canvases[0].PdfWriter; 

     // rectangle holds the dimensions and coordinates of the cell that was created 
     // which you can then use to place the textfield in the correct location 
     // and optionally fit the textfield to the size of the cell 


     float textboxheight = 12f; 
     // modify the rectangle so the textfield isn't the full height of the cell 
     // in case the cell ends up being tall due to the table layout 
     Rectangle rect = rectangle; 
     rect.Bottom = rect.Top - textboxheight; 

     TextField text = new TextField(writer, rect, fieldname); 
     // set and options, font etc here 

     PdfFormField field = text.GetTextField(); 

     writer.AddAnnotation(field); 
    } 
} 

Luego, en el código donde se crea la tabla que va a utilizar el evento como este:

PdfPCell cell = new PdfPCell() 
    { 
     CellEvent = new CustomCellLayout(fieldname) 
     // set borders, or other cell options here 
    }; 

Si desea diferentes tipos de campos de texto puede hacer eventos personalizados adicionales, o puede agregar propiedades adicionales a la clase CustomCellLayout como "fontsize" o "multiline" que establecería con el constructor de la clase, y luego buscar en el código de CellLayout para ajustar las propiedades del campo de texto.

+0

¡Oh, sí! Esto es genialidad personificada, err ... codificada. –

+0

¿Qué sucede si quiere crear casillas de verificación? ¿Cómo debe modificarse el código anterior para ese evento (sin juego de palabras)? –

+1

@ B.ClayShannon agregaría un RadioCheckField en lugar de un TextField.El rectángulo que se pasa al constructor de RadioCheckField se debe hacer usando el rectángulo pasado al CellLayout ajustado con el desplazamiento y las dimensiones de la casilla de verificación que desee. –

Cuestiones relacionadas