Java

[Java] ApachePDF 라이브러리 이용하여 PDF 파일 읽기

챌인! 2023. 11. 26. 21:20

■ ApachePDFBox 란?

Java로 작성된 오픈 소스 라이브러리로, PDF 파일을 생성, 수정, 조작 및 변환할 수 있는 기능을 제공합니다. 해당 라이브러리는 아래 링크에서 다운받을 수 있습니다. 

https://pdfbox.apache.org/download.html

 

Apache PDFBox | Download

Download Latest Releases The Apache PDFBox community provides feature and bugfix releases. Feature release for PDFBox 3.0.0 — 3.0.0 (requires Java 8) Feature release for PDFBox 2.0.x — 2.0.30 (requires Java 6) Feature release of JBIG2 ImageIO plugin 3.

pdfbox.apache.org

 

 

 

사용예제 

설정정보

저의 경우는  2.0.30 버전의 라이브러리를 다운받아 사용하였습니다. 다운받은 라이브러리는 다음과 같이 설정하여 사용할 수 있습니다.

 

 

Code

Apache PDFBox 라이브러리를 활용하여 PDF 파일의 내용을 텍스트로 읽어옵니다. 해당 코드는 다음과 같습니다.

try 
{
    PDDocument document = PDDocument.load( file );

    PDFTextStripperByArea stripper = new PDFTextStripperByArea();
    stripper.setSortByPosition(true);

    PDFTextStripper Tstripper = new PDFTextStripper();

    // 읽을 페이지 지정
    Tstripper.setStartPage(0);
    Tstripper.setEndPage(1);

    // 해당 페이지 텍스트로 불러오기
    String str = Tstripper.getText(document);

    System.out.println( str );

} 
catch (IOException e) 
{
    e.printStackTrace();
}

 

 

Result

PDF 파일의 1페이지를 출력한 결과입니다.