html转换到pdf

xml 复制代码
<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单独处理

javascript 复制代码
// 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()
    });
})()
相关推荐
DT——1 小时前
Vite项目中eslint的简单配置
前端·javascript·代码规范
dawn1912282 小时前
SpringMVC 入门案例详解
java·spring·html·mvc
学习ing小白3 小时前
JavaWeb - 5 - 前端工程化
前端·elementui·vue
真的很上进4 小时前
【Git必看系列】—— Git巨好用的神器之git stash篇
java·前端·javascript·数据结构·git·react.js
胖虎哥er4 小时前
Html&Css 基础总结(基础好了才是最能打的)三
前端·css·html
Arisono4 小时前
财富之眼用经济思维看清世界PDF高清下载
pdf
qq_278063714 小时前
css scrollbar-width: none 隐藏默认滚动条
开发语言·前端·javascript
.ccl4 小时前
web开发 之 HTML、CSS、JavaScript、以及JavaScript的高级框架Vue(学习版2)
前端·javascript·vue.js
小徐不会写代码4 小时前
vue 实现tab菜单切换
前端·javascript·vue.js
Arisono4 小时前
android google play应用发布上架流程PDF下载
pdf