Search code examples
itextcellbarcode

Add itextsharp barcode image to PdfPCell


I'm trying generate barcodes from a text string and then PDF the results using iTextSharp. Right now, I have the code below:

// Create a Document object
var pdfToCreate = new Document(PageSize.A4, 0, 0, 0, 0);

// Create a new PdfWrite object, writing the output to a MemoryStream
var outputStream = new MemoryStream();
var pdfWriter = PdfWriter.GetInstance(pdfToCreate, outputStream);
PdfContentByte cb = new PdfContentByte(pdfWriter);
// Open the Document for writing
pdfToCreate.Open();

PdfPTable BarCodeTable = new PdfPTable(3);
// Create barcode
Barcode128 code128          = new Barcode128();
code128.CodeType            = Barcode.CODE128_UCC;
code128.Code                = "00100370006756555316";
// Generate barcode image
iTextSharp.text.Image image128 = code128.CreateImageWithBarcode(cb, null, null);
// Add image to table cell
BarCodeTable.AddCell(image128);
// Add table to document
pdfToCreate.Add(BarCodeTable);

pdfToCreate.Close();

When I run this and try to open the PDF programmatically, I receive an error saying "The document has no pages."

However when I use:

 pdfToCreate.Add(image128);

(instead of adding to a table, I add it to a cell), the barcode shows up (though it's floating off the document).

I'd like to send the barcodes to a table so that I can format the document easier. The final product will be 20-60 barcodes read from a database. Any idea on where I'm going wrong?


Solution

  • You are telling the PdfPTable constructor to create a three column table but only providing one of the columns:

    PdfPTable BarCodeTable = new PdfPTable(3);
    

    iTextSharp by default ignores incomplete rows. You can either change the constructor to match your column count, add the extra cells or call BarCodeTable.CompleteRow() which will fill in the blanks using the default cell template.