본문 바로가기

Infra/01.linux

[PDF 변환] wkhtmltopdf linux 서버 설치 방법 (내부망)

배경 : 내부망 내 운영하는 앱 내 PDF 출력 기능을 구현해달라는 요건이 있었다. 직접 PDF 화면을 만들어 적용하는 것도 있지만, 매우 운영하기 부적합하다. 그에 따른 다른 계열사 운영시 사용하는 wkhtmltopdf 라는 라이브러리를 직접 리눅스 서버에 설치하는 과정을 정리해두려 한다.

 

내용 : 

 

우선 가늠이 잘 안되어서, 사이트를 검색했다.

https://wkhtmltopdf.org/

 

wkhtmltopdf

What is it? wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely "headless" and do not require a display or display service. The

wkhtmltopdf.org

====

우선 제공해준 소스를 보니, 로컬 환경에서는 내 c: 에 설치한 윈도우상태에서 테스트하는 것을 기존에 사용한듯 하여 나도 동일하게 윈도우에 설치하여 테스트 한다

 

https://beautifulhill.tistory.com/22

 

wkhtmltopdf 사용하기 - 윈도우10

wkhtmltopdf는 html 페이지를 pdf로 다운받을 수 있는 프로그램이다. 1. OS에 맞게 다운로드한다. https://wkhtmltopdf.org/downloads.html wkhtmltopdf All downloads are currently hosted via Github releases, so you can browse for a speci

beautifulhill.tistory.com

- 윈도우의 경우 cmd 창에서

cd wkhtmltopdf위치\bin

wkhtmltopdf "다운로드 받고자 하는 페이지" "pdf 다운받을 위치"

 

출처 : https://beautifulhill.tistory.com/22

- 다운로드 됨

출처 : https://beautifulhill.tistory.com/22

 

*참고

wkhtmltopdf -h 

를 작성하면 여러 옵션들이 나온다.

 

난 안되네 쩝; ㅠㅠ

 

 

=====

제공해준 소스 1차 체크

 

파일 생성

Controller

1. 특정 화면에 대한 PDF 다운로드 용 메소드 셋팅

ex) 

 

	@RequestMapping("/testPdf")
	public void testReportDown(HttpServletRequest request, HttpServletResponse response, Model model, testVo testVo) throws Exception {
		testService.testReportDown(request, response, model, testVo);
	}

 

 

Service

1. 단건 PDF에 대한 pdf 파일 생성 정보 셋팅 후 실제 PDF 생성 Util에 만든 pdf 생성 상세 기능 실행

 

testPdfUtil

1. 다운로드 받을 경로 셋팅

2. wkhtmltopdf 실행 위한 설정 정보 셋팅

3. pdf 다은로드 관련 정보 셋팅 

 

파일 다운로드

1. controller 에서 다운로드 메서드 실행 --> service 실행 --> FileDownloadUtil 에 있는 downloadfile, downloadZipFile 두가지 형태로 분리하여 사용 가능

 

 

 

 

 

 

 

 

========

그리고 퍼플렉시티를 활용했다.

 

3. Spring Boot에서 사용하는 방법
Spring Boot에서 wkhtmltopdf를 사용하는 방법은 JSP와 유사하지만, Spring의 구조에 맞게 Controller와 Service를 분리하여 구현하는 것이 좋습니다.

Spring Boot 예시
PdfService.java

import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;

@Service
public class PdfService {

    public String generatePdf(String url, String filename) throws IOException, InterruptedException {
        String wkhtmltopdfPath = "/usr/local/bin/wkhtmltopdf";
        String savePath = "/tmp/" + filename;

        Process process = Runtime.getRuntime().exec(wkhtmltopdfPath + " " + url + " " + savePath);
        process.waitFor();

        return savePath;
    }
}

 

PdfController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class PdfController {

    @Autowired
    private PdfService pdfService;

    @GetMapping("/downloadPdf")
    public ResponseEntity<byte[]> downloadPdf() throws IOException, InterruptedException {
        String url = "http://example.com/page";
        String filename = "output.pdf";
        String filePath = pdfService.generatePdf(url, filename);

        File file = new File(filePath);
        byte[] bytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(bytes);
        fis.close();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        headers.add("Content-Type", "application/pdf");

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

 

이 예시에서는 wkhtmltopdf를 실행하여 PDF 파일을 생성하고, 생성된 PDF 파일을 클라이언트에 다운로드하도록 구현했습니다.

 

위 처럼하면, 특정 화면내 PDF 다운로드 기능을 쉽게 구현할 수 있을 것 으로 판단된다.

 

근데 내가 어드민에서 해야하는건 이게 아니라고 한다.

 

728x90