How to put text above a bar code instead of under the bars?

Tags: bar codetablesiText 5

I'm using iText to dynamically generate PDF docs.I'm able to introduce bar codes with text below the bars like this:

Bar code with text below the bars

I need the text to be above the bars as shown in this screen shot:

Bar code with text above the bars

How can I do this?

Question posted on StackOverflow on Jan 26, 2016 by girish

This question was first answered by Berger

The BarCode class (and BarCode128 extends BarCode), has a setBaseLine() method .

It states that providing a negative value, would place the text above the bars :

public void setBaseline(float baseline)

Sets the text baseline. If positive, the text distance under the bars. If zero or negative, the text distance above the bars.

However, this wasn't sufficient for the OP, as he commented:

I able to print the number above the barcode but I am not able to add the description "PO Line #:"

That is why Bruno Lowagie provided a more elaborate answer:

Please take a look at the BarcodeInTable example. In this example, we add a bar code in two different ways:

Two ways to add text above the bars in a bar code
Two ways to add text above the bars in a bar code

In the first way, we use the setBaseLine() method with a negative value to make sure the code is added above the bar code instead of under it:

Barcode128 code128 = new Barcode128();
Image code128Image = code128.createImageWithBarcode(cb, null, null);
PdfPCell cell = new PdfPCell(code128Image);

There are some disadvantages to this method. The first disadvantage is that you'll have to tweak some size parameters to get a good result (maybe also use the setTextAlignment() to change the default alignment). The second disadvantage is that you may want to have more freedom with respect to the text you are adding. For instance: you may want to add PO #: as is done in your example.

That's why I also provided a second way to add the text and the bar code:

code128 = new Barcode128();
code128Image = code128.createImageWithBarcode(cb, null, null);
cell = new PdfPCell();
cell.addElement(new Phrase("PO #: " + code));

In this case, we set the font to null so that no text is generated. We add the text to the cell, along with the bar code. Now we have much more freedom to format the text exactly the way we want it.

The code128Image is scaled to fit the width of the cell, but you can change this by setting the width percentage of the image, or you can change the width of the column.