【问题标题】:How to enable UTF-8 in jsPDF library如何在 jsPDF 库中启用 UTF-8
【发布时间】:2014-03-22 07:43:17
【问题描述】:

我很高兴使用 jsPDF 库,它可以帮助我将 HTML 页面导出为 PDF 文件。我遇到了一些困难。我从http://parall.ax/products/jspdf/ 下载了库。当我在 pdf 中使用 š、ć (UTF-8) 等字符时,它们看起来像错误。即使我通过 doc.text 插入。在图书馆的网站上,当我使用他们的示例并使用其中一些字符更改文本时 - 它可以工作。所以假设它可以使用 UTF-8。为什么它不能在我的电脑上运行。

我为您提供我的代码。这里缺少的是lib(可以从网站下载),你会看到我的问题。为什么CSS在pdf中消失了?

testing.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TESTING JSPDF LIB</title>
<script type="text/javascript" src="pdffile.js" charset="utf-8"></script>
<script type="text/javascript" src="jspdf/jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jspdf/jspdf.js"></script>
<script type="text/javascript" src="jspdf/libs/Deflate/adler32cs.js"></script>
<script type="text/javascript" src="jspdf/libs/FileSaver.js/FileSaver.js"></script>
<script type="text/javascript" src="jspdf/libs/Blob.js/BlobBuilder.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.standard_fonts_metrics.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.from_html.js"></script>
<script>
function redirect() {
    document.write("Hello world" + '<br />');
}
</script>
</head>

<body>
<div id="box" class="box-shadow">
    <input type="submit" name="ok" id="ok" value="LETS TRY" onClick="redirect();pdf();" /> </div>
</div>
</body>
</html>

pdffile.js

