jsPDF无法在localhost中工作

时间:2016-05-21 10:30:37

标签: javascript php jspdf

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"></script>
<script type="text/javascript">
    var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });
</script>
<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

我的代码在jsfiddle中正常工作但在localhost中没有工作我已经提到了我的所有代码所以很容易理解我在做什么

1 个答案:

答案 0 :(得分:0)

问题是你的html的顺序,将你的标记改为:

<div id="editor"></div>
    <button id="cmd">generate PDF</button>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"></script>
    <script type="text/javascript">
        var doc = new jsPDF();
        var specialElementHandlers = {
            '#editor': function (element, renderer) {
                return true;
            }
        };

        $('#cmd').click(function () {
            console.log("Hola");
            doc.fromHTML($('#content').html(), 15, 15, {
                'width': 170,
                    'elementHandlers': specialElementHandlers
            });
            doc.save('sample-file.pdf');
        });
    </script>
    <div id="content">
         <h3>Hello, this is a H3 tag</h3>

        <p>a pararaph</p>
    </div>

未触发点击事件,因为您正在向不存在的内容添加侦听器。该代码即使在file://协议中也能正常工作。使用jsFiddle是有效的,因为应用程序会自动呈现标记。