Create PDF documents like a pro – part 1

For the creation of  PDF documents, we will use the iText library. It is opensource and can be downloaded here. I will create a series of blog posts in which I will describe how to manipulate PDF files through Java. Create dynamic document This is the most common and easy way. In this case, you don`t […]

by Denis Danov

November 27, 2014

3 min read

schema PDFTPlus final 3 - Create PDF documents like a pro - part 1

For the creation of  PDF documents, we will use the iText library. It is opensource and can be downloaded here. I will create a series of blog posts in which I will describe how to manipulate PDF files through Java.

Create dynamic document

This is the most common and easy way. In this case, you don`t use any PDF templates and the new file is created at runtime from your java code. In this case iText takes care of inserting new pages when there is not enough space. Each component is added one after another to the document. As you can see I prefer using tables for layout and content but you can insert text in Paragraph, Phrases, Chunks or any other component. To complete this case you need to follow several easy steps:

  1. Create and obtain document instance with its size and margins
  2. Create PdfWriterInstance, just call the getInstance method the actual instance is not needed in this case
  3. After writer is created open the document
  4. Add the content to the document
  5. Close the document and the output stream

It is as easy as that, you can see from the provided code below:

[java]
public class FirstExample {
public static void main(String[] args) {
[/java]

 1.Create and obtain document instance with its size and margins

[java]
Document document = new Document(PageSize.A4);
document.setMargins(36, 36, 36, 36);
FileOutputStream fos = null;
try {
fos = new FileOutputStream("FirstPdfDocument.pdf");
[/java]

 2.Create PdfWriterInstance

Just call the getInstance method the actual instance is not needed in this case

[java]
PdfWriter writer = PdfWriter.getInstance(document, fos);
[/java]

 3.After the writer is created open the document

[java]
document.open();
[/java]

4.Add the content to the document

[java]
addContent(document);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
[/java]

5.Close the document and the output stream

[java]
document.close();
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}}}}
public static void addContent(Document document) throws DocumentException {
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell(new Phrase("Your first PDF document"));
table.addCell(cell); document.add(table);
}
}
[/java]

Create document from template

Now I  will show you how to accomplish the following scenario where you have predefined template created with another program and you have to populate its form field values from the java code.  It is useful to use templates when you have static content, well-designed layout and just a few form fields to fill. Let’s look in this example as it is self-explanatory and has comments in it:

[java]
public class TemplateExample {
[/java]

 1.Get some Lorem text for content

[java]
public static String getLoremText() throws IOException, DocumentException {
return "Lorem ipsum dolor sit amet," +
"consectetur adipiscing elit. Etiam sit amet ligula pretium," +
"feugiat nisl vel, lacinia elit. Vivamus porta elit at erat" +
"gravida malesuada eu a mi. Sed sed dui est. Aliquam porta cursus eros," +
"ac imperdiet ex sagittis vel. Proin id nibh eu magna efficitur rutrum." +
"Cras a metus ipsum. Aenean quis urna dapibus, semper nulla in, cursus dolor.";
}
public static void main(String[] args) throws FileNotFoundException,
DocumentException,
IOException {
File newPdfPage = new File("PageTemplateExample.pdf");
FileOutputStream fileOutputStream = new FileOutputStream(newPdfPage);
PdfReader pdfTemplate = new PdfReader(new FileInputStream("PdfPageTemplate.pdf"));
[/java]

2.The only change is here we get PdfStamper object instead of PdfWriter

[java]
PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
[/java]

3.This will flatten the fields once the document is closed

[java]
stamper.setFormFlattening(true);
AcroFields acroFields = stamper.getAcroFields();
[/java]

4.Get the form field by its name and set its text

[java]
acroFields.setField("TextArea", getLoremText());
stamper.close();
pdfTemplate.close();
fileOutputStream.close();
}
}
[/java]

Here is the example.

 

Ready here. Up to Part 2.

 I welcome your comments & suggestions

 

Java EE and Oracle Developer at Dreamix