在django 1.8中提供PDF错误



在django 1.8中,我有几个函数读取pdf文件并返回它们,并且使用reportlab生成pdf并返回它。在某些情况下,文件是正确的,但有时PDF被浏览器打开,就像它是html一样,更奇怪的是,PDF源显示在我的django基本模板中。在这种情况下,如果在出现错误后重新加载页面,则会提供pdf。

这是一个视图的代码:

fpdf = open (path, 'rb')
return HttpResponse (FileWrapper (fpdf), content_type = 'application/pdf')

,这是另一个的代码:

pdf = pisa.CreatePDF (StringIO.StringIO (html.encode ("UTF-8")), result)
if not pdf.err:
    response = HttpResponse (result.getvalue (), content_type = 'application / pdf')
    response ['Content-Disposition'] = 'attachment; filename =% S.pdf '% (doc.name.replace ("", "_"))
    return response
    #Return HttpResponse (result.getvalue (), content_type = 'application/pdf')

将PDF作为附件返回是我做的一个测试,看看是否解决了,因为期望的行为将是直接打开文件。不幸的是,即使这样,错误仍然发生。

改变这一行

response = HttpResponse (result.getvalue (), content_type = 'application / pdf')

到这一行

response = HttpResponse (result.getvalue (), content_type = 'application/octet-stream')

这将使文件被视为二进制文件,并下载给用户,而不是在浏览器中打开它。

如果您在浏览器中查看它,请遵循Igor pomaransky的建议,并通过执行以下操作删除content_type变量中的空格

改变这种情况Content_type = 'application/pdf'这个

content_type = 'application/pdf'

最新更新