This example is the first example of the iText PDF series, we are going to start by learning to use the iText PDF library to create a PDF document. We will see how to use the Document
class, getting an instance of PdfWriter
, creating a simple Paragraph
and set the text alignment and the font.
The basic steps to produce a PDF documents are:
- Create a
Document
object that represents a PDF document. - The
PdfWrite
object that need theDocument
and anOutputStream
object write the content of the PDF we added to theDocument
into a PDF file. - We add a paragraph into the
Document
instance using theParagraph
object. - Finally, we need to close the document by calling the
Document.close()
method.
And here is a code example that demonstrate the creation of a PDF document.
package org.kodejava.itextpdf;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class DocumentCreate {
public static void main(String[] args) {
// Create a new document.
Document document = new Document();
try {
// Get an instance of PdfWriter and create a HelloWorld.pdf
// file as an output.
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));
document.open();
// Create our first paragraph for the pdf document to be
// created. We also set the alignment and the font of the
// paragraph.
String text = "Kode Java website provides beginners to Java " +
"programming some examples to use the Java API " +
"(Application Programming Interface) to develop " +
"applications. Learning from some examples will " +
"hopefully decrease the time required to learn " +
"Java.";
Paragraph paragraph = new Paragraph(text);
paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
paragraph.setFont(new Font(
Font.FontFamily.HELVETICA, 10, Font.NORMAL));
document.add(paragraph);
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
} finally {
document.close();
}
}
}
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=com/itextpdf/itextpdf/5.5.13.3/itextpdf-5.5.13.3.jar -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023