关于javascript:html转pdf

6次阅读

共计 1315 个字符,预计需要花费 4 分钟才能阅读完成。

  1. 先 npm html2canvas jspdf
  2. 而后在 utils 增加 htmlToPdf.js

// 具体代码
import html2canvas from ‘html2canvas’
import JSPDF from ‘jspdf’
export default {
install(Vue, options) {

Vue.prototype.ExportSavePdf = function() {var element = document.getElementById('pdfDom')
  html2canvas(element, {logging: false}).then(function(canvas) {
    /**jspdf 将 html 转为 pdf 一页显示不截断,整体思路:* 1. 获取 DOM
     * 2. 将 DOM 转换为 canvas
     * 3. 获取 canvas 的宽度、高度(略微大一点)* 4. 将 pdf 的宽高设置为 canvas 的宽高
     * 5. 将 canvas 转为图片
     * 6. 实例化 jspdf,将内容图片放在 pdf 中(因为内容宽高和 pdf 宽高一样,就只须要一页,也避免内容截断问题)*/
    // 失去 canvas 画布的单位是 px 像素单位
    var contentWidth = 1062
    var contentHeight = canvas.height
    console.log('contentWidth', contentWidth)
    console.log('contentHeight', contentHeight)
    // 将 canvas 转为 base64 图片
    var pageData = canvas.toDataURL('image/jpeg', 1.0)

    // 设置 pdf 的尺寸,pdf 要应用 pt 单位 已知 1pt/1px = 0.75   pt = (px/scale)* 0.75
    // 2 为下面的 scale 缩放了 2 倍
    var pdfX = ((contentWidth + 10) / 2) * 0.75
    var pdfY = ((contentHeight + 20) / 2) * 0.75 // 20 为底部留白
    console.log(pdfX, pdfY, 'pdfx')
    // 设置内容图片的尺寸,img 是 pt 单位
    var imgX = pdfX - 20 // 设置 margin
    var imgY = (contentHeight / 2) * 0.75 // 内容图片这里不须要留白的间隔

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

    // 将内容图片增加到 pdf 中,因为内容宽高和 pdf 宽高一样,就只须要一页,地位就是 0,0
    PDF.addImage(pageData, 'jpeg', 10, 10, imgX, imgY)
    PDF.save('download.pdf')
  })
}

}
}

3.main.js 全局注册
import htmlToPdf from ‘../src/utils/htmlToPdf’
Vue.use(htmlToPdf)

4. 在 vue 组件外面应用
<el-button type=”primary” @click=”ExportSavePdf()”>PDF</el-button>

正文完
 0