kz2014
kz2014

Reputation: 333

Get custom metadata for itext 7 pdf document

I used the link given below for getting metadata in itext 5 using: Get and set metadata for itext pdf document

Currently, i can get metadata in itext7 too using the snippet:

PdfDocument pdfDoc = new PdfDocument(new PdfReader(src));
PdfDocumentInfo info = pdfDoc.getDocumentInfo();
info.getAuthor();
info.getCreator();
info.getProducer();

I don't know how to get custom properties using the same. I can set custom metadata using:

pdfDoc.getDocumentInfo().setMoreInfo("Test", "test");

How to get this value programatically without hard coding the key name? Also, is there a way to get these metadata values (including custom metadata) without actually writing:

getAuthor, getCreator, etc?

Upvotes: 2

Views: 5291

Answers (2)

Pavel Chermyanin
Pavel Chermyanin

Reputation: 391

In iText 7.0.8+ you can get a pdf metadata map this way.

PdfDocument pdfDoc = new PdfDocument(new PdfReader(src));
//get metadata map
PdfDictionary catalog = pdfDoc.getTrailer();
PdfDictionary map = catalog.getAsDictionary(PdfName.Info);
for (Map.Entry<PdfName, PdfObject> entry : map.entrySet()) {
 System.out.println(entry.getKey().getValue() + " - " + entry.getValue());
}
pdfDoc.close();

You can set custom metadata using:

 map.put(new PdfName("test"), new PdfString("test"));       

Upvotes: 0

kz2014
kz2014

Reputation: 333

No worries, got the answer. Didn't realize earlier that:

PdfDictionary map = info.getPdfObject();

returns map type object. Parsed the map to get all the key-value pairs including the custom properties. Below is the full code snippet:

import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfDocumentInfo;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfObject;
import com.itextpdf.kernel.pdf.PdfReader;

import java.io.File;
import java.io.IOException;
import java.util.Map.Entry;

public class GetInfo {

    public static final String SRC = "hello.pdf";

    public static void main(String[] args) throws IOException {
        File file = new File(SRC);
        file.getParentFile().mkdirs();
        new GetInfo().manipulatePdf(SRC);
    }

    public void manipulatePdf(String src) throws IOException {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src));
        PdfDocumentInfo info = pdfDoc.getDocumentInfo();
        PdfDictionary map = info.getPdfObject();
        for(Entry<PdfName, PdfObject> entry : map.entrySet()){
            System.out.println(entry.getKey().getValue() + " - " + entry.getValue() );
        }
        pdfDoc.close();
    }
}

Upvotes: 4

Related Questions