用jsPDF创建pdf

时间:2017-10-30 14:39:10

标签: javascript php html jspdf html2canvas

我在div

中有一个php页面
<div id="content">
    ....
    <img src="link">

    <div>
        <?php echo $content1; ?>
    /div>
    <table border = 1>
        <tr>
            <td><?php echo $content1; ?></td>
            <td><?php echo $content1; ?></td>
        </tr>
    </table>
</div>

<button onClick="generatePDF()" >generate PDF</button>

function generatePDF()
{
    var pdf = new jsPDF('p', 'mm', 'a0');
    var canvas = pdf.canvas;

    canvas.height = 297;
    canvas.width = 210;

    html2canvas($('#estimateContent').get(0), {
        canvas:canvas,
        allowTaint: true,
        onrendered: function (canvas) {
            pdf.save("Current Data2.pdf")   
        }
    });
}

PDF是空的。如何生成像我的div一样的pdf?

非常感谢

1 个答案:

答案 0 :(得分:2)

jsPDF没有属性,例如pdf.canvas

您可以使用canvas.toDataUrl()和jsPDF.addImage()从画布渲染数据 在pdf。 代码应该是这样的(对pdf的画布和纸张尺寸进行微调):

<div id="content">
....
<img src="link">

<div>
<?php echo $content1; ?>
/div>
<table border = 1>
<tr>
<td><?php echo $content1; ?></td>
<td><?php echo $content1; ?></td>
</tr>
</table>
</div>

<button onClick="generatePDF()" >generate PDF</button>

function generatePDF()
{
    html2canvas($('#content'), {
        allowTaint: true,
        onrendered: function (canvas) {
            var imgData = canvas.toDataURL("image/jpeg", 1.0);
            var pdf = new jsPDF('p', 'mm', 'a0');

            pdf.addImage(imgData, 'JPEG', 0, 0);
            pdf.save("Current Data2.pdf")
        }
    });
} 

或者除了jsPDF和html2canvas之外你还可以使用html2pdf: https://github.com/eKoopmans/html2pdf

以下是代码示例中的实际应用程序:

<div id="content">
....
<img src="link">

<div>
<?php echo $content1; ?>
/div>
<table border = 1>
<tr>
<td><?php echo $content1; ?></td>
<td><?php echo $content1; ?></td>
</tr>
</table>
</div>

<button onClick="generatePDF()" >generate PDF</button>

function generatePDF()
{

    var element = document.getElementById('content');

    html2pdf(element, {
        margin:       1,
        filename:     'Current Data2.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { dpi: 192, letterRendering: true,  allowTaint: true, onrendered: function(canvas) {
            // canvas is the final rendered <canvas> element
            //if you need to perform some actions, cleanup, etc after the canvas has been generated
        } },
        jsPDF:        { unit: 'mm', format: 'a0', orientation: 'portrait' }
    });

}