Adding List in a PDF using Java
Last Updated :
04 Oct, 2021
In this article, we will learn how to create a PDF and add a list to that PDF using java. For adding a list in a PDF, we will use the iText library. These are the steps that should be followed to add a list in a PDF using java.
1. Creating a PdfWriter object
The PdfWriter class represents the DocWriter for a PDF. The constructor of this class accepts a string, i.e. the path of the file where the PDF is to be created.
Java
import com.itextpdf.kernel.pdf.PdfWriter;
String path = "C:/JavaPdf/addingList.pdf" ;
PdfWriter pdfwriter = new PdfWriter(path);
|
2. Creating a PdfDocument object
The PdfDocument class is the class that represents the PDF Document in iText, To instantiate this class in write mode, you need to pass an object of the class PdfWriter (i.e. pdfwriter from above code ) to its constructor.
Java
PdfDocument pdfdocument = new PdfDocument(pdfwriter);
|
3. Creating the Document object
The Document class is the root element when creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument (i.e. pdfdocument).
Java
Document document = new Document(pdfdocument);
|
4. Creating a List object and adding elements to the list object.
The List represents a series of objects that are vertically oriented. We add elements to the list object using the add() method of the List class.
Java
List list = new List();
list.add( "geekforgeeks" );
list.add( "helps" );
list.add( "to" );
list.add( "master" );
list.add( "DSA" );
|
5. Here comes the final part Adding List objects to the document.
Add the list object using the add() method of the Document class, and close the document using close() method of Document class
Java
document.add(list);
document.close();
|
Example: Here is the final code that helps us in understanding how to add a list in PDF using java.
Java
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.Document;
public class AddList {
public static void main(String args[])
{
try {
String path = "C:/JavaPdf/addingList.pdf" ;
PdfWriter pdfwriter = new PdfWriter(path);
PdfDocument pdfdocument
= new PdfDocument(pdfwriter);
Document document = new Document(pdfdocument);
List<String> list = new ArrayList();
list.add( "geekforgeeks" );
list.add( "helps" );
list.add( "to" );
list.add( "master" );
list.add( "DSA" );
document.add(list);
document.close();
System.out.println(
"List has been successfully added to the file :"
+ path);
}
catch (Exception e) {
System.out.println(
"failed to add the list to file due to "
+ e);
}
}
}
|
Compile and execute the saved Java file from the Command prompt using the following commands:
javac AddList.java
java AddList
Output
pdf with a list added using java
Share your thoughts in the comments
Please Login to comment...