python - 在 django 中使用 doraptor 生成 Pdf

标签 python django pdf

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

下面是我生成 pdf 的代码/ View

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'] 

那么为什么我会收到此异常值:强制转换为 Unicode:需要字符串或缓冲区,找到文件错误以及如何在 django 中将我获得的文件显示为 pdf ?

最佳答案

而不是这个-

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

尝试

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

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

关于python - 在 django 中使用 doraptor 生成 Pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22247595/

相关文章:

javascript - 什么会导致 html 和脚本在 for 循环的迭代中表现不同?

python - django queryset aggregation count 计数错误

python - 转换数据框以获得共同作者关系

python - 如何在 pandas 中多次旋转我的数据框,同时创建合并多个列的新列?

python - 在Python BeautifulSoup4中,如何提取这样的特殊文本

python - 将字典列表转换为 Pandas 数据框

django - 从 Django 访问 Neo4j 的最佳方式是什么?

python - 寻找有关如何将 PDF 转换为结构化格式的建议

c++ - 在 Cimg 上创建的图像在使用 GDI+ 保存时在 pdf 上显示不同,而在 pdf 上使用 jagPDF 创建

android - 如何在 webview 中加载 base64 字符串?