js实现html导出为PDF文件

html2canvas官网:http://html2canvas.hertzen.com/

<?php
if(!empty($_POST['datauri'])){
    if(preg_match('/data:.*?;base64,/i',$_POST['datauri'])){
        $datauri = base64_decode(preg_replace('/data:.*?;base64,/i','',$_POST['datauri']));
        $dir = 'upload/';
        if(!is_dir($dir)){
            mkdir($dir);
        }
        $file = md5($_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']).'.pdf';
        try {
            file_put_contents($dir.$file,$datauri);
            $data = ['code' => 1,'msg' => '上传成功','url' => $dir.$file];
        } catch (Exception $e) {
            $data = ['code' => 0,'msg' => '上传失败'];
        }
        echo json_encode($data);exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="content">内容</div>
    <script src="http://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="http://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
    <script>
        $(".download").on('click', function() {
            downLoadPdf(document.getElementById("content"));
            //downloadQrCode(document.getElementById("content"));
        })
        //保存为jpg图片
        function downloadQrCode(content) {
            html2canvas(content).then(function(canvas) {
                var img = document.createElement('a');
                img.href = canvas.toDataURL("image/jpeg",1);
                img.download = 'report.jpg';
                img.click();
            });
        }
        //保存为PDF文件
        function downLoadPdf(content) {
            content = content ? content : null;
            // 条件判断是否打印
            if (!content) {
                alert("打印失败,请重新操作")
                return false
            }

            html2canvas(content, {
                allowTaint: true,
                useCORS: true
            }).then(function(canvas) {
                var pdfWidth = canvas.width;
                var pdfHeight = canvas.height;
                var pageHeight = pdfWidth / 592.28 * 841.89;
                var leftHeight = pdfHeight;
                var position = 0;
                var imgWidth = 595.28;
                var imgHeight = 595.28 / pdfWidth * pdfHeight;
                var pageData = canvas.toDataURL("image/jpeg",1);
                var pdf = new jsPDF('', 'pt', 'a4');
                // 判断打印dom高度是否需要分页,如果需要进行分页处理
                if (leftHeight < pageHeight) {
                    pdf.addImage(pageData, "jpeg", 0, 0, imgWidth, imgHeight)
                } else {
                    while (leftHeight > 0) {
                        pdf.addImage(pageData, "jpeg", 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight
                        position -= 841.89
                        if (leftHeight > 0) {
                            pdf.addPage()
                        }
                    }
                }
                //pdf.save("report.pdf");//下载PDF
                var datauri = pdf.output('dataurlstring'); //base64编码
                //上传
                $.post('', {
                    datauri
                }, function(res) {
                    if (res.code == 1) {
                        window.open(res.url);
                    } else {
                        alert('获取PDF文件失败');
                    }
                }, 'json')
            })
        }
        // js计算base64图片大小
        function imageSize(base64Str) {
            const indexBase64 = base64Str.indexOf('base64,');
            if (indexBase64 < 0) return -1;
            const str = base64Str.substr(indexBase64 + 6);
            return (str.length * 0.75 / 1000).toFixed(2);
        }
    </script>
</body>

</html>

声明:本文全部内容均从网络中采集而成,只做测试与学习之用,请在下载后24小时自行删除,如有任何涉及版权的问题,请及时联系站长删除内容。谢谢!(邮箱:doubaiwang@126.com)
逗呗网 » js实现html导出为PDF文件

发表评论