时间: 2023-06-19 【学无止境】 阅读量:共1420人围观
简介 将页面指定内容转为canvas,可实现分页下载,需安装html2canvas,使用js控制页面数量实现进度条。
实现代码
/* eslint-disable */
// 不使用JQuery版的
import html2canvas from 'html2canvas'
// 下载
function downloadPDF (num, count, pdf, colorWidth, colorNum, title) {
window.scrollTo(0, 0)
let ele = document.querySelector('#id_' + num)
let objWidth = count === 0 ? 100 : (parseInt((num / count) * 100) > 100 ? 100 : parseInt((num / count) * 100))
colorWidth.style.width = objWidth + '%'
colorNum.innerText = objWidth
let eleW = ele.offsetWidth // 获得该容器的宽
let eleH = ele.offsetHeight // 获得该容器的高
let eleOffsetTop = ele.offsetTop // 获得该容器到文档顶部的距离
let eleOffsetLeft = ele.offsetLeft // 获得该容器到文档最左的距离
var canvas = document.createElement('canvas')
var abs = 0
let win_in = document.documentElement.clientWidth || document.body.clientWidth // 获得当前可视窗口的宽度(不包含滚动条)
let win_out = window.innerWidth // 获得当前窗口的宽度(包含滚动条)
if (win_out > win_in) {
abs = (win_out - win_in) / 2 // 获得滚动条宽度的一半
}
canvas.width = eleW * 2 // 将画布宽&&高放大两倍
canvas.height = eleH * 2
var context = canvas.getContext('2d')
context.scale(2, 2)
context.translate(-eleOffsetLeft - abs, -eleOffsetTop)
// 这里默认横向没有滚动条的情况,因为offset.left(),有无滚动条的时候存在差值,因此
// translate的时候,要把这个差值去掉
html2canvas(ele, {
async: false,
dpi: 300,
scale: 2, //设置缩放
// allowTaint: true, //允许 canvas 污染, allowTaint参数要去掉,否则是无法通过toDataURL导出canvas数据的
useCORS: true //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
}).then((canvas) => {
var contentWidth = canvas.width
var contentHeight = canvas.height
//一页pdf显示html页面生成的canvas高度;
var pageHeight;
//一页pdf显示html页面生成的canvas高度;
if (eleW < eleH) {
pageHeight = contentWidth / 595.28 * 841.89
} else {
pageHeight = contentWidth / 841.89 * 595.28
}
//未生成pdf的html页面高度
var leftHeight = contentHeight
//页面偏移
var position = 0
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth, imgHeight
if (eleW < eleH) {
imgWidth = 595.28;
imgHeight = 595.28/contentWidth * contentHeight
} else {
imgWidth = 841.89
imgHeight = 841.89/contentWidth * contentHeight
}
var pageData = canvas.toDataURL('_uploads/photos/jpeg', 1.0)
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 10) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
//避免添加空白页
if (leftHeight > 10) {
pdf.addPage()
}
}
}
//可动态生成
if (num === count) {
pdf.save(title)
} else {
pdf.addPage()
num++
downloadPDF(num, count, pdf, colorWidth, colorNum, title)
}
})
}
export default {
downloadPDF
}