java iText paragraph

The Paragraph is a subclass of Phrase and represents the paragraph of the text. Using Paragraph class we can manage paragraph alignment, spacing etc. It is represented by com.itextpdf.text.Paragraph class.

Steps:

1. Create Document instance. It represents the current document to which we are adding content.
2. Create OutputStream instance. It represents the generated pdf.
3. Create PDFWriter instance and pass Document and OutputStream instance to its constructor.
4. Open the Document by calling document.open().
5. Add the content to the document by calling document.add() method using Paragraph objects.
6. Close the document by calling document.close() method.

Example:

PDFParagraphExample.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
 
/**
 * This class is used to create a pdf file using iText jar.
 * @author javawithease
 */
public class PDFParagraphExample {
  public static void main(String args[]){
    try {
  	//Create Document instance.
	Document document = new Document();
 
	//Create OutputStream instance.
	OutputStream outputStream = 
	    new FileOutputStream(new File("D:\\TestParagraphFile.pdf"));
 
	//Create PDFWriter instance.
        PdfWriter.getInstance(document, outputStream);
 
        //Open the document.
        document.open();
 
        //Create Paragraph objects
        Paragraph paragraph1 = new Paragraph("Test Paragraph1.");
        Paragraph paragraph2 = new Paragraph("Test Paragraph2.");
 
        //Set alignment, spacing etc on Paragraph2
        paragraph2.setSpacingAfter(35);
        paragraph2.setSpacingBefore(35);
        paragraph2.setAlignment(Element.ALIGN_CENTER);
        paragraph2.setIndentationLeft(40);
        paragraph2.setIndentationRight(40);
 
        //Add content to the document using Paragraph objects.
        document.add(paragraph1);
        document.add(paragraph2);           
 
        //Close document and outputStream.
        document.close();
        outputStream.close();
 
        System.out.println("Pdf created successfully.");
     } catch (Exception e) {
	e.printStackTrace();
     }
   }
}

Output:

Pdf created successfully.

Download this example.
 
Next Topic: Java iText anchor.
Previous Topic: Java iText phrase.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.