사용 라이브러리
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
0.03MB
잘린왼쪽.pdf
0.03MB
잘린오른쪽.pdf
0.03MB
도움되셨다면 좋아요~! ㅎㅎ
'JAVA > JAVA' 카테고리의 다른 글
[FTPClient] 550-The filename, directory name, or volume label syntax is incorrect (0) | 2023.10.22 |
---|---|
자바 jdk 버전 매칭표 (0) | 2023.06.05 |
[JAVA] 리눅스 자바 설치 위치 찾는 방법 (how to find real installed java path) (0) | 2023.02.05 |
[Error] Keycloak The method getLocation() is undefined for the type Response (Eureka com.sun.jersey - jsr311-api 관련) (0) | 2023.01.27 |
[Error] Unrecognized field "xml 필드명" (0) | 2023.01.18 |