How do I align string print out in left, right, center alignment?

The following code snippet will teach you how to align string in left, right or center alignment when you want to print out string to a console. We will print the string using the printf(String format, Object... args) method. The format specifier / parameter defines how the string will be formatted for output and the args is the value that will be formatted.

The format parameter / specifier include flags, width, precision and conversion-characters in the order shown below. The square brackets in the notation means the part is an optional parameter.

% [flags] [width] [.precision] conversion-character
Flags Description
- left-align the output, when not specified the default is to right-align
+ print (+) or (-) sign for numeric value
0 zero padded a numeric value
, comma grouping separator for number greater that 1000
space will output a (-) symbol for negative value and a space if positive
Conversion Description
s string, use capital S to uppercase the strings
c character, use capital C to uppercase the characters
d integer: byte, short, integer, long
f floating point number: float, double
n new line

Width: Defines the field width for printing out the value of argument. It also represents the minimum number of characters to
be printed out to the output.

Precision: For floating-point conversion the precision define the number of digits of precision in a floating point value. For string value this will extract the substring.

To center the string for output we use the StringUtils.center() method from the Apache Commons Lang library. This method will center-align the string str in a larger string of size using the default space character (‘ ‘). You can supply the third parameter to define your own space character / string.

package org.kodejava.lang;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class StringAlignment {
    private static final Object[][] people = {
            {"Alice", LocalDate.of(2000, Month.JANUARY, 1)},
            {"Bob", LocalDate.of(1989, Month.DECEMBER, 15)},
            {"Carol", LocalDate.of(1992, Month.JULY, 24)},
            {"Ted", LocalDate.of(2006, Month.MARCH, 13)},
    };

    public static void main(String[] args) {
        String nameFormat = "| %1$-20s | ";
        String dateFormat = " %2$tb %2$td, %2$tY  | ";
        String ageFormat = " %3$3s |%n";
        String format = nameFormat.concat(dateFormat).concat(ageFormat);
        String line = new String(new char[48]).replace('\0', '-');

        System.out.println(line);
        System.out.printf("|%s|%s|%s|%n",
                StringUtils.center("Name", 22),
                StringUtils.center("Birth Date", 16),
                StringUtils.center("Age", 6));
        System.out.println(line);

        for (Object[] data : people) {
            System.out.printf(format,
                    data[0], data[1],
                    ChronoUnit.YEARS.between((LocalDate) data[1], LocalDate.now()));
        }

        System.out.println(line);
    }
}

Here is the output of our code snippet above:

------------------------------------------------
|         Name         |   Birth Date   | Age  |
------------------------------------------------
| Alice                |  Jan 01, 2000  |   17 |
| Bob                  |  Dec 15, 1989  |   27 |
| Carol                |  Jul 24, 1992  |   24 |
| Ted                  |  Mar 13, 2006  |   10 |
------------------------------------------------

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Maven Central

How do I set Table’s cell alignment in iText?

We can set table cell’s content alignment horizontally and vertically. To set the horizontal alignment we use the setHorizontalAlignment() method. To align it vertically we use the setVerticalAlignment() method. The alignment constant is defined in the com.itextpdf.text.Element class.

package org.kodejava.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class TableCellAlignment {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("TableCellAlignment.pdf"));
            doc.open();

            // Setting table's cells horizontal alignment
            PdfPTable table = new PdfPTable(3);
            PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1"));
            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(cell1);
            PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2"));
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell2);
            PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3"));
            cell3.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cell3);
            table.completeRow();

            // Setting table's cells vertical alignment
            PdfPCell[] cells = new PdfPCell[3];
            int[] alignments = new int[]{
                    Element.ALIGN_TOP,
                    Element.ALIGN_MIDDLE,
                    Element.ALIGN_BOTTOM
            };
            for (int i = 0; i < cells.length; i++) {
                cells[i] = new PdfPCell(new Phrase("Cell " + (i + 1)));
                cells[i].setMinimumHeight(50);
                cells[i].setVerticalAlignment(alignments[i]);
                table.addCell(cells[i]);
            }
            table.completeRow();

            doc.add(table);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

How do I set Paragraph alignment in iText?

To set the alignment of a paragraph object we can use the Paragraph.setAlignment() method. We can pass constants such as Paragraph.ALIGN_LEFT, Paragraph.ALIGN_CENTER, Paragraph.ALIGN_RIGHTto the setAlignment() method.

package org.kodejava.itextpdf;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ParagraphAlignment {
    private static final String CONTENT = """
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, \
            sed do eiusmod tempor incididunt ut labore et dolore magna \
            aliqua. Ut enim ad minim veniam, quis nostrud exercitation \
            ullamco laboris nisi ut aliquip ex ea commodo consequat. \
            Duis aute irure dolor in  reprehenderit in voluptate velit \
            esse cillum dolore eu fugiat nulla pariatur. Excepteur sint \
            occaecat cupidatat non proident, sunt in culpa qui officia \
            deserunt mollit anim id est laborum.
            """;

    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream("ParaAlign.pdf"));
            document.open();

            // Creates a check for the paragraphs contents
            Chunk chunk = new Chunk(ParagraphAlignment.CONTENT);

            // Creates paragraphs and set the alignment of the paragraph.
            // We use the Paragraph.ALIGN_LEFT, Paragraph.ALIGN_CENTER
            // and Paragraph.ALIGN_RIGHT
            Paragraph para1 = new Paragraph(chunk);
            para1.setAlignment(Paragraph.ALIGN_LEFT);
            para1.setSpacingAfter(50);
            document.add(para1);

            Paragraph para2 = new Paragraph(chunk);
            para2.setAlignment(Paragraph.ALIGN_CENTER);
            para2.setSpacingAfter(50);
            document.add(para2);

            Paragraph para3 = new Paragraph(chunk);
            para3.setAlignment(Paragraph.ALIGN_RIGHT);
            document.add(para3);

            document.close();
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central