[SPRING/JAVA] Apache Pdfbox를 이용한 PDF 생성, 저장, 병합, 비밀번호 설정, 다운로드
본문 바로가기

Web 개발/Java, SpringBoot, JPA

[SPRING/JAVA] Apache Pdfbox를 이용한 PDF 생성, 저장, 병합, 비밀번호 설정, 다운로드

728x90
반응형

1. 의존성 주입

pom.xml 에 다음과 같이 추가

        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.18</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox-tools -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox-tools</artifactId>
            <version>2.0.18</version>
        </dependency>

 

 

 

 

2. PDF 파일 불러오기

  2.1 새 파일 생성

PDDocument document = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
doc.addPage(page);

 

  2.1 기존 파일 불러오기

File file = new File(path);
PDDocument document = PDDocument.load(file);

 

 

 

3. 파일 저장

this.document.save(path);
this.document.close();

 

 

 

4. 페이지 가져오기

  4.1 특정 페이지 불러오기

int pageIdx = 0;
PDPage page = document.getPage(pageIdx);

 

  4.2 첫번째 페이지 불러오기

PDPage page = document.getPage(0);

 

  4.3 마지막 페이지 불러오기

int lastPage = document.getNumberOfPages() - 1;
PDPage page = document.getPage(lastPage);

 

 

 

5. 페이지의 가로, 세로 길이 구하기

float pageW = page.getCropBox().getWidth();
float pageH = page.getCropBox().getHeight();

 

 

 

6. 페이지 삭제

document.removePage(pageIdx);

 

 

 

7. 파일 병합

File file1 = new File(path);
File file2 = new File(path);

PDFMergerUtility merger = new PDFMergerUtility();
merger.setDestinationFileName("fileName");
try {
    merger.addSource(file1);
    merger.addSource(file2);
    merger.mergeDocuments(null);
} catch (IOException exception) {
    log.error(String.valueOf(exception));
    throw new IOException("PDF 병합에 실패하였습니다.");
}

 

 

 

8. 비밀번호

8.1 비밀번호 설정

AccessPermission accessPermission = new AccessPermission();
StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword,userPassword,accessPermission);
spp.setEncryptionKeyLength(128);
spp.setPermissions(accessPermission);
document.protect(spp);

 

8.2 비밀번호 해제

document.setAllSecurityToBeRemoved(true);

 

8.3 비밀번호 설정 여부

boolean result = document.isEncrypted();

 

8.4 비밀번호 설정된 파일 가져오기

File file = new File(path);
PDDocument document = PDDocument.load(file, password);

 

 

 

 

9. PDF 다운로드

파일을 Resource 타입으로 변환

(비밀번호 설정 후에는 다운로드 할 수 없음)

ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos);
document.close();
byte[] bytes = baos.toByteArray();
return new ByteArrayResource(bytes);

 

 

 

 

728x90
반응형