如何将由weasyprint生成的PDF文件保存到指定目录?

8

我需要将由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

但这个视图并不会将PDF文件存储到目录中,它只是在浏览器上显示文件。我需要将文件存储在目录my_project/pdf_files/中。


2
如果我将 response['Content-Disposition'] = 'filename="some_file.pdf"' 替换为 **response['Content-Disposition'] = 'attachment; filename="some_file.pdf"'**,文件将直接被下载。 - Kholdarbekov
3个回答

4
我将输出写入二进制模式,它起作用了。
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)

1

与我相反,我得到了PDF文件,但无法在浏览器中查看。 将“myfile.pdf”替换为绝对路径,并检查是否生成PDF文件。在我的情况下,它有效。


0

您可以将文件名作为参数传递,它将把PDF存储为文件:

HTML(string=html).write_pdf('out.pdf')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接