Search code examples
itexttext-alignment

How to align paragraph with different chunks in iText


I need help in to Justify the alignment of the below paragraph:

Font certifyFont = new Font(Font.TIMES_ROMAN, 16);
Paragraph certifyParagraph = new Paragraph();
certifyParagraph.setAlignment(Element.ALIGN_JUSTIFIED_ALL);

Chunk certifyText = new Chunk("This is to certify that  ", certifyFont);
certifyParagraph.add(certifyText);

Font nameFont = new Font(Font.TIMES_ROMAN, 16, Font.BOLD);
Chunk nameText = new Chunk("NAME ", nameFont);

Font workingFont = new Font(Font.TIMES_ROMAN, 16);
Chunk workingText = new Chunk("has been working in the company since the ", workingFont);

doc.open();
doc.add(certifyText);
doc.add(nameText);
doc.add(workingText);
doc.close();

I tried to align the paragraph to justify, center and right, but the alignment doesn’t seem to be reflected in the PDF file.


Solution

  • In your code, you are creating a Paragraph object certifyParagraph and you are defining an alignment for it, but you are never adding it to the document. Instead you are adding three different Chunk objects, named certifyText, nameText and workingText.

    I have adapted your code so that these three Chunk objects are added to the Paragraph object, and so that the Paragraph object is added to the document instead of the separate (alignment-less) chunks:

    Paragraph certifyParagraph = new Paragraph();
    certifyParagraph.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
    
    Font certifyFont = new Font(Font.TIMES_ROMAN, 16);
    Chunk certifyText = new Chunk("This is to certify that  ", certifyFont);
    certifyParagraph.add(certifyText);
    
    Font nameFont = new Font(Font.TIMES_ROMAN, 16, Font.BOLD);
    Chunk nameText = new Chunk("NAME ", nameFont);
    certifyParagraph.add(nameText);
    
    Font workingFont = new Font(Font.TIMES_ROMAN, 16);
    Chunk workingText = new Chunk(" has been working in the company since the ", workingFont);
    certifyParagraph.add(workingText);
    
    doc.open();
    doc.add(certifyParagraph);
    doc.close();