Formatting the Text in a PDF using Java
Last Updated :
02 Mar, 2023
We can add nested tables to a PDF by installing the document class. Following are the steps to format the text in a PDF using java.
1. Create a PDF writer object
The PdfWriter class here represents the DocWriter for a PDF. This class belongs to the package com.itextpdf.kernel.pdf. The constructor of this class accepts a string, representing the trail of the file where the PDF is to be created.
Create the PdfWriter class by passing a string value (representing the trail where you would like to make a PDF) to its constructor.
2. Create a PDFdocument object
The PdfDocument class is the class that represents the PDF Document in iText. This class belongs to the package com.itextpdf.kernel.pdf. To create this class (in writing mode), you would like to pass an object of the category PdfWriter to its constructor.
Create the PdfDocument class by passing the above created PdfWriter object to its constructor.
3. Add text to the document
Add the desired text to your PDF document
4. Set text color and font
Set the text color of the text added in the previous step using setFontColor() method.
Set the font of the text added in the previous step using setFont() method.
5. Add new text
Add new text which you want to be formatted or added in the text added in step 3.
6. Add the new text to the document
Add the newly created text to our original text. We can do that by using doc.add() method which takes the variable in which the text is stored as a parameter.
Java
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.kernel.color.Color;
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.element.Text;
public class PdfTextFormat {
public static void main(String args[]) throws Exception
{
String file
= "C:/EXAMPLES/itextExamples/GfG.pdf" ;
PdfDocument pdfDoc
= new PdfDocument( new PdfWriter(file));
Document doc = new Document(pdfDoc);
Text text1 = new Text( "Hi I'm Mayank Tyagi" );
text1.setFontColor(Color.BLACK);
text1.setFont(PdfFontFactory.createFont(
FontConstants.HELVETICA));
Paragraph para1 = new Paragraph(text1);
Text text2 = new Text(
"I'm a technical content writer at GeeksforGeeks" );
text2.setFontColor(Color.BLACK);
text2.setFont(PdfFontFactory.createFont(
FontConstants.HELVETICA));
Paragraph para2 = new Paragraph(text2);
doc.add(para1);
doc.add(para2);
doc.close();
System.out.println( "Text added successfully.." );
}
}
|
Output
Share your thoughts in the comments
Please Login to comment...