Django PDF:如何在浏览器中显示进度?

时间:2012-10-10 02:40:06

标签: python django http pdf reportlab

在加载整个文件之前,文件不会显示。如何在浏览器中显示进度?

from io import BytesIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse

def some_view(request):
     # Create the HttpResponse object with the appropriate PDF headers.
     response = HttpResponse(mimetype='application/pdf')
     response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

     buffer = BytesIO()

     # Create the PDF object, using the BytesIO object as its "file."
     p = canvas.Canvas(buffer)

     p.drawString(**, **, "Hello world.") # draw pdf, size > 10M

     # Close the PDF object cleanly.
     p.showPage()
     p.save()

     # Get the value of the BytesIO buffer and write it to the response.
     pdf = buffer.getvalue()
     buffer.close()
     response.write(pdf)
     return response

1 个答案:

答案 0 :(得分:2)

嗯,在你的例子中,我认为这将非常简单(并且几乎是即时的)。您只需打印/返回drawStringshowPage等的进度指示器。假设您生成的实际PDF更为复杂,您可以使用setProgressCallBack方法{ {1}}课程。当然,这需要您使用reportlab platypus引擎。

有一些注意的方法/属性(请参阅注释),假设您有一个自定义模板类覆盖BaseDocTemplate

BaseDocTemplate

以下是更多值(您可以在from reportlab.platypus import BaseDocTemplate class MyDocTemplate(BaseDocTemplate): """Override BaseDocTemplate for "progress bar" information""" def __init__(self, *args, **kwargs): BaseDocTemplate.__init__(self, *args, **kwargs) # BaseDocTemplate keeps a "progress" dictionary for its own # internal use, which is updated as various drawings are done. # This directs reportlab to use your own custom method # as the "callback" function when updates are made. # Notice the use of the __ prefix for the method, which ensures # that it calls *your* custom class's method, and not the default. # Should match the signature of the original callback: (self, type, value) self.setProgressCallBack(self.__onProgress) def __onProgress(self, prog_type, value): """Progress monitoring""" # One example "progress type" is the "PAGE" key. Which indicates # which page reportlab is working on. if prog_type == "PAGE": print "Drawing page: %s" % value elif prog_type == "FINISHED": print "Drawing complete!" 中看到代码):

reportlab.platypus.doctemplate