【问题标题】:Django: The HTML template fails to be converted to PDFDjango:HTML模板无法转换为PDF
【发布时间】:2019-02-04 18:58:30
【问题描述】:

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

单击“批准”按钮后,我正在尝试生成我的 HTML 模板的 pdf 视图。我还在同一个模板中编写了一个 js/jquery 脚本来生成 pdf,而是被重定向到我的主页;正如我在相应的视图方法中定义的那样。 我现在想知道为什么它不运行 js/jquery 脚本并一直引用我的视图方法,以及我可以做些什么来让它通过脚本并将页面转换为 PDF 并在点击后为用户下载“批准”按钮。

非常感谢您的智能 cmets !

我的模板

<!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>

这是我的视图方法(注意 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"),

【问题讨论】:

  • preventDefault()

标签: javascript python jquery django pdf-generation


【解决方案1】:

将您的 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

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

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

【讨论】:

  • 愿上帝保佑你!谢谢!
猜你喜欢
  • 2018-10-04
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 2023-02-24
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多