2014-03-07 75 views
1

我有一個Django應用程序,其中我有一個頁面顯示一些數據和圖像,現在我需要將該HTML頁面轉換爲pdf,所以我試圖使用Docraptor在django中生成pdf與docraptor

所以下面是我的代碼/視圖生成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'] 

那麼,爲什麼我會得到這個Exception Value: coercing to Unicode: need string or buffer, file found錯誤,以及如何顯示我在django中的PDF文件?

回答

2

取而代之的是 -

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

嘗試

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

你傳入文件對象,而功能需求文件路徑/文件名。

+0

正確使用相同的工作 –

+0

@ shivakrishna:這是Gr8! – anuragal

+0

@shivakrishna - 你能否接受答案,如果它的工作! – anuragal