【问题标题】:Generating Multiple Documents (Python TempFile Module)生成多个文档(Python TempFile 模块)
【发布时间】:2021-09-29 10:28:06
【问题描述】:

我目前正在尝试使用我的网络应用程序打印财务报告 - 这需要通过单击按钮来实现。但是,当我单击该按钮时,该应用程序仅打印 1 个文档(第一个文档) p>

这是我目前尝试过的:

import tempfile
def printReports(request , reports_pk):
    pkForm = get_object_or_404(SettingsClass , pk=reports_pk)

    complexName = pkForm.Complex
    if pkForm.Trial_balance_Year_To_Date == True:
        ### Printing Trial Balance PDF
        response = HttpResponse(content_type= 'application/pdf')
        response['Content-Disposition']= 'attachment; filename=TrialBalance' + \
            str(datetime.now()) + '.pdf'
        response['Content-Transfer-Encoding'] = 'binary'

        content =  {"x_AlltrbYTD":x_AlltrbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero , 'printDesc':printDesc , 'printAcc':printAcc}
        html_string=render_to_string('main/reports/trialBalanceYear.html' , content)
        html=HTML(string=html_string)

        result=html.write_pdf()

        with tempfile.NamedTemporaryFile(delete=True) as output:
            output.write(result)
            output.flush()

            output.seek(0)
            response.write(output.read())

            return response

    if pkForm.Trial_balance_Monthly == True:
       
        ### Printing Trial Balance PDF
        response = HttpResponse(content_type= 'application/pdf')
        response['Content-Disposition']= 'attachment; filename=TrialBalanceMonthly' + \
            str(datetime.now()) + '.pdf'
        response['Content-Transfer-Encoding'] = 'binary'

        content =  {"xtrbMonth":xtrbMonth , 'xCreditTotalM':xCreditTotalM , 'xDebitTotalM':xDebitTotalM , 'complexName':complexName , 'printZeroM':printZeroM}
        html_string=render_to_string('main/reports/trialBalanceMonthly.html' , content)
        html=HTML(string=html_string)

        result=html.write_pdf()

        with tempfile.NamedTemporaryFile(delete=True) as output:
            output.write(result)
            output.flush()

            output.seek(0)
            response.write(output.read())

    else:
        printTrialBalanceMonth = False

程序只打印第一个 if 语句显示的内容,而不打印第二个 .pdf 文档。有谁知道这可能是什么原因造成的?

【问题讨论】:

标签: python django pdf httpresponse temporary-files


【解决方案1】:

您在第一个 if 块中使用 return

Django 生成一个响应,并且 return 下面的代码永远不会运行(顺便说一句,它什么也不返回,所以即使 pkForm.Trial_balance_Monthly == True 也不会有响应。

现代 IDE,例如 Pycharm 会在此处显示彩色警告,但如果您不使用此类 IDE,则可以使用调试器跟踪代码中发生的情况。

要进行您所描述的交互(只有一个按钮和 2 个报告),您需要:

  1. 为 2 个报告创建 2 个不同的端点
  2. 编写侦听按钮单击并调用 2 个端点的 JS 处理程序。照常处理回复。

替代方案:

制作一个包含两个报告的临时 zip 文件,并创建一个仅包含一个 zip 文件的响应。 每个操作系统都有解压缩功能,因此您的用户会发现这非常直观。这是压缩文件documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2019-09-26
    相关资源
    最近更新 更多