Java에서 Hwp를 Image로 변환하기 2부 (Java + Python)

주의

이 문건은 과거 Hexo 블로그 (2019-01-25) 에서 이동된 문서입니다.

시간이 지남에 따라 최신 기술과 다를 수 있으니 주의 바랍니다.



만약 1부를 안 보신 분이 있다면 이곳 1부 포스팅을 참고하자.
실제 구현 전 설치하거나 구성해야 할 것들이 있는데 이는 1부 포스팅의 참고 링크를 확인하자.

1부에 이어서..

이번엔 바로 적용한 코드를 확인해보자.


1. Hwp to XHtml

아래의 메서드로 구현을 하였다.

private String changeHwp2Xhtml(String uniqueId, String targetHwpPath) {
	String outputPath = "/home/dev/sample/temp/img"; //Xhtml이 저장될 디렉토리
        StringBuilder runCommand = new StringBuilder(); //pyhwp를 실행할 커맨더를 조립할 String Builder 객체

        runCommand.append("hwp5html --output=" + outputPath + " " + targetHwpPath); //pyhwp를 실행하는 코드를 조립

        try {
            Files.createDirectories(Paths.get(outputPath)); //Output 경로를 생성해 준다.

            //명령어를 수행
            Process process = Runtime.getRuntime().exec(runCommand.toString());
            int exitStatus = process.waitFor();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader (process.getInputStream()));

            String currentLine;
            StringBuilder stringBuilder = new StringBuilder(exitStatus==0?"SUCCESS:":"ERROR:");
            currentLine= bufferedReader.readLine();
            while(currentLine !=null) {
                stringBuilder.append(currentLine);
                currentLine = bufferedReader.readLine();
            }

            //변환에 실패한 경우 예외 처리
            if (stringBuilder.toString().equals("ERROR:")) { throw new Hwp2XHtmlChagneException(this, "Change fail hwp to xhtml. Command result is Error."); }
        }
        catch(Exception e) {  } //알맞는 예외 처리 진행
        return outputPath + "/index.xhtml";
}

위의 메서드는 hwp를 xhtml로 변환 후 변환된 경로를 반환하는 메서드이다.
자세한 것은 코드를 참고하자.


2. Xhtml to Pdf

이것도 아래의 메서드를 참고하면…

private String changeXhtml2Pdf(String inputHtmlPath, String uniqueId) {
        //파일명은 temp.pdf로 맞춰준다.
        String outputPath = "/home/dev/sample/temp/pdf" + "/" + getPathPart4DateStr() + "/" + uniqueId + "/temp.pdf";
        Pdf pdf = new Pdf();
        pdf.addPageFromUrl(inputHtmlPath);
        try { pdf.saveAs(outputPath); } //Html을 pdf로 변환 처리하는 로직
        catch (IOException e) { throw  new Xhtml2PdfChangeException(this, "Change fail xhtml to pdf. IOException message = " + e.getMessage()); }
        catch (InterruptedException e) { throw  new Xhtml2PdfChangeException(this, "Change fail xhtml to pdf. InterruptedException message = " + e.getMessage()); }
        return outputPath;
    }

이 메서드도 변환 후 경로를 반환하는 메서드이다.
여기서 사용된 Pdf의 경우 WKHtmlToPdf 설치하기 포스팅의 번외 1편을 참고하자.


3. Pdf to Image

바로 코드를 보자면…

private List<String> conversionPdf2Img(InputStream is, String uniqueId) {
        List<String> savedImgList = new ArrayList<>(); //저장된 이미지 경로를 저장하는 List 객체
        try {
            PDDocument pdfDoc = PDDocument.load(is); //Document 생성
            PDFRenderer pdfRenderer = new PDFRenderer(pdfDoc);

            String resultImgPath = "/home/dev/sample/result/"; //이미지가 저장될 경로
            Files.createDirectories(Paths.get(resultImgPath)); //PDF 2 Img에서는 경로가 없는 경우 이미지 파일이 생성이 안되기 때문에 디렉토리를 만들어준다.

            //순회하며 이미지로 변환 처리
            for (int i=0; i<pdfDoc.getPages().getCount(); i++) {
                String imgFileName = resultImgPath + "/" + i + ".png";

		//DPI 설정
                BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB);

                // 이미지로 만든다.
                ImageIOUtil.writeImage(bim, imgFileName , 300);

                //저장 완료된 이미지를 list에 추가한다.
                savedImgList.add(makeDownloadUrl4Uuid(imgFileName));
            }
            pdfDoc.close(); //모두 사용한 PDF 문서는 닫는다.
        }
        catch (FileNotFoundException e) { throw new PdfNotFoundException(this, "Pdf file not found. exception message = " + e.getMessage() ); }
        catch (IOException e) { throw new Pdf2ImgChangeException(this, "Change fail pdf to image. IOException message = " + e.getMessage() ); }
        return savedImgList;
    }

이곳에서는 PDF를 이미지로 변환하기 위해 PDFbox 를 사용하였다.
이것과 관련해서는 Java에서 PDF를 이미지로 변환하기 포스팅을 참고하자.
참고로 저 포스팅에 위에 공개한 메서드에 대해 자세한 설명이 되어 있다.


결론

이제 1부와 이번 포스팅을 통해서 hwp를 이미지로 변환하는 과정에 대해 알아보았다.
물론 완벽하게 처리된 것은 아니지만… 나름 최선의 방법을 찾은 것 같다.
혹시 나와 같은 고민을 하신 분들에게 도움이 되길 바라면서…
만약 더 좋은 방법이 있다면 알려주시면 감사하겠다.


Written by@MHLab
로또는 흑우집합소 🎲
와인관리, 시음노트, 셀러관리는 마와셀 🥂

🫥 My Service|  📜 Contact|  💻 GitHub