Core Java

iText PDFwriter Example

In the previous example, we studied about how we can use Itext to create a PDF and perform basic operations. In this example, we will dive deeper into the PDFWriter and demonstrate the different operations we can perform on PDF using the same.
 
 
 
 
 
 
 
 

 
So let’s get started without much ado. Here’s the pom.xml

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>ITextExample</groupId>
	<artifactId>ITextExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.6</version>
		</dependency>
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk15on</artifactId>
			<version>1.52</version>
		</dependency>


	</dependencies>

</project>

This pom.xml has one more dependency for the bouncycastle.jar. We need this Jar for encrypting the PDF Files that we have created. The Jar provides implementation of the encryption algorithms we will use, to encrypt the PDF document we generate. We will see in a while how we can achieve this, let’s have a look at the table of contents.

1. Creation of PDF

We will look at a simple code that will create a PDF with “Hello-World”.

CreatePDF.java

package com.jcg.examples;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class CreatePdf
{
		public static void main(String[] args) throws FileNotFoundException, DocumentException
		{
			Document document = new Document();
			@SuppressWarnings("unused")
			PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
			document.open();
			
			Paragraph paragraph = new Paragraph();
			paragraph.add("Hello World!");
			paragraph.setAlignment(Element.ALIGN_CENTER);
				
			Paragraph otherParagraph = new Paragraph();
			otherParagraph.add("Welcome to JCG!");
			otherParagraph.setAlignment(Element.ALIGN_CENTER);
				
			document.add(paragraph);
			document.add(otherParagraph);
			document.close();
		}
		
}

The code is pretty straight-forward. We start by instantiating the com.itextpdf.text.Document class. Then pass this Documentinstance to the PDFWriter class along-with the FileOutputStream object. Then we add a Paragraph element to the document and indent it to the center. Adding an element to the document is enough to get it written to the PDF. When we close the document(line 31), all the elements written to the document get flushed and thus written to the PDF File. Once the Document is closed, nothing can be written to the body anymore. Doing so throws DocumentException.

Here’s a snapshot of the document thus created:

Fig 1 : Sample PDF
Fig 1 : Sample PDF

2. Add a Water-Mark

When generating PDF documents, many-a-times it is important to add water-mark of your organization or your client’s organization to the document. We will see how we can add water-mark to our HelloWorld PDF generated above.

To add a water-mark to the PDF generated, we shall create a event-listener class. This event listener class will listen for the page end event and add the water-mark when it encounters such an event.

PDFEventListener.java

package com.jcg.examples;


import java.io.IOException;
import java.net.MalformedURLException;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;


class PDFEventListener extends PdfPageEventHelper
{

		@Override
		public void onEndPage(PdfWriter writer, Document document)
		{
				try
				{
					Image background = Image.getInstance("src\\main\\resources\\JavaCodeGeeks-water3.png");
					float width = background.getWidth();
					float height = background.getHeight();
					writer.getDirectContentUnder().addImage(background, width, 0, 0, height, 0, 0);
				}
				catch (BadElementException e)
				{
					e.printStackTrace();
				}
				catch (MalformedURLException e)
				{
					e.printStackTrace();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				catch (DocumentException e)
				{
					e.printStackTrace();
				}
		}

}

Next we need to register this event listener with the PdfWriter class.

PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
pdfWriter.setPageEvent(new PDFEventListener());

Here’s how the book-marked document looks like :

Fig 2 : WaterMark Document
Fig 2 : WaterMark Document

Note: Decreasing the opacity of the image prior to using it in the document will improve the aesthetics of the document.

3. Attach a File to PDF

In this section we will demonstrate how we can attach a file to a PDF document while creating it. Let’s see the code :

AddAttachment.java

package com.jcg.examples;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfFileSpecification;
import com.itextpdf.text.pdf.PdfWriter;


public class AddAttachment
{
		public static void main(String[] args) throws FileNotFoundException, DocumentException
		{
				Document document = new Document();
				PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
				document.open();
				File file  = new File("HelloWorld1.pdf");
				if(file.exists())
				try
				{
						PdfFileSpecification fileSpecification = PdfFileSpecification.fileEmbedded(pdfWriter, file.getAbsolutePath(),file.getName(), null);
						
						pdfWriter.addFileAttachment("Sample Attachment", fileSpecification);
				}
				catch (IOException e)
				{
						e.printStackTrace();
				}
				
				
				Paragraph paragraph = new Paragraph();
				paragraph.add("Hello World!");
				paragraph.add("Welcome to JCG!");
				paragraph.setAlignment(Element.ALIGN_CENTER);

				document.add(paragraph);
				document.close();
		}

}

We get the com.itextpdf.text.pdf.PdfFileSpecification instance by passing the source of the file and the description which we want to see in the attachment section of the PDF. Then we attach the Specification to the writer using PdfWriter#addFileAttachment method which in turn attaches to the Document body. One important thing to note here is that the document should be open for writing before get the instance of the PdfFileSpecification, else the document body is null. This throws NullPointerException when the attachment object is added to the body.

Here’s the attached document snapshot:

Fig 3 : Attachment to a PDF
Fig 3 : Attachment to a PDF

4. Encryption of the PDF

One of the most common operation we may want to perform on the PDF we generate is to protect them from unauthorized eyes.The best way to achieve this is to password protect the file. In this section, we will see how we can encrypt the PDF Files we generate using the PdfWriter class.

PdfEncrytpion.java

package com.jcg.examples;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;


public class PdfEncrytpion
{
		public static void main(String[] args)
		{
				try
				{
						Document document = new Document();
						PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
						pdfWriter.setEncryption("chandan".getBytes(), "chandansingh".getBytes(), PdfWriter.ALLOW_ASSEMBLY, PdfWriter.ENCRYPTION_AES_256);
						document.open();
						
						Paragraph paragraph = new Paragraph();
						paragraph.add("Hello World!");
						
						document.add(paragraph);
						document.close();
				}
				catch (FileNotFoundException | DocumentException e)
				{
						e.printStackTrace();
				}
		}

}


To encrypt a pdf file we need to set the encryption option for the document using the PdfWriter class. We use the PdfWriter.setEncryption method to do this. Here’s is its signature:

void com.itextpdf.text.pdf.PdfWriter.setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) throws DocumentException

The user password recognizes the consumers(by default readers) of the document. The owner password recgnizes the creater or the owner of the document. The creator may also choose the operations that are to be permitted once the document is opened. The operations can be multi-selected by ORing the different operations provided by the PdfWriter class. We chose the encryption Type to AES 256 bytes.

Here’s the password prompt when you attempt to open the PDF :

Fig 4 : Encrypted PDF
Fig 4 : Encrypted PDF

5. Download the Source Code

We studied how we can create PDF using PDFWriter class from IText and the different operations supported by it.

Download
You can download the source code of this example here: PDFWriterExample.zip

Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button