추가된 사용자 정의 메타데이터 읽기
- 추가된 메타데이터를 간단하게 Sysout을 통해 읽어 보기
사용자가 해당 데이터를 자유롭게 사용
- 메타데이터 읽는 과정
- 'PdfDocument' 객체를 생성 해 파일 경로에서 PDF 문서를 읽음
- PDF 문서 정보 딕셔너리를 'PdfDictionary' 객체로 가져 옴. 메타데이터의 키,값을 포함
- 키가 존재하면 해당 키에 대해서 반복작업 실행
- Base64 인코딩 검사를 하여 예외가 없다면 복호화를 시도
- 해당 과정이 끝났다면 생성된 pdf를 삭제하는 메소드 호출
public class ReadCustomMetadata {
public static void ReadMetaData(String filePath) {
// 암복호화 클래스
Endecryption endecryption = new Endecryption();
try {
// 파일 경로로 PdfDocument 객체를 생성
PdfDocument pdfDocument = new PdfDocument(new PdfReader(filePath));
// pdfDocument 내부 로우객체에서 키값 가져오기
PdfDictionary infoDict = pdfDocument.getTrailer().getAsDictionary(PdfName.Info);
if (infoDict != null) {
// 키가 존재하면 모든 값에 대해 반복
for (PdfName key : infoDict.keySet()) {
// PdfName 객체를 문자열로 변환 후 맨 앞의 '/' 문자를 제거
String keyValue = key.toString().substring(1);
PdfObject value = infoDict.get(key);
if (value != null && value instanceof PdfString) {
// 값이 PdfString 인스턴스이면, 문자열로 변환
String valueStr = ((PdfString) value).toUnicodeString();
if (isBase64Encoded(valueStr)) {
// Base64로 인코딩된 경우, 복호화를 시도
String decryptedValue = endecryption.decrypt(valueStr);
System.out.println(keyValue + ": " + decryptedValue);
} else {
// 사용자 정의 메타데이터 이외의 값은 나오지 않도록 주석처리, 원한다면 해제
// System.out.println(keyValue + ": " + valueStr + " (Base64 인코딩 아님)");
}
}
}
} else {
System.out.println("사용자 정의 메타데이터가 없습니다.");
}
pdfDocument.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 파일 삭제하는 메소드 호출
DeleteBlobFile.DeleteFile(filePath);
}
}
// 문자열이 Base64 인코딩 형식인지 확인
private static boolean isBase64Encoded(String value) {
try {
Base64.getDecoder().decode(value);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
public static void main(String[] args) {
String filePath = "D:/MakePdf/workspace/PDF/outputPdf_new.pdf";
ReadMetaData(filePath);
}
}