Adding more text to a cell in table in itext

2019-01-29 00:11发布

问题:

I am trying to add some text with a bar code in a table cell using itext as per the following code but it does not show in the pdf file. i tried adding chunks and paragraph. Any help on this would be appreciated.

Barcode128 barcode = new Barcode128();
//barcode.setCodeType(Barcode.EAN8);
barcode.setCode(code);
PdfPCell cell = new PdfPCell(barcode.createImageWithBarcode(writer.getDirectContent(), BaseColor.BLACK, BaseColor.GRAY), true);

Paragraph paragraph = new Paragraph("Hello World"); 
cell.addElement(paragraph);

cell.setPadding(10);

回答1:

You are probably confused by text vs. composite mode.

When using the PdfPCell(Image) constructor, you create a cell in text mode. Any subsequent call to addElement(Element) will then switch the cell to composite mode, removing all content previously entered in the constructor.

You'll have to change your code that way:

PdfPCell cell = new PdfPCell();

Barcode128 barcode = new Barcode128();
barcode.setCode(code);
Image barcodeImage = barcode.createImageWithBarcode(writer.getDirectContent(), BaseColor.BLACK, BaseColor.GRAY);
cell.addElement(barcodeImage);

Paragraph paragraph = new Paragraph("Hello World"); 
cell.addElement(paragraph);