티스토리 뷰

 

PDF 파일의 내부 데이터를 핸들링할 일이 생겼다.

 

처음에 든 생각은 PDF 파일을 XML 형태로 바꾸면 되지 않을까?라고 생각을 했는데,

 

XML 형태든 JSON 형태든 파일 형식을 바꿔버리면, 표나 이미지 글자 크기 등이 제대로 반영이 되지 않을 것 같았다.

 

물론할 수는 있겠지만 아마 솔루션 개발급 공수가 들어가지 않을까? 란 견적이 서서 다른 방법이 없나 찾아봤다.

 

찾다보니 가장 그럴듯한게 HTML로 변환 하는 것이었다.

 

PDF box와 css box를 이용하는 방법인데 라이브러리를 쓰면 되다보니 그렇게 어렵지 않다.

 

하나씩 해보자.

코드

gradle

# commons-io를 낮은 버전을 쓰고 있으면 버전업해야함, 안쓰고 있으면 필요 x
implementation 'commons-io:commons-io:2.11.0' 
implementation 'org.apache.pdfbox:pdfbox:2.0.13'
implementation 'org.apache.pdfbox:pdfbox-tools:2.0.13'
implementation 'net.sf.cssbox:pdf2dom:2.0.1'

변환 매서드

public String pdfToHtml(File file) {
	String html = "";
    try (InputStream inputStream = Files.newInputStream(file.toPath())) {
        PDDocument document = PDDocument.load(inputStream);
        PDFDomTree parser = new PDFDomTree();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (PrintWriter output = new PrintWriter(new OutputStreamWriter(baos, StandardCharsets.UTF_8), true)) {
            parser.writeText(document, output);
            html = new String(baos.toByteArray(), StandardCharsets.UTF_8);
        }
    } catch(Exception e) {
    	// 에러처리는 상황에 맞게
        return null;
    }
    return html;
}

text를 그대로 복붙해서 HTML 파일을 만들거나, Postman으로 테스트를 해볼 수 있다.

 

Postman 테스트를 해보자.

 

간단한 Spring multipartfile을 전달받는 POST API를 만들었다.

@PostMapping("/converter/pdf-html")
public String pdf(@ModelAttribute MultipartFileRequestDto multipartFileRequestDto) {
    File tempFile = null;
    MultipartFile multipartFile = multipartFileRequestDto.getMultipartFile();
    try {
        tempFile = File.createTempFile("temp_", multipartFile.getOriginalFilename());
        FileCopyUtils.copy(multipartFile.getBytes(), tempFile);
    } catch (IOException e) {
        if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
            System.out.println("error");
        }
    }
    tempFile.delete(); // return 값을 사용하지 않았다고, 경고가 뜨는데 지우긴해야 함
    
    return pdfToHtml(tempFile);
}

Postman에서 요청 데이터를 전달하고, 응답값을 보면 그냥 plain/text다.

 

preview를 보면 제대로 HTML 형식으로 출력되는 걸 확인할 수 있다.

 

결과

 

 

출처 : https://danielangel22.medium.com/converting-pdf-to-html-in-java-a-simple-guide-da4a979f5979

 

출처의 코드는 자바 1.8보다 높은 버전이라 코드 수정이 조금 있었음.

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함