2017-09-02 76 views
0

Django的視圖中的多個PDF當用戶點擊下載按鈕,我想生成多個PDF 目前我只能生成一個PDF生成與Weasyprint

我想是從Django的視圖生成兩個PDF當用戶點擊下載按鈕與weasyprint。

下面的代碼只生成一個PDF

def get(self, *args, **kwargs): 
    obj = self.get_object() 
    html_result = super(GenerateInvoicePDFView, self).get(*args, 
    **kwargs) 
    response = HttpResponse(content_type='application/pdf') 
    response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % 
    obj.name 
    weasyprint.HTML(string= html_result.getvalue()).write_pdf(response) 
    return response 

這種反應應該產生兩個PDF,這可能嗎?請幫忙謝謝

+1

您可以創建歸檔或者多頁的PDF文件,但響應 –

+0

可能的複製沒有辦法回報多文件[用單個動作下載多個文件](https://stackoverflow.com/questions/2339440/download-multiple-files-with-a-single-action) – Pythonist

回答

0

你不能在響應中返回多個文件。我看到的唯一解決方案是將它們壓縮,通過電子郵件發送給用戶,或創建兩個單獨的下載按鈕。

如何:

觀點:

def get(self, *args, **kwargs): 
    if 'file-1' in self.request.GET: 
     obj = self.get_object(file='file-1') 
    else: # I assume you always want to download some file 
     obj = self.get_object(file='file-2') 

    html_result = super(GenerateInvoicePDFView, self).get(*args, 
    **kwargs) 
    response = HttpResponse(content_type='application/pdf') 
    response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % 
    obj.name 
    weasyprint.HTML(string= html_result.getvalue()).write_pdf(response) 
    return response 

模板:

<form action="" method="get"> 
    {{ form }} 
    <input type="submit" name="file-1" value="Download file 1" /> 
    <input type="submit" name="file-2" value="Download file 2" /> 
</form> 
+0

噢!我不能讓他們都單擊下載 –

+0

那麼哪種方法最適合您?將這兩個PDF合併成一個,壓縮或通過電子郵件發送它們? – Pythonist

+0

我想讓他們兩個下載! –