The Paragraph
class in iText 8 is a fundamental building block in the creation of a PDF document. It is used to add and format texts in your document.
Here’s a simple code snippet that demonstrates how to use Paragraph
:
package org.kodejava.itext;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
public class ParagraphExample {
public static void main(String[] args) throws Exception {
PdfWriter writer = new PdfWriter("paragraph.pdf");
PdfDocument pdf = new PdfDocument(writer);
try (Document document = new Document(pdf)) {
Paragraph paragraph = new Paragraph("Hello, World!");
document.add(paragraph);
}
}
}
In this example, a new Paragraph
object is created with the text “Hello, World!” which is then added to the Document
.
The Paragraph
class also provides numerous methods to fine-tune the appearance of the text:
package org.kodejava.itext;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
public class ParagraphSettingExample {
public static void main(String[] args) throws Exception {
PdfWriter writer = new PdfWriter("paragraph-setting.pdf");
PdfDocument pdf = new PdfDocument(writer);
try (Document document = new Document(pdf)) {
Paragraph paragraph = new Paragraph("Hello, World!")
.setFont(PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN))
.setFontSize(12)
.setBold()
.setItalic()
.setTextAlignment(TextAlignment.JUSTIFIED);
document.add(paragraph);
}
}
}
In this snippet:
setFont()
is used to set the desired font.setFontSize()
adjusts the text size.setBold()
andsetItalic()
can be called to apply bold and italics styles to the text.setTextAlignment()
can be used to align text left, right, centered, or justified.
It’s worth highlighting that the Paragraph
also supports adding chunks, images, lists, and even other paragraphs, offering a wide variety of ways to customize the content and layout of your PDF documents.
Maven Dependencies
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>8.0.4</version>
<type>pom</type>
</dependency>