function pdf() {
document.write('<div id="mydiv" style="background-color:#CCC; width:780px;640px;"><p>Open these letters š and c in PDF file and see error</p></div><br />');
document.write('<button id="export">OPEN IN PDF FILE</button>');

$(function () {
    var doc = new jsPDF();
    doc.text(35, 25, "Text with the letter Š");
    var specialElementHandlers = {
        'body': function (element, renderer) { 
            return true;
        }
    };
    $('#export').click(function () {
        doc.fromHTML($('#mydiv').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });
});
}

【问题讨论】:

  • 您确定您的 html/javascript 文件是以 UTF-8 编码/格式保存的吗?
  • 根据 jsPDF 团队,他们还不会支持它。你可以跟踪状态github.com/MrRio/jsPDF/issues/12
  • 是的,我确定。它在浏览器中显示这些字符,但之后不在 pdf 中。 :(
  • 您可以尝试将图像放置在字符的位置,或者尝试使用花哨的字体。当然那很痛苦。
  • 我知道他们不支持您发送的主题中的这些信件。但是我的信是如何出现在他们的网站上的。请尝试在他们的官方网站parall.ax/products/jspdf上的图片标题中加上Š或Č。只需更改标题即可。

标签: javascript html pdf utf-8 jspdf


【解决方案1】:

在 jsPDF 中,PDF 中的 14 种标准字体仅限于 ASCII 代码页。如果你想使用 UTF-8,你必须集成一个自定义字体,它提供了所需的字形。 jsPDF 支持 .ttf 文件。因此,如果您想在 pdf 中包含例如中文文本,您的字体必须具有必要的中文字形。因此,请检查您的字体是否支持所需的字形,否则它将显示乱码而不是正确的文本。

要将字体添加到 jsPDF,请使用 /fontconverter/fontconverter.html 中的 fontconverter。 fontconverter 将创建一个 js 文件,其中提供的 ttf 文件的内容为 base64 编码字符串和 jsPDF 的附加代码。您只需将此生成的 js-File 添加到您的项目中。然后,您就可以在代码中使用 setFont-method 并编写 UTF-8 编码文本了。

或者,您可以使用 fetch 或 XMLHttpRequest 将 *.ttf 文件的内容作为二进制字符串加载,并将字体添加到 PDF 文件:

const doc = new jsPDF();

const myFont = ... // load the *.ttf font file as binary string

// add the font to jsPDF
doc.addFileToVFS("MyFont.ttf", myFont);
doc.addFont("MyFont.ttf", "MyFont", "normal");
doc.setFont("MyFont");

【讨论】:

    【解决方案2】:

    jsPDF 仍然不支持 UTF-8。尽管 pdfmake.org 似乎支持 UTF-8。 尝试使用their playground 并使用您自己的角色进行测试。

    【讨论】:

    • 真的。但是pdfmake不支持ie。
    • @Saulius,现在可以了 :)
    • 您能在某处链接到此信息吗?你怎么知道的?
    • @trainoasis我用汉字测试了自己:autocosts.info/CN最后有PDF报告可以下载
    【解决方案3】:

    经过一天的搜索,我得到了所有网站的答案。

    toPDF(): void {
        const AmiriRegular = 'AAEAAAASAQAABAAgRFNJR2D2zXQA.....A';
    
        const doc = new jsPDF({ filters: ["ASCIIHexEncode"] });
    
        doc.addFileToVFS("Amiri-Regular.ttf", AmiriRegular);
        doc.addFont("Amiri-Regular.ttf", "Amiri", "normal");
    
        doc.setFont("Amiri"); // set font
        doc.setFontSize(10);
    
        doc.text(10,10,'אוהב אותך'.split('').reverse().join(''));
           this.CAccounts.forEach(function (AccountsBody, i) {
          doc.text(20, 20 + (i * 10),
    
    
            "ID: " + AccountsBody.ID +
            "NAME: " + AccountsBody.NAME.split('').reverse().join(''));
        });
        doc.save('employee.pdf');
    
      }
    

    【讨论】:

    • 那很好,但是混合英语和希伯来语呢
    【解决方案4】:

    jsPDF 不支持 UTF-8 虽然以下插件确实可以实现,因为当您可以将文件(FONT 文件)转换为 BASE64 时,它集成了完整的自定义字体支持。我已将 Arial Unicode 转换为 base64 并使用它它会产生一些间距和对齐问题,您需要通过调试代码来处理这些问题。

    https://github.com/sphilee/jsPDF-CustomFonts-support

    【讨论】:

      【解决方案5】:

      截至 2015 年,jsPDF 不正确支持 UTF-8,解决方法是使用 html2canvas 呈现 jpg 或 png 并将其添加到 pdf。您可以使用以下 sn-p 来了解一下:

      var doc = new jsPDF();
      
      var utf_8_string_to_render = 'any_value_you_want';
      
      Promise.all(
      [
          new Promise(function (resolve) 
          {
              var temp = document.createElement("div");
              temp.id = "temp";
              temp.style = "color: black;margin:0px;font-size:20px;";
              phrase = utf_8_string_to_render;
              temp.innerHTML= phrase;
              //need to render element, otherwise it won't be displayed
              document.body.appendChild(temp);
      
              html2canvas($("#temp"), {
              onrendered: function(canvas) {
      
                      $("#temp").remove();
                  resolve(canvas.toDataURL('image/png'));
              },
              });
          })
      ]).then(function (ru_text) { 
      
          doc.addImage(ru_text[0], 'JPEG', 0,0);
          doc.text(0, 10, 'Non-utf-8-string' );
      
          doc.save('filename.pdf');
          });
      
      
      };
      

      其他支持 utf-8 编码的库是:

      • PDFKit,据报道可以让您正确放置带有坐标的文本。
      • PDFMake,它可以正确呈现 UTF-8 字符,但不允许您定位文本,除非使用边距设置样式。

      【讨论】:

      • "onrendered" 选项已弃用,html2canvas 返回一个 Promise,取而代之的是 canvas 作为值。
      猜你喜欢
      • 2019-07-04
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 2015-09-24
      • 1970-01-01
      相关资源
      最近更新 更多