Skip to main content
 首页 » 编程设计

python之如何将weasyprint生成的PDF文件保存(存储)到指定目录

2024年10月01日7cloudgamer

我需要将由 weasyprint 生成的 pdf 文件放在某个指定的文件夹中,例如文件夹“my_project/pdf_files/ "

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

my_project/ 
 
----pdf_generator_app/ 
 
--------admin.py 
 
--------models.py 
 
--------views.py 
 
pdf_files/ 

目前我的 views.py

中有这个
def generate(student_id): 
    student = get_object_or_404(Student, application_id=student_id) 
    html = render_to_string('contract.html', {'student': student}) 
    response = HttpResponse(content_type='application/pdf') 
    response['Content-Disposition'] = 'filename="some_file.pdf"' 
    weasyprint.HTML(string=html).write_pdf('myfile.pdf',  
                                           presentational_hints=True, 
                                           stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + '/css/styles.css')]) 
    return response 

但此 View 不会将 pdf 文件存储到目录中。它只是在浏览器上显示文件。我需要将文件存储在目录 my_project/pdf_files/

请您参考如下方法:

我将输出写入二进制模式并且它有效。

dirname = os.path.dirname(__file__) 
 
 
def hello_pdf(): 
    # Make a PDF straight from HTML in a string. 
    html = render_template('template-1.html', name=name) 
 
    pdf = HTML(string=html).write_pdf() 
 
    if os.path.exists(dirname): 
 
        f = open(os.path.join(dirname, 'mypdf.pdf'), 'wb') 
        f.write(pdf)