생성된 PDF에 사용자 정의 메타데이터 추가
- 생성 과정
- endecryption 인스턴스 생성하여 메타데이터 값 암호화 이후 저장을 위해 HashMap 생성
- 예제에서는 for문을 통한 반복데이터와 단일 데이터를 추가하고 있음
데이터를 넣기 위한 다른 방식이 필요하다면 추가 개발이나 수정 계획
- 키와 암호화된 값은 PdfDictionary 객체인 customInfo에 추가. 그리고 PdfDictionary는 PdfDocument 객체를 통해 Pdf문서 카탈로그에 'Metadata' 항목으로 추가 함
public class AddCustomMetadata {
// PDF 문서에 사용자 정의 메타데이터를 추가하는 메서드
public static void addCustomMetadata(String pdfPath) {
// 암복호화 클래스의 인스턴스 생성
Endecryption endecryption = new Endecryption();
// 사용자 정의 메타데이터를 저장할 HashMap 생성
Map<String, String> customMetadata = new HashMap<>();
// 사용자 정의 메타데이터 값 추가 예시
for (int i = 1; i <= 10; i++) {
// 키를 평문으로 저장하고 값만 암호화하여 저장
// 키는 암호화X
String key = "Iron" + i;
String encryptedValue = endecryption.encrypt("man" + i); // 값만 암호화
customMetadata.put(key, encryptedValue);
}
// 단일 메타데이터 추가
customMetadata.put("OneData", endecryption.encrypt("OneValue"));
try {
// 지정된 PDF 파일을 읽고 새로운 PDF 파일로 저장하기 위해 PdfDocument 객체 생성
PdfDocument pdfDocument = new PdfDocument(new PdfReader(pdfPath), new PdfWriter(pdfPath.replace(".pdf", "_new.pdf")));
// 사용자 정의 메타데이터를 Info 딕셔너리에 추가
PdfDocumentInfo info = pdfDocument.getDocumentInfo();
customMetadata.forEach((key, value) -> info.setMoreInfo(key, value));
// 새로운 pdf를 만듦었으므로 읽을 파일의 이름도 수정
pdfPath = pdfPath.replace(".pdf", "_new.pdf");
// 문서 종료
pdfDocument.close();
System.out.println("PDF에 사용자 정의 메타데이터가 추가되었습니다.");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 사용자 정의 메타데이터 읽는 클래스 호출
ReadCustomMetadata.ReadMetaData(pdfPath);
}
}
public static void main(String[] args) {
// 메타데이터를 추가할 PDF 파일의 경로를 지정
String pdfPath = "D:/MakePdf/workspace/PDF/outputPdf.pdf";
addCustomMetadata(pdfPath);
}
}