[java] Apache POI를 이용한 Word 문서 보호 설정

Apache POI는 Java로 작성된 라이브러리로, Microsoft Office 형식의 문서를 읽고 쓰는데 사용됩니다. 이번 블로그 포스트에서는 Apache POI를 사용하여 Word 문서를 보호하는 방법에 대해 알아보겠습니다.

필요한 라이브러리 추가

먼저 Apache POI를 사용하기 위해 Maven을 이용하여 필요한 의존성을 추가해야 합니다.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>

Word 문서 보호 설정하기

import org.apache.poi.xwpf.usermodel.*;

import java.io.*;

public class WordDocumentProtection {

    public static void main(String[] args) {
        try {
            // 보호할 Word 문서 파일을 읽기
            FileInputStream fileInputStream = new FileInputStream("input.docx");
            XWPFDocument document = new XWPFDocument(fileInputStream);

            // 보호 설정을 위한 작업
            document.enforceReadonlyProtection();  // 읽기 전용 보호 설정
            document.enforcePasswordProtection("password");  // 암호 보호 설정

            // 보호된 문서를 새 파일로 저장
            FileOutputStream fileOutputStream = new FileOutputStream("protected.docx");
            document.write(fileOutputStream);
            fileOutputStream.close();

            document.close();

            System.out.println("Word 문서 보호 설정이 완료되었습니다.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예시 코드는 input.docx라는 파일을 읽어와서 읽기 전용 보호와 암호 보호를 설정한 후, protected.docx라는 새로운 파일로 저장합니다. 암호를 설정할 때는 enforcePasswordProtection() 메소드의 인자로 암호를 전달하면 됩니다.

참고 자료