본문으로 바로가기

[pdfbox] PDF 반으로 자르는 자바 소스

category JAVA/JAVA 2023. 12. 30. 11:10

사용 라이브러리

implementation 'org.apache.pdfbox:pdfbox:3.0.0'

 

 

소스

public class PDFSplitter {

    public static void main(String[] args) throws IOException{
        PDFSplitter pdf = new PDFSplitter();
        pdf.cropPdfTest();
    }



    public File[] cropPdfTest() throws IOException {

        String inputFilePath = "D:\\workspace\\원본PDF.pdf"; 
        String outputFilePath1 = "D:\\workspace\\잘린왼쪽.pdf"; 
        String outputFilePath2 = "D:\\workspace\\잘린오른쪽.pdf"; 
        
        // 저장 변수
        File[] result = new File[2];
        
        // 원본 PDF 파일 경로
        File inputFile  = new File(inputFilePath);
        
        byte[] pdfbyte = Files.readAllBytes(inputFile.toPath());        

        // Load the PDF document (왼쪽)
        PDDocument document1 = Loader.loadPDF(pdfbyte);

        // PDF 페이지 가져오기
        PDPage page1 = document1.getPage(0); // 페이지 번호는 0부터 시작

        // 자르고자 하는 영역의 좌표 (왼쪽 아래 모서리와 오른쪽 위 모서리)
        float left1 = 0; // 왼쪽 모서리의 x 좌표
        float bottom1 = 0; // 아래쪽 모서리의 y 좌표
        float right1 = page1.getMediaBox().getWidth(); // 오른쪽 모서리의 x 좌표
        float top1 = page1.getMediaBox().getHeight(); // 위쪽 모서리의 y 좌표     

        // 페이지 자르기
        page1.setCropBox(new PDRectangle(left1, bottom1, right1 / 2, top1));

        // 자른 PDF 저장
        File outputFile1 = new File(outputFilePath1);
        document1.save(outputFile1);
        result[0] = new File(outputFilePath1);
        
        document1.close();

        // Load the PDF document (오른쪽)
        PDDocument document2 = Loader.loadPDF(pdfbyte);
        
        // PDF 페이지 가져오기
        PDPage page2 = document2.getPage(0); // 페이지 번호는 0부터 시작

        float left2 = page2.getMediaBox().getWidth() / 2;
        float bottom2 = 0;
        float right2 = page2.getMediaBox().getWidth();
        float top2 = page2.getMediaBox().getHeight();

        // 페이지 자르기
        page2.setCropBox(new PDRectangle(left2, bottom2, right2, top2));

        File outputFile2 = new File(outputFilePath2);
        document2.save(outputFile2);
        result[1] = new File(outputFilePath2);

        document2.close();

        System.out.println("PDF 자르기 완료");

        return result;
    }

 

 

원본 PDF

 

왼쪽, 오른쪽으로 잘린 모습
원본.pdf
0.03MB
잘린왼쪽.pdf
0.03MB
잘린오른쪽.pdf
0.03MB

 

 

 

도움되셨다면 좋아요~! ㅎㅎ