UnicodeEncodeError:“latin-1”编解码器无法对2082-2084位置的字符进行编码:序号不在范围(256)内

vd2z7a6w  于 2022-10-22  发布在  Python
关注(0)|答案(2)|浏览(154)

我不知道为什么会这样。每当我添加阿拉伯语内容时,它都会显示上面的错误,否则可以很好地使用英语*相同的代码在另一个项目中运行得很好,但在这里不行。*views.py

def generate_pdf_for_gift_and_add_to_cart(request):
    cart = Cart(request)
    if request.method == 'POST':
        id = request.POST.get('project_id')
        selectedAmount = request.POST.get('amount')
        senderNameDonatedDonationPage = request.POST.get(
            'senderNameDonatedDonationPage')
        receiverNameDonatedDonationPage = request.POST.get(
            'receiverNameDonatedDonationPage')
        phoneNumberDonatedDonationPage = request.POST.get(
            'phoneNumberDonatedDonationPage')
        emailDonatedDonationPage = request.POST.get('emailDonatedDonationPage')
        params = {
            "project_id": id,
            "selectedAmount": selectedAmount,
        }

        pdf = render_to_pdf('pdfs/gift_pdf.html', params)
        if pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            filename = f"Invoice_{emailDonatedDonationPage}_{datetime.now()}.pdf"
            content = "inline; filename='%s'" % filename
            download = request.POST.get("download")
            if download:
                content = "filename='%s'" % filename
            response['Content-Disposition'] = content
            receipt_file = BytesIO(pdf.content)
            return response

实用程序。py我还尝试了utf-8编码,但在生成的pdf页面上显示了空白框

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

gift.pdf。下面的html是示例模板,将在其中呈现该模板

<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gift PDF</title>

    <style type="text/css">
        @page {
            size: 6in;
        }

        body {
            margin: 0;
        }

        .page_body {
            background-image: url("");
            background-position: center center;
            background-repeat: no-repeat;
            background-size: cover;
            position: relative;
            width: 100%;
        }

        .page_body .content_row {
            display: flex;
            justify-content: center;
            align-items: center;
            grid-gap: 127px;
            margin: 630px 0;
            padding: 0 78px;
            flex-direction: column;
        }

        .page_body .ehdaa {
            position: absolute;
            top: 33px;
            left: 20%;
            width: 625px;
            height: 495px;
        }

        .page_body .flowers {
            position: absolute;
            top: 0;
            right: 0;
        }

        .page_body p {
            line-height: 10px;
            font-size: 15px;
            font-weight: 700;
            text-align: center;
        }

        .page_body .headings {
            color: #B1915A;
        }

        .page_body .paragraph {
            color: #1F858F;
        }

        .page_body .hands {
            position: absolute;
            left: 0;
            bottom: 0;
            width: 370px;
            height: auto;
        }
    </style>

</head>

<body>

<div class="page_body container-fluid">
    <img class='ehdaa' src="" alt="ehda">
    <img class='flowers' src=""
         alt="flowers">
    <div class="content_row">

        <div class="headings">{{ receiverNameDonatedDonationPage }}إلي</div>

    </div>
    <img class="hands" src=""
         alt="hands">
</div>
</body>

</html>
xlpyo6sf

xlpyo6sf1#

您的代码需要进行一些调整,才能在输出中不生成块字符。
1.添加支持阿拉伯语的字体
默认情况下,xhtml2pdf仅提供少数字体,这些字体都不支持阿拉伯语:
Times Roman:Times New Roman,Times,Georgia,衬线
Helvetica:Arial,Verdana,日内瓦,sansserif,sans
Courier:Courier新的,单空间,单空间
Zapf丁巴茨
象征
因此,您想在HTML文件中添加一种字体,以创建一个font-face

<style type="text/css">
        @font-face {
            font-family: ArialUnicode;
            src: url("static/Arial Unicode.ttf")
        }
        <!-- other stuff here -->
        body {
            margin: 0;
            font-family: "ArialUnicode", sans-serif;
        }

        <!-- more css here -->
   </style>

1.将编码更改为utf-8
这与您的产品线有关:

pdf = pisa.pisaDocument(BytesIO(template.encode("ISO-8859-1")), result)

假设您有兼容的字体,您也可以使用ISO-8859-6,但我在示例中使用了Arial Unicode
这是一个非常精简的代码版本,它只加载HTML文件并在xhtml2pdf.pisa中运行

from io import BytesIO

from xhtml2pdf import pisa

# I have a templates directory with the html file in it

# and a 'static' directory with fonts in it

if __name__ == '__main__':
    with open("templates/gift_pdf.html") as t:
        template = t.read()

    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(template.encode("utf-8")), result)
    with open("output.pdf", "w+b") as ofile:
        ofile.write(result.getbuffer())

输出如下:


小时

xyhw6mcr

xyhw6mcr2#

如果你想下载html页面的pdf

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>A paragraph</p>
</div>
<button onclick="CreatePDFfromHTML()">generate PDF</button>

您需要引用两个JS库,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

然后调用下面的函数,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".content").width();
    var HTML_Height = $(".content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        // if you want to upload pdf on your server
        // you can call ajax request here and pass pdf and upload it.
        pdf.save("{{invoice_name}}.pdf");
        $(".content").hide();
    });
}

相关问题