Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

python - Generate PDF of Protected Django Webpage with Attachments

So I'm trying to generate a PDF of a view that I have in a django web application. This view is protected, meaning the user has to be logged in and have specific permission to view the page. I also have some attachments (stored in the database as FileFields) that I would like to append to the end of the PDF.

I've read most of the posts I could find on how to generate PDFs from a webpage using pdfkit or reportlab, but all of them fail for me for some reason or another.

Currently, the closest I've gotten is successfully generating a PDF of the page using pdfkit, but this requires me to remove the restrictions that require the user to be logged in and have page permissions, which really isn't an option long term. I found a couple posts that discuss printing pdfs on protected pages and providing login information, but I couldn't get any of that to work.

I haven't found anything on how to include attachments, and don't really know where to start with that.

I'm more than happy to update this question with more information or snippets of code if need be, but there's quite a few moving parts here and I don't want to flood people with useless information. Let me know if there's any other information I should provide, and thanks in advance for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I got it working! Through a combination of PyPDF2 and pdfkit, I got this to work pretty simply. It works on protected pages because django takes care of getting the complete html as a string, which I just pass to pdfkit. It also supports appending attachments, but I doubt (though I haven't tested) that it works with anything other than pdfs.

from django.template.loader import get_template
from PyPDF2 import PdfFileWriter, PdfFileReader
import pdfkit

def append_pdf(pdf, output):
    [output.addPage(pdf.getPage(page_num)) for page_num in range(pdf.numPages)]


def render_to_pdf():
    t = get_template('app/template.html')
    c = {'context_data': context_data}

    html = t.render(c)
    pdfkit.from_string(html, 'path/to/file.pdf')

    output = PdfFileWriter()
    append_pdf(PdfFileReader(open('path/to/file.pdf', "rb")), output)

    attaches = Attachment.objects.all()

    for attach in attaches:
        append_pdf(PdfFileReader(open(attach.file.path, "rb")), output)

    output.write(open('path/to/file_with_attachments.pdf', "wb"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...