无法使用jspdf将html导出为pdf

时间:2016-07-20 09:57:54

标签: javascript jquery html pdf

我正在尝试将我的html文件下载为pdf,我将其包括在内:

<script src="http://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.js" ></script>

这是我的js:

<script type="text/javascript">
function demoFromHTML() {
    var pdf = new jsPDF('p', 'pt', 'letter');
    // source can be HTML-formatted string, or a reference
    // to an actual DOM element from which the text will be scraped.
    source = $('#content')[0];

    // we support special element handlers. Register them with jQuery-style 
    // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
    // There is no support for any other type of selectors 
    // (class, of compound) at this time.
    specialElementHandlers = {
        // element with id of "bypass" - jQuery style selector
        '#bypassme': function (element, renderer) {
            // true = "handled elsewhere, bypass text extraction"
            return true
        }
    };
    margins = {
        top: 80,
        bottom: 60,
        left: 40,
        width: 522
    };
    // all coords and widths are in jsPDF instance's declared units
    // 'inches' in this case
    pdf.fromHTML(
    source, // HTML string or DOM elem ref.
    margins.left, // x coord
    margins.top, { // y coord
        'width': margins.width, // max width of content on PDF
        'elementHandlers': specialElementHandlers
    },

    function (dispose) {
        // dispose: object with X, Y of the last line add to the PDF 
        //          this allow the insertion of new lines after html
        pdf.save('Test.pdf');
    }, margins);
}

这是我的html按钮:

 <div class="page-container container"><button id="cmd">generate PDF</button>
       </div>

我正在尝试输出它中的任何内容 进入pdf - 但我的按钮实际上什么也没做。我的控制台给了我这个错误:

parall.ax/products/jspdf/dist/jspdf.debug.js:1 Uncaught SyntaxError: Unexpected token <
parall.ax/products/jspdf/dist/jspdf.debug.js:1 Uncaught SyntaxError: Unexpected token <

我尝试了很多示例代码但没有一个正在运行。

1 个答案:

答案 0 :(得分:1)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello world</title>
</head>
<body>
<h1>Hello world</h1>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js">  </script>
<script type="text/javascript">
    var pdf = new jsPDF();
    pdf.text(30, 30, 'Hello world!');
    pdf.save('hello_world.pdf');
</script>
</body>
</html>