html 到 pdf 转换器出现意外错误的示例

Example for html to pdf converter getting unexpected error

此示例是所附 fiddle 的 运行 副本(其中示例是 运行 正确)。我很惊讶复制相同的是抛出错误。为什么?

HTML:

<html>
<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
    'body': function (element, renderer) {
        return true;
    }
};

$('button').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});
</script>
</head>

<body>
    <button>Click</button>
    <div class="container"> 
        Hello! 
    </div>
</body> 
</html> 

jSFiddle

http://jsfiddle.net/5ud8jkvf/

错误:

Notes:

  1. As fiddle is running properly, this example must also run without any error.
  2. There is no attachment of jQuery file in fiddle, so I dont think jQuery is required or missing in this example.
  3. Even on adding jQuery files - Error is gone - but pdf is not getting downloaded.

原因是你必须添加jQuery,像这样:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>

控制台不会撒谎。 fiddle 依赖于 jQuery。

您的标记需要 jQuery。将 jQuery 添加到您的代码中 ...

<html>
 <head> 
  <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>

试试这个

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
    'body': function (element, renderer) {
        return true;
    }
};
$(document).ready(function(){
$('button').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});
});
</script>
</head>

<body>
    <button>Click</button>
    <div class="container"> 
        Hello! 
    </div>
</body> 
</html>