如何在 django 中使用 xhtml2pdf 生成的 PDF 中显示表情符号字符?

How to display emoji characters in PDF generated using xhtml2pdf in django?

我正在尝试使用 xhtml2pdf 将 HTML 转换为 PDF,但无法正确呈现 HTML 中的表情符号字符,它们显示为黑框。我尝试了不同的字体,但仍然是同样的问题。

# -*- coding: utf-8 -*-
import time

import os
from io import BytesIO

from xhtml2pdf import pisa

source = """<html>
            <head>
              <title>Doc title</title>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <meta charset="UTF-8">
            </head>
            <style>
                @media print {
                    @font-face {
                        font-family: Helvetica;
                        src: url("/absolute/path/to/Helvetica.ttf");
                    }
                }
                
            </style>
            <body>
                <p></p>
            </body>
        </html>"""


def convert_html_to_pdf(source):
    pdf = BytesIO()
    pisaStatus = pisa.CreatePDF(BytesIO(source), pdf, encoding='utf-8')
    return pdf


if __name__ == "__main__":
    pdf = convertHtmlToPdf(source)
    fd = open(os.path.join('/home/userX/', 'test-%s.pdf' % time.time()), "w+b")
    fd.write(pdf.getvalue())
    fd.close()

所以我能够使用 Symbola 字体在 PDF 上获取表情符号,如下所示:

# -*- coding: utf-8 -*-
import time

import os
from io import BytesIO

from xhtml2pdf import pisa

source = """<html>
            <head>
              <title>Doc title</title>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <meta charset="UTF-8">
            </head>
            <style>
                @media print {
                    @font-face {
                        font-family: Symbola;
                        src: url("/absolute/path/to/Symbola.ttf");
                    }
                }

                body {font-family: Symbola, sans-serif !important}
            </style>
            <body>
                <p></p>
            </body>
        </html>"""


def convert_html_to_pdf(source):
    pdf = BytesIO()
    pisaStatus = pisa.CreatePDF(BytesIO(source), pdf, encoding='utf-8')
    return pdf


if __name__ == "__main__":
    pdf = convertHtmlToPdf(source)
    fd = open(os.path.join('/home/userX/', 'test-%s.pdf' % time.time()), "w+b")
    fd.write(pdf.getvalue())
    fd.close()