How to enable UTF-8 in jsPDF library

后端 未结 4 1426
自闭症患者
自闭症患者 2020-12-31 05:44

I am very happy to use jsPDF library which helps me to export my HTML page as PDF file. I came across some difficulties. I downloaded the library from http://parall.ax/produ

4条回答
  •  余生分开走
    2020-12-31 06:12

    As of 2015, jsPDF doesn't support UTF-8 properly, workaround is to use html2canvas to render jpg or png and to add it to pdf. You can use following snippet to get an idea:

    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');
        });
    
    
    };
    

    Another libraries that do support utf-8 coding are:

    • PDFKit, which is reported to allow you to proper place your texts with coordinates.
    • PDFMake, which renders UTF-8 characters properly, but doesn't allow you to position text, except for styling it with margins.

提交回复
热议问题