特殊字符未导出为PDF

时间:2017-10-30 00:23:40

标签: javascript jquery

我正在使用jspdf将数据导出为PDF。将数据导出到PDF时,PDF中不会显示特殊字符。

请找到演示插件:https://plnkr.co/edit/BCgDQm3jV9ctwYJMWkjh?p=preview

在上面的demo plunker中,当用户点击导出按钮时,内容将导出为PDF并且PDF已下载,但问题是我注意到特殊字符未导出到PDF。可以在网页上看到的针对option1,option2提到的项目符号和数字不会导出到PDF。

JavaScript代码:

$scope.export = function() {
    var pdf = new jsPDF('landscape');
    var pdfName = 'test.pdf';

    var options = {};

    var $divs = $('.myDivClass')                //jQuery object of all the myDivClass divs
    var numRecursionsNeeded = $divs.length -1;     //the number of times we need to call addHtml (once per div)
    var currentRecursion=0;

    //Found a trick for using addHtml more than once per pdf. Call addHtml in the callback function of addHtml recursively.
    function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
        //Once we have done all the divs save the pdf
        if(currentRecursion==totalRecursions){
            pdf.save(pdfName);
        }else{
            currentRecursion++;
            pdf.addPage();
            //$('.myDivClass')[currentRecursion] selects one of the divs out of the jquery collection as a html element
            //addHtml requires an html element. Not a string like fromHtml.
            pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                console.log(currentRecursion);
                recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
            });
        }
    }

    pdf.addHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
        recursiveAddHtmlAndSave(currentRecursion, numRecursionsNeeded);
    });
}

任何输入都会有所帮助。

2 个答案:

答案 0 :(得分:1)

根据文档,doc.addHTML正在被弃用,以支持矢量API。 这种方法确实似乎缺少一些功能,例如CSS list-style-type的渲染。

我不确定doc.fromHTML是否是这个新的API (目前不在文档中),但它似乎能够呈现这些:



var doc = new jsPDF();
doc.fromHTML(ul, 15, 15, {
  width: 170
});
doc.addPage();
doc.fromHTML(ol, 15, 15, {
  width: 170
});
var blob = doc.output('blob');
var i = document.createElement('iframe');
i.width = '100%';
i.height = window.innerHeight;
i.src = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = 'doc.pdf';
a.innerHTML = 'download (for chrome...)';
a.href = i.src;
document.body.appendChild(a);
document.body.appendChild(i);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>

<div id="ul">
  <ul>
    <li>first</li>
    <li>second</li>
  </ul>
</div>
<div id="ol">
  <ol>
    <li>first</li>
    <li>second</li>
  </ol>
</div>
&#13;
&#13;
&#13;

所以这是你固定的plnkr

答案 1 :(得分:0)

当我正在阅读您在github使用的插件时,您可能需要使用UTF-8字符集来执行此操作。你可以尝试在你的头部html上添加meta charset UTF-8,你将用它来生成PDF

或者如果您使用nodeJS作为后端。你可以试试phantom JS PDF。我之前使用过它,它甚至支持阿拉伯语,中文,俄语,日语等符号语言(有一些配置)

为了更好的可读性而编辑