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

使用jsPDF转HTML为PDF时土耳其字符乱码的解决求助

解决jsPDF转换HTML为PDF时土耳其字符乱码问题

我需要直接将HTML元素转换为PDF(不经过转图片的步骤),但用jsPDF实现时遇到了土耳其字符乱码的问题。我的导出函数和调用代码如下:

导出函数代码

const ExportPDF = (FileName, Component, Size) => {
        Size = Size ?? [1100, 1200]

        var pdf = new jsPDF({
            orientation: '1',
            unit: 'px',
            format: Size,
        })

        var options = {
            callback: (pdf) => {
                pdf.save((FileName ?? "output") + ".pdf");
            },
            x: 10,
            y: 10,
        }

        pdf.html(Component, options)
    }

调用代码

<Button
    fullWidth
    variant="outlined"
    color="info"
    size="large"
    startIcon={<FilePdfBox />}
    onClick={() => {
        const PDFComponent = document.getElementById("pdf-content")
        ExportPDF("output-test", PDFComponent)
    }}
>
    Download as PDF
</Button>

我已经尝试过以下两种方法,但都没解决问题:

  • 在options中添加encoding: 'UTF-8'
    var options =  {
        encoding: 'UTF-8',
        ...
    }
    
  • 添加并设置Arial Unicode MS字体
    pdf.addFont("../../font/arialuni.ttf", "ArialUnicodeMS", "normal")
    pdf.setFont("ArialUnicodeMS")
    

有效解决方案

1. 确保HTML内容使用支持土耳其字符的字体

先给要转换的HTML元素(#pdf-content)设置支持Unicode的字体,比如系统自带的兼容字体,或者自定义字体:

#pdf-content {
    font-family: 'Arial Unicode MS', 'Segoe UI', Tahoma, sans-serif;
}

2. 修正jsPDF配置并正确加载字体

jsPDF的html()方法依赖html2canvas渲染,直接调用addFont可能因为时机或配置问题不生效,需要调整代码逻辑,同时修复参数错误:

const ExportPDF = async (FileName, Component, Size) => {
    Size = Size ?? [1100, 1200]

    // 初始化jsPDF实例
    const pdf = new jsPDF({
        orientation: 'portrait', // 原代码的'1'是无效值,改为portrait/landscape
        unit: 'px',
        format: Size,
        putOnlyUsedFonts: true, // 只打包用到的字体,减小文件体积
    })

    // 异步加载字体(确保字体路径正确,文件可访问)
    await pdf.addFont("../../font/arialuni.ttf", "ArialUnicodeMS", "normal");
    pdf.setFont("ArialUnicodeMS");

    const options = {
        callback: (pdf) => {
            pdf.save((FileName ?? "output") + ".pdf");
        },
        x: 10,
        y: 10,
        // 配置html2canvas渲染参数,指定字体
        html2canvas: {
            scale: 2, // 提升PDF清晰度
            fontFamily: 'ArialUnicodeMS',
            useCORS: true
        }
    }

    // 异步执行HTML转换
    await pdf.html(Component, options)
}

3. 额外检查项

  • 确认页面头部有<meta charset="UTF-8">标签,保证页面字符编码正确。
  • 自定义字体路径要正确,避免跨域问题(如果是本地开发,注意静态资源访问权限)。
  • 也可以使用Google Fonts中支持土耳其字符的字体(比如Roboto),直接在HTML中引入后,替换CSS和jsPDF配置中的字体名称即可。

内容的提问来源于stack exchange,提问作者M.Çelik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:35:31