将html内容导出为PDF

时间:2016-09-01 05:11:55

标签: php jquery



<script>
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>
&#13;
<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>a pararaph</p>
	<img src="4.jpg" />
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
&#13;
&#13;
&#13;

我将html导出为pdf。没有html内容中的图像PDF正确导出,但如果我将图像添加到HTML内容,则会创建空白pdf。

2 个答案:

答案 0 :(得分:3)

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<script>
function toPdf() {
var doc = new jsPDF();
// We'll make our own renderer to skip this editor
    var specialElementHandlers = {
        '#editor' : function(element, renderer) {
            return true;
        }
    };

    // All units are in the set measurement for the document
    // This can be changed to "pt" (points), "mm" (Default), "cm", "in"
    doc.fromHTML($('#render_me').get(0), 30, 50, {
        'width' : 170,
        'elementHandlers' : specialElementHandlers
    });

    doc.save('sample-file.pdf');
}

给id =&#34; render_me&#34; div想要渲染的内容。例如

<table id="render_me"></table>

答案 1 :(得分:0)

When using the fromHTML() it's important to save the pdf in the callback, because else it won't be done rendering by the time it saves the doc.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<script>
$(document).ready(function() {
    var doc = new jsPDF();
    $('#cmd').click(function () {
        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
        }, function () {
            doc.save('sample-file.pdf')
        });
    });
});
</script>

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>a pararaph</p>
        <img src="//i.imgur.com/7NtRajR.jpg" />
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

Demo: https://jsfiddle.net/qcyspvy7/