[java] Apache PDFBox로 PDF 파일 헤더 또는 푸터 추가하기

Apache PDFBox는 Java로 작성된 오픈 소스 PDF 라이브러리로, PDF 파일을 생성하고 수정하는 기능을 제공합니다. 이번 블로그 포스트에서는 Apache PDFBox를 사용하여 PDF 파일의 헤더 또는 푸터를 추가하는 방법에 대해 알아보겠습니다.

1. Apache PDFBox 설치

먼저, Apache PDFBox를 사용하기 위해 해당 라이브러리를 설치해야 합니다. Maven을 사용하는 경우 pom.xml 파일에 다음 종속성을 추가하십시오:

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>

Gradle을 사용하는 경우 build.gradle 파일에 다음 종속성을 추가하십시오:

implementation 'org.apache.pdfbox:pdfbox:2.0.24'

Apache PDFBox를 직접 다운로드하고 설치하는 방법은 Apache PDFBox 공식 웹사이트에서 확인할 수 있습니다.

2. PDF 파일 열기

PDFBox를 사용하여 PDF 파일을 편집하려면 다음과 같이 PDDocument 객체를 생성하고 PDF 파일을 엽니다:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

// Existing PDF file path
String filePath = "path/to/pdf/file.pdf";

// Load the PDF document
PDDocument document = PDDocument.load(new File(filePath));

3. 헤더 또는 푸터 추가하기

PDF 파일의 각 페이지에 헤더 또는 푸터를 추가하기 위해 다음과 같이 PDPageContentStream을 사용합니다:

import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

// Iterate through each page of the PDF document
for(PDPage page : document.getPages()) {
    PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);

    // Set font and font size for the header/footer text
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);

    // Choose the position for the header/footer text
    float x = 50;
    float y = page.getMediaBox().getHeight() - 50;

    // Write the header/footer text
    contentStream.beginText();
    contentStream.newLineAtOffset(x, y);
    contentStream.showText("Header/Footer Text");
    contentStream.endText();

    // Close the content stream
    contentStream.close();
}

위의 예제에서는 PDPageContentStream 객체를 생성할 때 PDPageContentStream.AppendMode.APPEND를 지정하여 이미 존재하는 콘텐츠 다음에 헤더 또는 푸터를 추가할 수 있습니다.

4. PDF 파일 저장하기

헤더 또는 푸터를 추가한 후, 수정된 PDF 파일을 저장해야 합니다. 다음과 같이 PDDocument 객체를 사용하여 저장할 수 있습니다:

// Save the modified PDF document
String outputFilePath = "path/to/output/file.pdf";
document.save(new File(outputFilePath));

// Close the PDF document
document.close();

위의 코드에서 outputFilePath는 헤더 또는 푸터가 추가된 수정된 PDF 파일의 경로를 나타냅니다.

마무리

이렇게 Apache PDFBox를 사용하여 PDF 파일의 헤더 또는 푸터를 추가하는 방법에 대해 알아보았습니다. PDFBox에는 다양한 기능과 API가 제공되므로, 더 많은 정보와 예제 코드는 Apache PDFBox 공식 문서를 참조하시기 바랍니다.