iText 8 is an open source library for creating and manipulating PDF files in Java. It’s a successor to iText 7, providing more advanced features and capabilities for transforming documents into PDF format.
iText 8 supports the creation and manipulation of PDF documents, and offers various functionalities to enhance your PDF generation requirements. With iText 8 you can generate documents from scratch, or manipulate existing documents, customize the content with font styling, add tables, lists and images, generate barcodes or even forms.
Here are the steps to create a simple PDF document using iText 8 in Java:
- Creating a new
PdfWriter
object, passing the outputdest
(file path) as an argument. - Then create a
PdfDocument
with thewriter
object as argument. - Create the root
Document
object. - Instantiate a new
Paragraph
object with some text and add it to the document object. - Finally, close the
document
object which effectively creates your PDF.
The code snippet:
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 CreatePDF {
public static void main(String[] args) {
try {
String dest = "./First-PDF.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating PDF document
PdfDocument pdfDoc = new PdfDocument(writer);
// Document is the default root element
Document document = new Document(pdfDoc);
String text = "This is the first paragraph of the PDF document created using iText 8.";
// Creating paragraph
Paragraph paragraph = new Paragraph(text);
// Adding paragraph to document
document.add(paragraph);
// Closing the document
document.close();
System.out.println("PDF Created Successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Running this code will give you the First-PDF.pdf
file as a result in our current working directory. We can replace the path to an absolute file path to where ever we want to write the output file.
iText version 8 is a powerful tool that, when used correctly, can help automate document generation tasks in your applications, saving a lot of manual effort and ensuring consistency and accuracy. However, it’s important to note that while iText 8 is open-source and free to use under the AGPL license, commercial implementations require purchasing a license.
Maven Dependencies
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>8.0.4</version>
<type>pom</type>
</dependency>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024