遇到了两个问题
第一个:导出的只是的可见页面,滚动条之后的内容一片空白
第二个:如果页面很长,会造成分页,给人一种断层的感觉,特别是有图表的时候,这个时候就不想要分页的效果,就只能将页面导出一页
第一个问题的解决方法:查看文档的关于高度的配置选项,设置好height和windowHeight即可
源码呈上,拿走不用谢
Vue.prototype.$getPDF = function(){
const targetDom = document.querySelector('#app')
const title = '这是导出pdf的标题'
const options = {
allowTaint: true,
height: targetDom.scrollHeight,
windowHeight: targetDom.scrollHeight,
}
html2canvas(targetDom, options).then(function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 592.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 595.28;
var imgHeight = 592.28/contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var pdf = new jsPDF('', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
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(title + '.pdf');
});
}
关于第二个问题,不想要断层的效果
好吧,因为第一次记录,不知道怎么把图片放上来,在心里默认有图就好了,解决方法就是不分页,直接导出一页
上代码
Vue.prototype.$downPDF = function(){
const targetDom = document.querySelector('#app')
const title = '这是导出pdf的标题'
const options = {
allowTaint: true,
height: targetDom.scrollHeight,
windowHeight: targetDom.scrollHeight,
}
html2canvas(targetDom, options).then(function(canvas) {
var context = canvas.getContext('2d')
context.mozImageSmoothingEnabled = false
context.webkitImageSmoothingEnabled = false
context.msImageSmoothingEnabled = false
context.imageSmoothingEnabled = false
var pageData = canvas.toDataURL('image/jpeg', 1.0)
var img = new Image()
const width = document.querySelector('#app').offsetWidth // / 4
const height = document.querySelector('#app').offsetHeight
img.src = pageData
img.onload = function () {
// 获取dom高度、宽度
img.width = img.width / 2
img.height = img.height / 2
img.style.transform = 'scale(0.5)'
let pdf;
if (width > height) {
// 此可以根据打印的大小进行自动调节
// eslint-disable-next-line
pdf = new jsPDF('l', 'mm', [
width * 0.505,
height * 0.545
])
} else {
// eslint-disable-next-line
pdf = new jsPDF('p', 'mm', [
width * 0.505,
height * 0.545
])
}
pdf.addImage(
pageData,
'jpeg',
0,
0,
width * 0.505,
height * 0.545
)
pdf.save(title + '.pdf')
}
})
}
这里注意的点是,因为每个人的页面长度有可能不一样,所以要修改的是width的值,
const width = document.querySelector('#app').offsetWidth / 4
const width = document.querySelector('#app').offsetWidth / 3
const width = document.querySelector('#app').offsetWidth / 2
const width = document.querySelector('#app').offsetWidth
以上,分享给大家,希望能帮助到正在做同样功能的你