Django在按钮点击时将当前页面转换为PDF

时间:2017-04-02 09:51:30

标签: django python-3.x

我在Windows上使用Django 1.10和python 3.4。我设置了pdfkit,它可以从命令行完美运行。我想在按钮上的站点中使用它将当前页面作为pdf附件返回,而不在任何地方重定向(如果可能)。要转换的页面是一个报告,它使用用户指定的日期作为网址。

目前,该按钮会重新定向,方法是将当前网址附加到"?mybtn =生成+ PDF#"

我见过一些使用jQuery或javascript的解决方案,但我真的很了解python。我最终会学到这些,但是现在我想要一个更快的解决方案,我明白了它的作用。

views.py

{"name":"Test","price":150} <link rel='stylesheet' type='text/css' property='stylesheet' href='//localhost:8080/_debugbar/assets/stylesheets?v=1488564328'><script type='text/javascript' src='//localhost:8080/_debugbar/assets/javascript?v=1488564328'></script><script type="text/javascript">jQuery.noConflict(true);</script>
<script type="text/javascript">
var phpdebugbar = new PhpDebugBar.DebugBar();
phpdebugbar.addTab("messages", new PhpDebugBar.DebugBar.Tab({"icon":"list-alt","title":"Messages", "widget": new PhpDebugBar.Widgets.MessagesWidget()}));
phpdebugbar.addIndicator("time", new PhpDebugBar.DebugBar.Indicator({"icon":"clock-o","tooltip":"Request Duration"}), "right");
phpdebugbar.addTab("timeline", new PhpDebugBar.DebugBar.Tab({"icon":"tasks","title":"Timeline", "widget": new PhpDebugBar.Widgets.TimelineWidget()}));
phpdebugbar.addIndicator("memory", new PhpDebugBar.DebugBar.Indicator({"icon":"cogs","tooltip":"Memory Usage"}), "right");
phpde[…]

reports_flash_report.html

class FlashReport(generic.View):
template_name = "reports_flash_report.html" 

def get(self, request, year, month, day):
    report_data = get_flash_report_data(int(year),int(month),int(day))
    return render(request, 'reports_flash_report.html', report_data)

def generate_PDF(request):
    path = request.get_full_path()
    pdf = pdfkit.from_url(path, False)
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="flash_report.pdf"'
    return response

urls.py

<div>
    <form action="" method="get">
        <input type="submit" class="btn" value="Generate PDF" name="mybtn" />
    </form>
</div>

0 个答案:

没有答案