如何使用Django输出PDF?

时间:2014-01-11 09:38:47

标签: python django pdf django-views pdf-generation

我指的是这个https://docs.djangoproject.com/en/dev/howto/outputting-pdf/用于生成pdf与reportlab。

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

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

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    logging.debug('-----p---')
    logging.debug(p)
    p.showPage()
    p.save()
    return response

如果我在myapp中添加此reportlab文件夹,则会出现此错误:

ViewDoesNotExist at /aps/print-pdf/
Could not import myapp.views. Error was: No module named reportlab

如果我将此reportlab文件夹放在myapp文件夹之外,则会出现此错误:

ViewDoesNotExist at /aps/print-pdf/
Tried some_view in module myapp.views. Error was: 'HardenedModulesHook' object has no attribute '_files'

这有什么问题?请帮忙。

1 个答案:

答案 0 :(得分:0)

  1. 检查myapp是否在您的设置中.STSTALLED_APPS?
  2. 检查reportlab已在python环境中成功安装,使用pip freeze或运行python shell以查看import reportlab是否可以正常工作