jsPDF 仅生成空 pdf

jsPDF generates empty pdf only

我正在使用 jsPDF 从我的 HTML 创建一个 PDF。但是,无论我输入哪个 HTML 内容作为来源,它总是生成一个空白页面。

这是我的代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Save HTML TO PDF</title>



</head>

<body>
        <div><button id="cmd">download as PDF</button></div>

        <div id="content">Hello</div>

        <script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
        <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

        <script type="text/javascript">
            document.getElementById("cmd").addEventListener("click", function () {
                    window.html2canvas = html2canvas;
                    var doc = new jsPDF("p", "pt", "a4");
                    doc.html(document.getElementById("content"), {
                        callback: function(pdf) {
                          pdf.save("cv-a4.pdf");
                        }
                    });
                });

        </script>

</body>

</html>

我做错了什么?在我看来,这完全符合 documentation. However, as stated above, the pdf generated does not show any content and not the "Hello". ( I took some of the code from Whosebug 问题)

@threxx

试试这个代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Save HTML TO PDF</title>
</head>

<body>
        <div><button id="cmd">download as PDF</button></div>

        <div id="content">
            <h1 style="color: brown;">Hello, He/She..</h1>
            <p style="color: green;">How Are you ??</p>
            Thank you.
         </div>

        <script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
        <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

        <script type="text/javascript">
            document.getElementById("cmd").addEventListener("click", function () {

            var doc = new jsPDF("p", "pt", "a4");
            var source = window.document.getElementById('content').innerHTML;
            doc.fromHTML(source, 30, 30);  
            doc.save("cv-a4.pdf");
            });
        </script>
</body>

</html>

希望以上代码对你有用。

谢谢。

因此,在进行更多研究后,我发现 答案将 return 来自 HTML 的 PDF。小问题:仍然只有很差的 CSS 样式,但是 afaik jspdf 不支持自定义 CSS.

<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

<script type="text/javascript">
    document.getElementById("cmd").addEventListener("click", function () {

        var doc = new jsPDF("p", "pt", "a4");
        var source = document.body;
        var margin = {
            top: 20,
            left: 20,
            right: 20,
            bottom: 20
        };
        doc.fromHTML(source, 30, 30, {
            'width': 80, // max width of content on PDF
        },
        function(pdf){doc.save('saveInCallback.pdf');},
        margin
        );

    });
</script>