본문 바로가기
개발 부산물

[Java] Apache PDFBox 사용하기 #1

by 개탱 2022. 11. 21.
728x90
  • 선 그리기 등은 추 후에 추가 예정입니다.

Apache PDFBox 공식 페이지

https://pdfbox.apache.org/

 

1. pom.xml PDFBox 추가


<!-- PDFBox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.27</version>
</dependency>

 

2-1 PDF 생성


PDDocument document
= new PDDocument();

2-2 기존 PDF 불러오기


String
path = "files/file.pdf";
ClassPathResource resource = new ClassPathResource(path);
File file = resource.getFile();

PDDocument doc = PDDocument.load(file);

 

3. 페이지 추가 및 선택

- 페이지 생성 시 new Page()로 생성을 하며 해당 페이지를 document에 등록시켜주기위하여 document.addPage(page)의 행위를 진행합니다.
- 페이지 선택시 페이지의 인덱스 번호를 파라메터로 가져오는데, 인덱스의 시작 번호는 0번 입니다.


//페이지 생성
PDPage page = new PDPage();
document.addPage(page);

//페이지 선택
PDPage selectedPage = document.getPage(idx);

4. 그리기 준비


PDPageContentStream contentStream = new PDPageContentStream(doc, page);
//PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);

 
 

5. 로컬 폰트 선택

- ttf Font 파일을 로드해옵니다. (PDType0Font 의 load() 이용)


URL resources = getClass().getResource("/font/");
PDType0Font font = PDType0Font.load(doc, new FileInputStream(resources.getPath()+"font.ttf"));

 

6. 텍스트 그리기

- 이전에 준비단계에서 추가하였던 PDPageContentStream을 통해 진행합니다.

- 폰트, 글자 색 등은 한번 지정시 계속 유지됩니다.


// 텍스트 그리기 시작
contentStream.beginText();
// 글자 색 지정
contentStream.setNonStrokingColor(Color.RED);
// 폰트 설정
contentStream.setFont(font, fontSize);
// 텍스트가 그려질 커서 위치 지정
contentStream.newLineAtOffset(x, y);
// 그려질 텍스트 추가
contentStream.showText(text);
// 텍스트 그리기 종료
contentStream.endText();

 

 

7. 그리기 종료


//등록하였던 PDPageContentStream 종료
contentStream.close();
//필자는 bos방식으로 저장하여 추가적인 행위를 진행하였습니다.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//doc 저장
doc.save(bos);
//아래와 같이 경로지정을 통한 파일 저장도 가능합니다.
//Saving the document
doc.save("E:/pdftitle.pdf");
//doc 종료
doc.close();
return bos.toByteArray(); //Byte [] 형식으로 출력

 

 

 

댓글