首页 > 解决方案 > 如何将 Django 中生成的 PDF 文件保存到我的项目中的指定目录?

问题描述

我需要将使用 xhtml2pdf 库生成的 pdf 文件保存/存储在我的项目文件夹中的某个指定目录中,例如文件夹“generate_pdf/media/”

注意:我正在为我的项目使用 django 框架。这是项目的结构。

 generate_pdf/
    -----generate_pdf/
    -----generate_pdf_app/
         --admin.py
         ---models.py
         ---views.py
    -----media/

这是我当前的视图.py

    from django.shortcuts import render 
    from io import BytesIO
    from django.http import HttpResponse
    from django.views import View
    from django.template.loader import get_template
    
    from xhtml2pdf import pisa
    
    def render_to_pdf(template_src, context_dict={}):  # this function renders html template to a PDF.
        template = get_template(template_src)
        html  = template.render(context_dict)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        if not pdf.err:
            return HttpResponse(result.getvalue(), content_type='application/pdf')
        return None
    
    
    context = {
            "first_name": "Jhon",
            "last_name": "Doe",
            "city": "London",
            "phone": "1234567890",
            "email": "jhon@mail.com",
        }
    
    def render_html(self, *args, **kwargs): # here i'm passing the template into this function, which get triggered on click of button 
        pdf = render_to_pdf('pdf_template.html', context)
        return HttpResponse(pdf, content_type='application/pdf')
    
    def download_pdf(self, *args, **kwargs): # I want this function to get triggered that will save the generated PDF in media directory. On click of button event. 
        pdf = render_to_pdf('app/pdf_template.html', context)

提前致谢!!

标签: pythondjango

解决方案


推荐阅读