【问题标题】:How to save (store) PDF file generated by weasyprint to specified directory?如何将weasyprint生成的PDF文件保存(存储)到指定目录?
【发布时间】:2020-09-26 20:49:36
【问题描述】:

我需要 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/

【问题讨论】:

  • 如果我把response['Content-Disposition'] = 'filename="some_file.pdf"'换成response['Content-Disposition'] = 'attachment; filename="some_file.pdf"'就直接下载了

标签: python django weasyprint


【解决方案1】:

我将输出写入二进制模式,它工作正常。

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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-06-14
        • 1970-01-01
        • 1970-01-01
        • 2021-01-28
        • 2017-02-01
        • 1970-01-01
        • 2016-08-21
        • 2021-08-31
        • 1970-01-01
        相关资源
        最近更新 更多