javadictionarypdfitextcatalog

Using iText Java to add a new entry to the PDF Catalog


I am trying to add a new entry to the PDF Catalog object in a new PDF Document. To do that I am using the library iText Java and the new entry is a pair whose key is "/MyVar" and value is a number. The code ends the execution with no problem and the file is created but if I go to the Catalog the entry is not there.

My current code:

package iTextExamples;

import java.io.FileNotFoundException;

import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.Document;

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        String path = "C:\\Path\\PDF1.pdf";
        
        PdfWriter pdfWriter = new PdfWriter(path);
        
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        
        pdfDocument.addNewPage();
        
        int dia = 14;
        
        PdfNumber value = new PdfNumber(dia);
        
        PdfObject obj;
        
        obj = value;
        
        PdfName key = new PdfName("/MyVar");
        
        PdfCatalog cat = pdfDocument.getCatalog();
        
        cat.put(key, value);        

        Document document = new Document(pdfDocument);
        
        document.close();
    }

}

If you know what could be wrong and you share it I would be thankful.


Solution

  • The code ends the execution with no problem and the file is created but if I go to the Catalog the entry is not there.

    On the contrary, I just tested your code and saw that the entry is there:

    1 0 obj
    <</#2fMyVar 14/Pages 2 0 R/Type/Catalog>> 
    

    If you expect /MyVar instead of /#2fMyVar, you should replace

    PdfName key = new PdfName("/MyVar");
    

    by

    PdfName key = new PdfName("MyVar");
    

    as the PdfName constructor does not expect a PDF name indicator / to be part of its argument.