Java iText Add PDF Metadata Tutorial Example

In this short tutorial, we will throw some light on how to add metadata in a PDF document using iText with a simple example based approach. Earlier,we discussed how to read(extracting) metadata information out of a PDF file through itext.The illustration we will be providing in this example will teach a reader the basics of adding information like Title, Author, Subject, Keywords and Creator. We are not going to add the metadata in a PDF file using the XML (XMP) based technique. We will discuss about adding metadata as XMP in a later tutorial. I would like to recommend the users to read about metadata from our earlier section to get some idea before attempting this section.The step by step procedure is given below;

Step-1: Begin by creating a Document and PdfWriter object. We also open the document for adding the structural information.
            Document PDF_Meta_Data = new Document();
            PdfWriter.getInstance(PDF_Meta_Data, new FileOutputStream("Sample.pdf"));
            PDF_Meta_Data.add(new Paragraph("Adding Metadata to PDF PDF_Meta_Datas using iText Example"));
Step-2: If you notice in Step-1, we have also pushed some sample content to the PDF document. Now, the Document object directly provides some methods to add the metadata information. We will be using those methods now to add the metadata we are after. These methods with suitable comments are provided below;
            /* Add PDF Document Title through Code */
            PDF_Meta_Data.addTitle("Append Metadata to PDF Example");
            /* Add PDF Author Information */
            /* Add the Subject for the file */
            PDF_Meta_Data.addSubject("Metadata Addition to PDF Tutorial");
            /* Included Keyword information */
            PDF_Meta_Data.addKeywords("Metadata, iText, PDF");
            /* Insert Creator Information and Creation Date to the Document */
The complete code that adds basic document information to a PDF file is provided below.
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
public class AddPDFMetadata {  
     public static void main(String[] args){
        try {
            Document doc = new Document();
            PdfWriter.getInstance(doc, new FileOutputStream("Sample.pdf"));
            doc.add(new Paragraph("Adding Metadata to PDF docs using iText Example"));
            doc.addTitle("Append Metadata to PDF Example");
            doc.addSubject("Metadata Addition to PDF Tutorial");
            doc.addKeywords("Metadata, iText, PDF");
        catch (Exception i)
When you run this code and then inspect document properties you can see the metadata we have added through the code in it. A sample screenshot is provided below;

Add PDF Metadata Example
PDF With Metadata Added
What will happen if you try to read the metadata we stamped using the getMetaData method? I got a java.lang.NullPointerException as we did not add any XMP information.

No comments:

Post a Comment