Django:HTML模板无法转换为PDF

时间:2018-08-29 22:07:41

标签: javascript python jquery django pdf-generation

我对Django和JS / Jquery还是很陌生。

单击“批准”按钮后,我试图生成HTML模板的pdf视图。我还在同一模板内编写了一个js / jquery脚本来生成pdf,而是重定向到我的主页;就像我在相应的view方法中定义的那样。 我现在想知道为什么它不运行js / jquery脚本并继续引用我的view方法,还有什么使它遍历该脚本并将页面转换为PDF并在点击后为用户下载的方法“批准”按钮。

非常感谢您的巧妙评论!

我的模板

<!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="{% static 'css/quote_letter_est.css' %}">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script 
src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"> 
</script>

<title>Estimate Quote Letter</title>
<script>
    var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

    $('#Approve').click(function () {
        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });
</script>
</head>
<div id="content">
<body  bgcolor="#ffffff" border="1">
    <form action="http://{{host}}:{{port}}/label/approve001" method="Get">
    {%csrf_token%}
        {% block content %}
            {% if cust_data %}
              {% for row in cust_data %}
                  <table id = "print-friendly" class="print-friendly" style="width:80%; cellspacing:0;">
                        <td colspan="8" align="left" valign="top" >{{ row.contact_fname }}&nbsp;{{ row.contact_lname }}<br>We trust that the following estimate meets with your approval and we look forward to working with you.<br><br>
                        </td>
                        <th colspan="2" align="left" style="width:300px; height:25px; font-size:14px;">
                        <p>TO: <br>{{ row.customer }} <br>{{row.add_line1}}, 
                           {{row.add_line2}} <br>{{ row.city}}, {{ 
                            row.province}}{{ row.postal_code}} 
                            <br>ATTN:&nbsp;&nbsp;{{ row.contact_lname }} 
                            <br>Phone:&nbsp;&nbsp;{{ row.phone }} 
                            <br>Email:&nbsp;&nbsp;{{ row.email }}</th> </p> 

                        <th></th><th align="left" style="width:300px; 
                        height:25px; font-size:14px;">QUOTATION#:&nbsp;&nbsp; 
                        {{ quotation_number }}<br>Date:&nbsp;&nbsp;{{ 
                         current_date}}<br><br>Sales Person:&nbsp;&nbsp;{{ 
                         row.sales_person }}<br>CSR:&nbsp;&nbsp;{{row.csr}} 
                         <br>Estimator:&nbsp;&nbsp;{{estimater}}
                       </th>
                       <input type="hidden"  name="Description" id="Description"     value={{quote_description}}>
                       <input type="hidden"  name="sales_person" id="sales_person"     value={{sales_person}}>
                       <input type="hidden"  name="csr_name" id="csr_name"     value={{csr_name}}>
                       <input type="hidden"  name="estimater" id="estimater"     value={{estimater}}>
                       <input type="hidden"  name="contact_lname" id="contact_lname"     value={{row.contact_lname}}>
                       <input type="hidden"  name="contact_fname" id="contact_fname"     value={{row.contact_fname}}>
                       <input type="hidden"  id="quotation_id" name="quotation_id" value={{ quotation_number }}>
                       <input type="hidden" name="deal_id" value={{ deal_id }}>
              </table>
              <button class="myButton" id="Approve" type="submit" name="approve001" formaction="approve001/" value=approve001>Approve</button>

              <input type="button" class ="myButton" name="Revise_All" 
               onclick="window.location.href='http://{{host}}: 
               {port}}/label/generate_quotation_letter001/letter_quotation/? 
               id='+ quotation_id.value + '&deal_id=' + deal_id.value "  
               value="Revise" /> 
    </div>
</body>
</html>

和这个my view方法(请注意request.GET值是从数据库中获取的,并在另一个方法中处理,在那里没有问题)。

class approve(APIView):
    def get(self, request):
        print ("Step 1 121get")
        part = request.GET['quotation_id']
        try:
            req_id = request.GET['quotation_id']
        except:
            req_id = ""
        try:
           verb = request.GET['approve001']
        except:
            verb = ""

        if verb == "decline001": #""decline":
            print ("decline data............")
        try:
            self.UpdateStatusRequest(req_id, "Request-Declined")
        except:
            quotation_id = ""

    elif verb == "approve001": #""approved":
        print ("approve data............")
        try:
            self.UpdateStatusRequest(req_id, "Request-Approved")
        except:
            quotation_id = ""
    return redirect('/')

def UpdateStatusRequest(self, req_id, status_state):
    print("pppppppppp", req_id, status_state)
    query = "update label_newquote set status=" + "'" + status_state + "' " + " WHERE id = " + str(req_id) + ";"
    print (query)
    with connection.cursor() as cursor:
        cursor.execute(query)

def post(self, request):
    print("Step 1 post")
    try:
        submit = request.POST.get('submit')
    except:
        submit = ""
    try:
        decline = request.POST.get('decline')
    except:
        decline = ""
    print(submit)
    print(decline)

    return redirect('generate_quotation_letter001/letter_quotation/')

以防万一,这是我的网址:

url(r'^generate_quotation_letter/perform_generate_quotation_letter/letter_quotation/LetterTwoQuotation/approve001/$', views_pdf.approve.as_view(), name="approve"),

1 个答案:

答案 0 :(得分:0)

将您的js包装在一个函数中,并在提交表单时返回该函数。

做这样的事情。

<script>
function pdfdownload(){
var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

    $('#Approve').click(function () {
        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });
return false;
}
</script>

,并且为

<form action="your_url" onsubmit="return pdfdownload()"> // your form

没有此调用,submit按钮会将表单中的任何表单提交到表单操作中提到的url中,而无需执行js。

请注意,这不会在执行js后提交您的表单。如果您希望将表单提交到js执行后实际提供的url,只需在函数中将“ return false”更改为“ return true”即可。 / p>