JS导出 html 节点为 PDF

发布时间:2023-11-20浏览次数:0

exportDialogAsImage() {
            domtoimage.toPng(document.getElementById('test'),{
                style: {
                    'background-color': '#1E2A44',
                    'padding':"20px"
                }
            })
                .then(function (dataUrl) {
                    // 创建 jsPDF 实例
                    const pdf = new jsPDF({
                        orientation: 'portrait',
                        unit: 'px',
                        format: 'a4'
                    });

                    // 获取图片的尺寸
                    const img = new Image();
                    img.src = dataUrl;
                    img.onload = () => {
                        // 计算 PDF 中图片的位置和尺寸
                        const imgWidth = img.width;
                        const imgHeight = img.height;
                        const pageWidth = pdf.internal.pageSize.getWidth();
                        const pageHeight = pdf.internal.pageSize.getHeight();
                        const ratio = Math.min(pageWidth / imgWidth, pageHeight / imgHeight);

                        const imgScaledWidth = imgWidth * ratio;
                        const imgScaledHeight = imgHeight * ratio;
                        const x = (pageWidth - imgScaledWidth) / 2;
                        const y = (pageHeight - imgScaledHeight) / 2;

                        // 将图片添加到 PDF 中
                        pdf.addImage(dataUrl, 'PNG', x, y, imgScaledWidth, imgScaledHeight);
                        // 下载 PDF
                        pdf.save('download.pdf');
                    };
                })
                .catch(function (error) {
                    console.error('截图出错', error);
                });
        },
字节笔记本扫描二维码查看更多内容