我在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?

非常感谢

最佳答案

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' }
    });

}

关于javascript - 用jsPDF创建pdf,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47017967/

10-13 01:46