0

I would like to realize the following with twisted web:

  1. The user clicks on a link on a page
  2. This is bring the user to a temporary page where the user is informed that the PDF is generated
  3. When the PDF generation is finished, the download starts automatically.

This is my example code:

from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.server import NOT_DONE_YET

class DownloadResource(Resource):
    isLeaf = True

    def render_GET(self, request: Resource):
        # Start generating the PDF file in the background
        reactor.callInThread(generate_pdf, request)
        request.write(b"<html><body>Please wait while the PDF file is generated and download will start soon...</body></html>")
        return NOT_DONE_YET

def generate_pdf(request: Resource):
    # Generate the PDF data
    # for the time being, just open it from the disk.
    # the real application will generate it.
    filename = r'/path/to/pdf' 
    with open(filename, 'rb') as f:
        pdf_data = f.read()

    # Serve the PDF data
    request.setHeader(b"content-type", b"application/pdf")
    request.setHeader(b"content-length", str(len(pdf_data)).encode('utf-8'))
    request.write(pdf_data)
    request.finish()

resource = DownloadResource()

This works almost ok, the point is that the pdf data are written as bytes next to the text message. Something like this: Please wait while the PDF file is generated and download will start soon...%PDF-1.4 %ª«¬­ 1 0 obj << /Title....

Instead I would like the pdf file to be downloaded. Ideally I would need a kind of send_file. Does it exist?

Can you help me in solving this issue?

toto
  • 110
  • 1
  • 6

0 Answers0