[JAVA] 자바 PDF 변환 (pdf를 jpg로 변환 / jpg를 pdf로 변환)
자바에서 PDF를 다루기 위한 라이브러리로 apache 의 pdfbox 가 있다.
본 게시글에서는 pdfbox 2.0.11 버전을 사용하였다.
우선 http://pdfbox.apache.org/ 에 들어가서 pdfbox-app-2.0.11.jar 를 다운받는다. (아래 그림)
잘 다운로드 되었으면 활용할 프로젝트 클래스 패스에 추가하자.

1. PDF 파일을 JPG 파일들로 변환하는 방법
PDF 파일을 JPG 파일들로 변환하는 방법이다.
try ~ catch가 포함된 자세한 코드는 본 게시글의 “convertPDFFileToJPGFile” 메서드를 검색해 보면 된다.
1-1. PDF 문서 객체(PDDocument) 준비
|
File file = new File(“pdf파일의위치”); |
1-2. PDF 파일의 페이지 수 가져오기
|
int pageCount = document.getNumberOfPages(); |
1-3. PDF 파일을 JPG 파일로 변환
|
PDFRenderer pdfRenderer = new PDFRenderer(document); // 0 페이지를 JPG파일로 저장 // 1 페이지를 JPG파일로 저장 // 2 페이지를 JPG파일로 저장 … (후략) |
1-4. 사용한 PDF 문서 객체 닫기
|
if (document != null) { |
2. JPG 파일들을 PDF 파일로 변환하는 방법
JPG 파일들을 PDF 파일들로 변환하는 방법이다.
try ~ catch가 포함된 자세한 코드는 본 게시글의 “convertJPGFileToPDFFile” 메서드를 검색해 보면 된다.
2-1. 새 PDF 문서 객체(PDDocument) 준비
|
PDDocument document = new PDDocument(); |
2-2. JPG 파일 읽어서 PDF 문서 객체에 1장씩 그리기
|
// 추가할 JPG 파일 읽기 // PDF 페이지 객체 1장 생성 // PDF 문서 객체에 페이지 1장 그리기 // 1장 그릴 때마다 사용한 객체 닫기 if (contentStream != null) { if (inputStream != null) { |
2-3. PDF 문서를 파일로 저장
|
document.save(“결과PDF파일경로지정”); |
2-4. 사용한 PDF 문서 객체 닫기
|
if (document != null) { |
아래부터 직접 작성한 예제 소스코드이며 http://github.com/thkmon/PDFConverter 에서 자세한 내용을 볼 수 있다.
———-
package com.bb;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
public class PDFConverter {
public static void main(String[] args) {
PDFConverter pdfConverter = null;
try {
pdfConverter = new PDFConverter();
pdfConverter.testConvertPDF2JPG();
pdfConverter.testConvertJPG2PDF();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* example method of converting PDF file to JPG file.
*
* @throws Exception
*/
public void testConvertPDF2JPG() throws Exception {
String pdfFilePath = new File(“input/example.pdf”).getAbsolutePath();
String destFolderPath = new File(“output”).getAbsolutePath();
this.convertPDFFileToJPGFile(pdfFilePath, destFolderPath);
}
/**
* example method of converting JPG file to PDF file.
*
* @throws Exception
*/
public void testConvertJPG2PDF() throws Exception {
String jpgsFolderPath = new File(“output”).getAbsolutePath();
String destFolderPath = new File(“result/result.pdf”).getAbsolutePath();
this.convertJPGFileToPDFFile(jpgsFolderPath, destFolderPath);
}
/**
* convert PDF file to JPG file.
*
* @param pdfFilePath
* @param destFolderPath
* @throws Exception
*/
public void convertPDFFileToJPGFile(String pdfFilePath, String destFolderPath) throws Exception {
System.out.println(“convertPDFFileToJPGFile : begin”);
if (pdfFilePath == null || pdfFilePath.length() == 0) {
throw new Exception(“convertPDFFileToJPGFile : pdfFilePath is null or empty”);
}
if (destFolderPath == null || destFolderPath.length() == 0) {
throw new Exception(“convertPDFFileToJPGFile : destFolderPath is null or empty”);
}
PDDocument document = null;
try {
File file = new File(pdfFilePath);
if (!file.exists()) {
throw new Exception(“convertJPGFileToPDFFile : this path not exists. [“ + file.getAbsolutePath() + “]”);
}
String fileName = file.getName();
if (fileName == null || fileName.length() == 0) {
throw new Exception(“convertJPGFileToPDFFile : fileName is null or empty. [“ + file.getAbsolutePath() + “]”);
}
String fileNameOnly = null;
int dotIndex = fileName.lastIndexOf(“.”);
if (dotIndex > -1) {
fileNameOnly = fileName.substring(0, dotIndex);
} else {
fileNameOnly = fileName;
}
if (fileNameOnly.indexOf(“.”) > -1) {
fileNameOnly = fileNameOnly.replace(“.”, “_”);
}
File destFolder = new File(destFolderPath);
if (!destFolder.exists()) {
destFolder.mkdirs();
}
document = PDDocument.load(file);
int pageCount = document.getNumberOfPages();
System.out.println(“pageCount : “ + pageCount);
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int i=0; i<pageCount; i++) {
int pageNum = i + 1;
BufferedImage imageObj = pdfRenderer.renderImageWithDPI(i, 100, ImageType.RGB);
String imageFileName = fileNameOnly + “-“ + pageNum + “.jpg”;
File outputfile = new File(destFolderPath + “/” + imageFileName);
ImageIO.write(imageObj, “jpg”, outputfile);
System.out.println(“output “ + pageNum + “/” + pageCount + ” : “ + outputfile.getAbsolutePath());
}
} catch (Exception e) {
throw e;
} finally {
try {
if (document != null) {
document.close();
}
} catch (Exception e) {}
}
System.out.println(“convertPDFFileToJPGFile : end”);
}
/**
* convert JPG file to PDF file.
*
* @param jpgsFolderPath
* @param resultFilePath
* @throws Exception
*/
public void convertJPGFileToPDFFile(String jpgsFolderPath, String resultFilePath) throws Exception {
System.out.println(“convertPDFFileToJPGFile : begin”);
if (jpgsFolderPath == null || jpgsFolderPath.length() == 0) {
throw new Exception(“convertPDFFileToJPGFile : jpgsFolderPath is null or empty”);
}
if (resultFilePath == null || resultFilePath.length() == 0) {
throw new Exception(“convertPDFFileToJPGFile : resultFilePath is null or empty”);
}
PDDocument document = null;
try {
File folder = new File(jpgsFolderPath);
if (!folder.exists()) {
folder.mkdirs();
}
if (!folder.isDirectory()) {
throw new Exception(“convertJPGFileToPDFFile : this path is not a folder. [“ + folder.getAbsolutePath() + “]”);
}
File[] fileArr = folder.listFiles();
int fileCount = 0;
if (fileArr != null) {
fileCount = fileArr.length;
}
if (fileCount == 0) {
throw new Exception(“convertJPGFileToPDFFile : fileCount == 0”);
}
sortFileArray(fileArr);
document = new PDDocument();
for (int i=0; i<fileCount; i++) {
File oneFile = fileArr[i];
if (oneFile == null || !oneFile.exists()) {
continue;
}
InputStream inputStream = null;
PDPageContentStream contentStream = null;
try {
inputStream = new FileInputStream(oneFile);
BufferedImage bufferedImage = ImageIO.read(inputStream);
float width = bufferedImage.getWidth();
float height = bufferedImage.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page);
PDImageXObject pdImage = PDImageXObject.createFromFile(oneFile.getAbsolutePath(), document);
contentStream = new PDPageContentStream(document, page);
// contentStream.drawImage(pdImage, 0, 0);
contentStream.drawImage(pdImage, 0, 0, width, height);
} catch (Exception e) {
throw e;
} finally {
try {
if (contentStream != null) {
contentStream.close();
}
} catch (Exception e) {}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e) {}
}
}
File resultFile = new File(resultFilePath);
if (resultFile.exists()) {
resultFile.delete();
}
String motherFolderPath = getMotherFolderPath(resultFile);
File motherFolder = new File(motherFolderPath);
if (!motherFolder.exists()) {
motherFolder.mkdirs();
}
document.save(resultFile.getAbsolutePath());
} catch (Exception e) {
throw e;
} finally {
try {
if (document != null) {
document.close();
}
} catch (Exception e) {}
}
System.out.println(“convertPDFFileToJPGFile : end”);
}
private String getMotherFolderPath(File fileObj) throws Exception {
if (fileObj == null) {
return “”;
}
String path = revisePath(fileObj.getAbsolutePath());
int lastSlashIdx = path.lastIndexOf(“/”);
if (lastSlashIdx < 0) {
throw new Exception(“getMotherFolderPath : this path is not valid. [“ + path + “]”);
}
String motherFolderPath = path.substring(0, lastSlashIdx);
return motherFolderPath;
}
private String revisePath(String path) {
if (path == null || path.length() == 0) {
return “”;
}
if (path.indexOf(“\\”) > -1) {
path = path.replace(“\\”, “/”);
}
while (path.indexOf(“//”) > -1) {
path = path.replace(“//”, “/”);
}
return path.trim();
}
private void sortFileArray(File[] fileArr) throws Exception {
if (fileArr == null) {
return;
}
if (fileArr.length < 2) {
return;
}
File file1 = null;
File file2 = null;
File tempFile = null;
int fileCount = fileArr.length;
for (int i=0; i<fileCount; i++) {
for (int k=i+1; k<fileCount; k++) {
file1 = fileArr[i];
file2 = fileArr[k];
if (checkShouldChangeOrder(file1.getName(), file2.getName())) {
tempFile = fileArr[i];
fileArr[i] = file2;
fileArr[k] = tempFile;
}
}
}
}
private boolean checkShouldChangeOrder(String firstStr, String nextStr) {
if (firstStr == null) {
firstStr = “”;
}
if (nextStr == null) {
nextStr = “”;
}
if (firstStr.length() > nextStr.length()) {
return true;
} else if (firstStr.length() < nextStr.length()) {
return false;
}
char ch1 = 0;
char ch2 = 0;
int len = firstStr.length();
for (int i=0; i<len; i++) {
ch1 = firstStr.charAt(i);
ch2 = nextStr.charAt(i);
if (ch1 == ch2) {
continue;
} else if (ch1 > ch2) {
return true;
} else if (ch1 < ch2) {
return false;
}
}
return false;
}
}