Python 在django中使用docraptor生成Pdf

Python 在django中使用docraptor生成Pdf,python,django,pdf,Python,Django,Pdf,我有一个django应用程序,其中有一个页面显示一些数据和图像,现在我需要将HTML页面转换为pdf,所以我正在尝试使用 下面是我生成pdf的代码/视图 def generate_report_pdf(request, user_id): site = Site.objects.get(id=settings.SITE_ID) url = site.domain + reverse('overview', args=[user_id,]) docraptor = DocR

我有一个django应用程序,其中有一个页面显示一些数据和图像,现在我需要将HTML页面转换为pdf,所以我正在尝试使用

下面是我生成pdf的代码/视图

def generate_report_pdf(request, user_id):
    site = Site.objects.get(id=settings.SITE_ID)
    url = site.domain + reverse('overview', args=[user_id,])
    docraptor = DocRaptor(settings.DOCRAPTOR_API_KEY)
    with open("test.pdf", "wb") as f:
        f.write(docraptor.create({
            'document_url': url,
            'test': True,
            'document_type':'pdf',
        }).content)

    print f,f.name,">>>>>>>>>>>>"
    print type(f),">>>>>>>>>>>>"
    print dir(f),">>>>>>>>>>>>"
    file = open(f, 'r').read()
    return HttpResponse(file, mimetype='application/pdf')
输出:

Exception Type: TypeError
Exception Value:    coercing to Unicode: need string or buffer, file found
此错误发生在
file=open(f,'r')行。read()

以上打印出来的语句是

<closed file 'test.pdf', mode 'wb' at 0x7faea05a59c0> test.pdf >>>>>>>>>>>>
<type 'file'> >>>>>>>>>>>>
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] 
test.pdf>>>>>>>
>>>>>>>>>>>>
“UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU“,”、”、“、”、“、”、“、”子类钩子“、”关闭“、”编码“、”错误“、”文件号“、”刷新“、”isatty“、”模式“、”名称“、”换行“、”next、read、readinto、readline、readlines、seek、softspace、tell、truncate、write、writelines、xreadlines']
那么,为什么我会得到这个
异常值:强制使用Unicode:需要字符串或缓冲区,找到文件
错误,以及如何在django中将我得到的文件显示为pdf?

而不是这个-

file = open(f, 'r').read()
试一试

您正在传递文件对象,而函数需要文件路径/名称

file = open(f.name, 'r').read()