当HTML内容太长时,如何使用jsPDF将HTML转换为PDF?

问题描述 投票:0回答:1

我想将 html 转换为 pdf。为此,我使用 jsPDF 库。但我的 HTML 是动态变化的,而且可能太长。 HTML 文本过长时会被截断。我正在尝试转换包含多个页面的 pdf 页面。

这是我当前的代码:


async function generatePdfFromHtml(htmlElement) {
            // Create a new div element to hold the HTML content
            const div = document.createElement('div');
            div.innerHTML = htmlElement;

            // Append the div element to the document body
            document.body.appendChild(div);

            // Convert the HTML content to a canvas element
            const canvas = await html2canvas(div);
            const imgData = canvas.toDataURL('image/png');

            const pdf = new jsPDF("p", "pt", "a4", true);
            const pageWidth = pdf.internal.pageSize.width;
            const pageHeight = (canvas.height * pageWidth) / canvas.width;
            pdf.addImage(imgData, 'PNG', 0, 0, pageWidth, pageHeight);
            pdf.save('myfile.pdf');

            // Remove the temporary div element from the document body
            document.body.removeChild(div);
        }

我也会在这里添加一个导出的 pdf 示例:

jspdf html2canvas html-to-pdf
1个回答
-1
投票

你有办法解决这个问题吗?我和你遇到同样的问题已经好几个星期了,但没有找到解决方案。我快疯了。请帮助我!!

© www.soinside.com 2019 - 2024. All rights reserved.