You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用xhtml2pdf转换PDF时高棉语Unicode字符显示异常求助

解决xhtml2pdf转换含高棉语Unicode字符网页为PDF的显示异常问题

xhtml2pdf基于ReportLab,对高棉语这类需要复杂字形组合的脚本支持需要额外配置,以下是具体解决步骤:

1. 完善HTML字体配置

修改HTML中的@font-face规则,补充字体格式声明,确保xhtml2pdf能正确识别字体类型:

<!DOCTYPE html>
<html>
    <title>sample file</title>
<head>
    <meta charset="UTF-8">
    <style>
        @font-face {
            font-family: 'KhmerOS';
            src: url('KhmerOS.ttf') format('truetype');
            font-weight: normal;
            font-style: normal;
        }
        body {
            font-family: 'KhmerOS', Arial, sans-serif;
        }
    </style>
</head>
<body>
    <h1>ភាសាខ្មែរ</h1>
    <p>នេះគឺជាអត្ថបទសាមញ្ញជាភាសាខ្មែរដែលបានសរសេរជាអក្សរខ្មែរយូនីកូដ។</p>
</body>
</html>

确认KhmerOS.ttf为完整版本的高棉语字体,包含所有必要的字形、连字及元音附标支持

2. 在Python代码中注册字体并指定渲染参数

xhtml2pdf依赖ReportLab渲染PDF,仅靠HTML加载字体无法处理高棉语这类复杂脚本,需手动注册字体并配置渲染参数:

from xhtml2pdf import pisa
import io
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# 提前注册高棉语字体到ReportLab
pdfmetrics.registerFont(TTFont('KhmerOS', 'KhmerOS.ttf'))

def convert_html_to_pdf(source_html, output_filename):
    with open(output_filename, "wb") as output_file:
        # 指定UTF-8编码,将默认字体设为已注册的KhmerOS
        pdf_status = pisa.CreatePDF(
            source_html,
            dest=output_file,
            encoding='UTF-8',
            default_font='KhmerOS'
        )

    return not pdf_status.err

if __name__ == "__main__":
    with io.open("khmer_unicode.html", "r", encoding="utf-8") as html_file:
        html_content = html_file.read()

    pdf_output = "khmer_unicode.pdf"
    if convert_html_to_pdf(html_content, pdf_output):
        print("PDF file has been created at " + pdf_output)
    else:
        print("Error generating PDF")

3. 关键注意事项

  • 避免使用精简版高棉语字体,这类字体通常缺失复杂字形组合所需的字模
  • ReportLab字体注册是解决复杂脚本显示问题的核心,仅HTML的@font-face无法覆盖渲染需求
  • 确保传递给CreatePDF的HTML内容始终保持UTF-8编码,避免编码转换丢失字符

内容的提问来源于stack exchange,提问作者Houy Narun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 17:07:17