최근 pdf 파일을 암호설정 후 이메일로 전송해주는 기능을 구현하는 업무를 하게 되었는데, 먼저 pdf 파일을 암호 설정하는 방법을 정리하는 글을 쓴 뒤 이메일 전송에 관한 글을 쓸 예정이다.
먼저 Java + Spring + maven 환경에서 개발할 때를 기준으로 글을 작성할 예정이고, Itextpdf, pdfbox라는 외부라이브러리를 사용했기 때문에 Itextpdf를 이용하여 암호설정을 하는방법을 정리한다.
(회사에서 사용하고 있는설정이라 그대로 사용)
[maven의존성 추가]
<!-- ItextPdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
<!-- pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.1</version>
</dependency>
다음과 같이 코드를 작성해주면 된다.
(예외 throws, 생성된 파일을 이메일로 발송하는데 쓸것이기 때문에 filefath를 리턴했다.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.xhtmlrenderer.pdf.ITextRenderer;
/**
* 클래스 선언 및 메인메소드 선언 생략
* 중요 import 부분만 서술함
*/
private String pdfEncryption(String target, String password) throws IOException, DocumentException {
// html 파일 읽기
String filePath = "";
ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("font/Spoqa Han Sans Regular.ttf", com.itextpdf.text.pdf.BaseFont.IDENTITY_H, com.itextpdf.text.pdf.BaseFont.NOT_EMBEDDED);
renderer.getFontResolver().addFont("font/Spoqa Han Sans Bold.ttf", com.itextpdf.text.pdf.BaseFont.IDENTITY_H, com.itextpdf.text.pdf.BaseFont.NOT_EMBEDDED);
renderer.setDocument(target); // html 페이지의 url 또는 file 경로
renderer.layout(); // ITextRenderer가 html파일을 xhtml형식으로 읽음
//pdf파일 생성
filePath = "/test/testpdf.pdf";
OutputStream outputStream = new FileOutputStream(filePath);
renderer.createPDF(outputStream); // pdf파일 생성
outputStream.close();
//pdf파일 암호설정
File file = new File(filePath);
PDDocument pdDocument = PDDocument.load(file); // 파일에 암호가 있으면 두번째 인자에 입력
AccessPermission accessPermission = new AccessPermission();
StandardProtectionPolicy standardProtectionPolicy = new StandardProtectionPolicy(password, password, accessPermission); // param : ownerpassword, userpassword, AccessPermission
standardProtectionPolicy.setEncryptionKeyLength(128); // 암호화 키길이(40, 128, 256) 이외 값 exception
standardProtectionPolicy.setPermissions(accessPermission);
pdDocument.protect(standardProtectionPolicy);
pdDocument.save(filePath);
pdDocument.close();
return filePath;
}
|
cs |
코드를 보면 알 수 있지만, 별로 어려운부분은 없고 렌더가 렌더링할 떄 css나 옵션을 줄 수 있는데 나의 경우는 html 페이지에서 해결을 했다.
추가로 xhtml문법으로 페이지가 작성되있지 않으면 오류가 발생한다. (태그만 잘닫아주면 될듯 오류를 볼일은 없을 듯?)
작업하기전에는 복잡한 작업이 될 줄 알았는데, 생각보다 간단한 작업이였다.
다음글은 생성된 pdf파일을 이메일로 전송하는 로직을 정리해보려한다.
'JAVA' 카테고리의 다른 글
Java의 UnsupportedOperationException (feat array, List) (0) | 2021.12.08 |
---|---|
Java 클래스의 변수명 가져오기 (0) | 2021.11.23 |
Java 실수형 자료 계산하기 (0) | 2021.06.08 |
Java를 처음부터 다시 살펴본 후기 (0) | 2021.05.21 |
JAVA의 Optional 정리 (Java 8 기준) (0) | 2021.03.22 |