How to create PDF filesLink to this heading

이 문서에서는 Django 보기를 사용하여 PDF 파일을 동적으로 출력하는 방법을 설명합니다. 이는 우수한 오픈 소스 ReportLab_Python PDF 라이브러리를 통해 가능합니다.

PDF 파일을 동적으로 생성할 수 있는 이점은 사용자나 컨텐츠의 다양한 용도로 사용자 정의된 PDF를 생성할 수 있다는 것입니다.

예를 들어, Django는 kusports.com_에서 3월 Madness 대회에 참가하는 사람들을 위해 PDF 파일로 사용자 정의되고 프린터 친화적인 NCAA 토너먼트 브래킷을 생성하는 데 사용되었습니다.

ReportLab을 설치합니다.Link to this heading

ReportLab 라이브러리는 PyPI에서 사용할 수 있습니다. 사용자 가이드(PDF 파일)도 다운로드할 수 있습니다. “pip”로 ReportLab을 설치할 수 있습니다.

Linux / macOS

Shell
$ python -m pip install reportlab

Windows

Windows
...\> py -m pip install reportlab

Python 대화형 인터프리터를 사용하여 설치를 테스트합니다.

Code
>>> import reportlab

해당 명령으로 인해 오류가 발생하지 않으면 설치가 작동했습니다.

당신의 견해를 쓰시오.Link to this heading

Django를 사용하여 PDF를 동적으로 생성하기 위한 핵심은 ReportLab API가 파일과 유사한 개체에 대해 작동하고 Django의 :class:’~django.the’ 입니다.파일 응답’ 개체는 파일 유사 개체를 수락합니다.

다음은 “Hello World”의 예입니다.

Code
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def some_view(request):
    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

코드와 코멘트는 자명해야 하지만 몇 가지 사항은 언급할 가치가 있습니다.

  • 응답은 파일 이름 확장자에 따라 자동으로 MIME 유형:mimtype:’application/pdf’를 설정합니다. 이것은 브라우저에게 문서가 HTML 파일이나 일반적인 :mimetype:’application/octet-stream’ 바이너리 콘텐츠가 아닌 PDF 파일임을 알려줍니다.

  • When as_attachment=True is passed to FileResponse, it sets the appropriate Content-Disposition header and that tells web browsers to pop-up a dialog box prompting/confirming how to handle the document even if a default is set on the machine. If the as_attachment parameter is omitted, browsers will handle the PDF using whatever program/plugin they’ve been configured to use for PDFs.

  • 임의의 “파일 이름” 매개 변수를 제공할 수 있습니다. 브라우저가 “다른 이름으로 저장…”에서 사용합니다.” 대화 상자입니다.

  • ReportLab API에 연결할 수 있습니다. “캔버스”에 대한 첫 번째 주장과 같은 완충장치가 통과되었습니다.캔버스’는 :class에 제공할 수 있습니다.’~django.the’ 입니다.파일 응답 클래스입니다.

  • 이후의 모든 PDF 생성 방법은 “버퍼”가 아닌 PDF 객체(이 경우 “p”)로 호출됩니다.

  • 마지막으로 PDF 파일로 ``쇼 페이지”와 “저장(save)”을 부르는 것이 중요합니다.

다른 포맷Link to this heading

이러한 예에서는 PDF에 특정한 것이 많지 않으며 단지 “보고서 실험실”을 사용한 일부입니다. 유사한 기술을 사용하여 Python 라이브러리를 찾을 수 있는 임의 형식을 생성할 수 있습니다. 또한 다른 예와 텍스트 기반 형식을 생성할 때 사용할 수 있는 몇 가지 기법은 :doc:’/how to/outputing-csv’를 참조하십시오.