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

2024. 5. 3. 16:01·프로그래밍 일기/Python & Flask
반응형
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예제 입니다.

반응형
저작자표시 (새창열림)

'프로그래밍 일기 > Python & Flask' 카테고리의 다른 글

Flask 보안 공격Cross-Site Scripting(XSS) 웹 취약점의 대응방안  (0) 2025.10.22
Python Flask 게시판 CRUD 웹 프로젝트 구현, 기본 구조 이해  (0) 2024.03.05
python flask 폴더 구조 및 __init__.py  (0) 2024.03.05
'프로그래밍 일기/Python & Flask' 카테고리의 다른 글
  • Flask 보안 공격Cross-Site Scripting(XSS) 웹 취약점의 대응방안
  • Python Flask 게시판 CRUD 웹 프로젝트 구현, 기본 구조 이해
  • python flask 폴더 구조 및 __init__.py
MakeMe
MakeMe
제가 포스팅한 글 중 잘못된 부분이 있으면 알려주세요!
  • MakeMe
    Developer blog
    MakeMe
    • 모든 글 (72)
      • 프로그래밍 일기 (58)
        • Java & Spring (21)
        • Python & Flask (4)
        • Linux (12)
        • Front-End (10)
        • DB & SQL (6)
        • Git (3)
        • IDE (2)
      • 자격증 (7)
        • 정보처리기능사 (2)
        • SQLD (1)
        • SW개발_L5 (1)
        • AWS (3)
      • 독립일기 (7)
        • 중소기업청년대출 (7)
  • 인기 글

  • 태그

    중기청후기
    DB
    중기청필수서류
    자바환경변수
    자바
    Vue
    psql
    xss 취약점
    java
    건강보험자격득실확인서
    Spring
    nuxt3
    AWS
    xss공격방어
    인텔리제이
    IntelliJ
    스프링부트
    중소기업청년대출
    nuxt
    중기청서류
    스프링
    DBeaver
    MYSQL
    넉스트
    중기청필요서류
    xss쿠키
    flask 세팅
    고용보험내역서
    springboot
    flask
  • hELLO· Designed By정상우.v4.10.1
MakeMe
Python html to pdf (render_template, pdfkit, wkhtmltopdf) 방법
상단으로

티스토리툴바