html转换到pdf

发布于:2024-07-11 ⋅ 阅读:(57) ⋅ 点赞:(0)
<head>
    <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
</head>

不含分页,分页需要使用addImage单独处理

// import htmlTo from './test.js'
const domToPdf = (function(){
    $('#downloadPDF').click(function() {
        const htmlToCanvas = function(){
            const options = {
                dpi: 192,  //dpi属性的值为192,表示图像的分辨率
                scale: 1, //scale属性的值为2,表示图像的缩放比例。
                loggging:true,
                allowTaint: true,//是否允许跨源图形污染画布
                useCORS: true,//是否允许跨域图像
            };
        
            let dom = document.querySelector('#pdfCtn');
            html2canvas(dom, options).then(canvas => {
                
                // 画布背景色
                // 在pdfCtn容器上定义

                // 转为base64
                let pageData = canvas.toDataURL('image/jpeg', 1.0);
                
                // 得到canvas画布的单位是px 像素单位
                let contentWidth = canvas.width;
                let contentHeight = canvas.height;
                
                // 设置PDF的尺寸
                // 设置pdf的尺寸,pdf要使用pt单位 已知 1pt/1px = 0.75   pt = (px/scale)* 0.75
                // 2为上面的scale 缩放了2倍
                const pdfX = (contentWidth + 10) / options.scale * 0.75
                const pdfY = (contentHeight + 500) / options.scale * 0.75 // 500为底部留白

                // 设置内容图片的尺寸,img是pt单位 
                const imgX = pdfX;
                const imgY = (contentHeight / options.scale * 0.75); //内容图片这里不需要留白的距离

                // 初始化jspdf 第一个参数方向:默认''时为纵向,第二个参数设置pdf内容图片使用的长度单位为pt,第三个参数为PDF的大小,单位是pt
                var PDF = new jsPDF('', 'pt', [pdfX, pdfY])

                // 将内容图片添加到pdf中,因为内容宽高和pdf宽高一样,就只需要一页,位置就是 0,0
                PDF.addImage(pageData, 'jpeg', 0, 0, imgX, imgY)
                PDF.save('测试.pdf')

            })
        }
        htmlToCanvas()
    });
})()