JAVA에서 HTML을 PDF 파일로 변환 및 다운로드하는 방법

wkhtmltopdf

웹 페이지 URL의 HTML, javascript를 해석하여 PDF 파일로 변환하는 실행파일입니다.
jquery는 PDF로 변환되지 않고, javascript로 그린 화면만 정상 변환됩니다.

wkhtmltopdf 설치 방법

https://wkhtmltopdf.org/downloads.html
윈도우 exe, 리눅스 rpm 등 OS에 맞는 설치파일로 wkhtmltopdf 실행파일을 설치합니다.

rpm 파일 설치

yum localinstall 파일명.rpm

리눅스 서버의 경우, wget URL 명령어로 rpm 파일을 다운받고 yum 명령어로 설치하면 됩니다.

리눅스 wkhtmltopdf 설치 경로

/usr/local/bin

wkhtmltopdf 사용법

wkhtmltopdf "HTML URL" "다운경로/파일명.pdf"

java에서 Process 객체로 운영체제 프로세스 생성 후 위 명령어를 실행하면,
HTML URL의 내용으로 PDF 파일이 만들어집니다.

javascript가 아니기 때문에, 크로스도메인 걸리는 이미지가 포함된 HTML도 PDF 변환 가능합니다.
PDF 사이즈로 조정되어 HTML과 완전히 동일하지 않을 수 있으나 대부분 깔끔하게 출력되는 것 같습니다.

HTML PDF 다운로드 예시

@GetMapping("/downloadFile")
public ResponseEntity<Resource> downloadFile(@RequestParam Map<String, Object> param, HttpServletRequest req) throws Exception {

    String pdfPath = "/data/upload";
    String pdfFilePath = pdfPath + File.separator + param.get("download_id") + ".pdf";

    File file = new File(pdfFilePath);
    if(file.createNewFile()) {
        logger.info("============== make file ==============");
    } else {
        logger.info("============== no make file ==============");
    }

    String wkhtmltopdfPath = "wkhtmltopdf";
    String host = "http://IP:포트";
    String cmd = wkhtmltopdfPath + " --no-stop-slow-scripts --enable-javascript --debug-javascript " + host + "/getDownloadData?download_id="
            + param.get("download_id") + " " + pdfFilePath;

    logger.info("cmd :: " + cmd);


    // 운영체제 프로세스 생성하고 PDF 파일 생성 명령어 실행
    Process process = Runtime.getRuntime().exec(cmd);
    process.waitFor();

    Path path = Paths.get(pdfFilePath);
    Files.readAllBytes(path);

    String contentType = Files.probeContentType(path);
    
    // header를 통해서 다운로드 되는 파일의 정보를 설정합니다.
    HttpHeaders headers = new HttpHeaders();
    headers.setContentDisposition(ContentDisposition.builder("attachment")
            .filename("다운로드.pdf", StandardCharsets.UTF_8)
            .build());

    headers.add(HttpHeaders.CONTENT_TYPE, contentType);

    Resource resource = new InputStreamResource(Files.newInputStream(path));

    return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}

리눅스 서버에 설치된 wkhtmltopdf를 사용하여 HTML을 PDF 파일로 생성하는 Controller 예시입니다.
Spring ResponseEntity를 사용하여 PDF 파일을 다운로드합니다.

Leave a comment