简体   繁体   中英

How to save (store) PDF file generated by weasyprint to specified directory?

I need my pdf files that is generated by weasyprint to be some specified folder, for example in the folder " my_project/pdf_files/ "

NOTE: I am using django framework for my project. And here is the structure of project.

my_project/

----pdf_generator_app/

--------admin.py

--------models.py

--------views.py

pdf_files/

Currently I have this in my 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

But this view does not store pdf file to a directory. It simply show file on browser. I need the file to be stored in the directory my_project/pdf_files/

I wrote the out put to the binary mode and it worked.

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)

Oppsite to me, I got the PDF file but couldn't view it on my browser. Replace 'myfile.pdf' to an absolulte path and check if if generates the pdf file. It work for me in my condition.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM