使用javascript将HTML页面中的div下载为pdf

Mid*_*hew 73 javascript jquery

我有一个id为"content"的内容div.在内容div中我有一些图表和一些表格.我想在用户点击下载按钮时将该div下载为pdf.有没有办法使用javascript或jQuery?

ily*_*oli 101

你可以用jsPDF来做

HTML:

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

    <p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

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');
});
Run Code Online (Sandbox Code Playgroud)

  • 我这里有问题.我在这里添加的CSS没有在pdf文件中应用.我也有一些图表..这些不会出现在pdf中.我该怎么做才能得到那些? (21认同)
  • jsPDF也没有正确地格式化表,它只是将td/th解释为display:block; (13认同)
  • 这很好,只是一个耻辱css没有得到渲染:/ (4认同)
  • 使用上面的代码,我们只能创建一个 pdf 一次。但是第二次它不起作用。要使其工作,请查看@kristof-feys 的 [answer](http://stackoverflow.com/a/19786792/3049065),我们需要在 click 函数中声明 `doc` 变量。 (3认同)
  • 我花了很多时间来使用 jsPDF,最后我发现它没有渲染 CSS。我的桌子看起来太糟糕了,无法正确添加任何图像。jsPDF 没什么用处。 (2认同)

小智 31

<div class='html-content'>....</div>可以使用jspdfhtml2canvas将a 中的内容下载为 pdf 样式。

你需要参考两个js库,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
Run Code Online (Sandbox Code Playgroud)

然后调用下面的函数,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}
Run Code Online (Sandbox Code Playgroud)

参考:来自 html canvas 和 jspdf 的 pdf 生成

可能这会帮助某人。

  • 这对我来说非常有用,谢谢。它保留了所有样式,但确实有一些限制(将 PDF 创建为图像,因此不可搜索;似乎也有点模糊)。 (6认同)