프로그래밍 일기/Python & Flask

Python html to pdf (render_template, pdfkit, wkhtmltopdf) 방법

MakeMe 2024. 5. 3. 16:01
반응형
pip install pdfkit
#window
choco install wkhtmltopdf

#linux ubuntu
sudo apt-get update
sudo apt-get install wkhtmltopdf

#mac
brew install Caskroom/cask/wkhtmltopdf

자신의 운영체제에 맞는 wkhtmltopdf 를 설치해야 다운로드 가능합니다.

<form id="downloadForm" action="/api/v1/license/certificate/download" method="post" style="display: none;">
    <input type="hidden" name="license_id" id="license_id">
    <button type="submit" id="downloadButton">Download PDF</button>
</form>

<script>
function downloadCertificate(id) {
    document.getElementById("license_id").value = id;
    document.getElementById("downloadForm").submit();
}
</script>

ajax통신으로는 파일다운로드가 불가능하여 form태그를 이용해야 합니다.

import pdfkit
import os

@api_bp.route('/license/certificate/download', methods=["POST"])
def download_license_pdf():
    try:
        license_info = {
            'customer_name': 'John Doe',
            'license_number': '1234567890',
            # 기타 라이선스 정보...
        }
        # HTML 템플릿 렌더링
        rendered_html = render_template('certificate.html', license_info=license_info)

        # HTML을 PDF로 변환
        fileName = 'license.pdf'
        pdfkit.from_string(rendered_html, fileName)
        pdfDownload = open(fileName, 'rb').read()
        os.remove(fileName)

        return Response(
            pdfDownload,
            mimetype="application/pdf",
            headers={
                "Content-disposition": "attachment; filename=" + fileName,
                "Content-type": "application/force-download"
            }
        )
    
    except Exception as e:
        return f"Error occurred: {str(e)}", 500

파이썬 코드는 위와 같이 작성합니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>License Certificate</title>
</head>
<body>
    <h1>License Certificate</h1>
    <p>Customer Name: {{ license_info.customer_name }}</p>
    <p>License Number: {{ license_info.license_number }}</p>
    <!-- 기타 라이선스 정보 출력 -->
</body>
</html>

render_template예제 입니다.

반응형