// 导出页面为PDF格式
|
import html2Canvas from 'html2canvas';
|
import JsPDF from 'jspdf';
|
|
export default function htmlToPdf(title=new Date().getTime()) {
|
return html2Canvas(document.body, {
|
// useCORS:true, //保证跨域图片的显示
|
// width:window.screen.availWidth, //显示canvas窗口的宽度
|
// height:window.screen.availHeight, //显示canvas窗口的高度
|
// windowHeight: document.body.scrollHeight, //获取y方向滚动条中的内容
|
// windowWidth: document.body.scrollWidth,//获取x方向滚动条中的内容
|
// x:0, //页面在水平方向上没有滚动,故设置为0
|
// y: window.pageXOffset //页面在垂直方向的滚动距离
|
}).then(function (canvas) {
|
let contentWidth = canvas.width;
|
let contentHeight = canvas.height;
|
let pageHeight = contentWidth / 592.28 * 841.89;
|
let leftHeight = contentHeight;
|
let position = 0;
|
// let imgWidth = 595.28;
|
// let imgHeight = 592.28 / contentWidth * contentHeight;
|
let imgWidth = 838.89;
|
let imgHeight = 835.89 / contentWidth * contentHeight;
|
|
// 将图片转化为dataUrl
|
let pageData = canvas.toDataURL('image/jpeg', 1.0);
|
|
// 三个参数,第一个方向(landscape横向?),第二个尺寸,第三个尺寸格式
|
let PDF = new JsPDF('landscape', 'pt', 'a4');
|
|
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度 (841.89)
|
//当内容未超过pdf一页显示的范围,无需分页
|
if (leftHeight < pageHeight) {
|
// 0, 0, 控制文字距离左边,与上边的距离,后两个参数控制添加图片的尺寸,此处将页面高度按照 a4纸宽高比列进行压缩
|
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');
|
});
|
|
}
|