Monday, January 8, 2018

Get / update the PDF document properties using PDFBox

Here's a neat snippet of how to retrieve or update the PDF document properties

import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
  :

 /*********************************************************
  * Get the PDF document's string metadata value. 
  * 
  * @param pdfDoc
  * @param metadataKey
  * @return
  *********************************************************/
 public static String getMetadataValue(PDDocument pdfDoc,  
                                        String metadataKey)
 {
    PDDocumentInformation info = pdfDoc.getDocumentInformation();
    COSDictionary dict = info.getCOSObject();
    String value = dict.getString(metadataKey);
    return value;
 }



 /**********************************************************
  *  Save Document Property values into the PDF
  *   
  * @param pdfDoc
  * @param metadataKey
  * @param metadataValue
  ***********************************************************/
 public static void saveDocPropertyValue(PDDocument pdfDoc,  
                                         String metadataKey, 
                                         String metadataValue)
 {
    PDDocumentInformation info = pdfDoc.getDocumentInformation();
    COSDictionary dict = info.getCOSObject();
    dict.setString(metadataKey, metadataValue);  
 }

No comments:

Post a Comment