12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- // 导出页面为PDF格式
- import html2Canvas from 'html2canvas'
- import JsPDF from 'jspdf'
- export default {
- install(Vue, options) {
- Vue.prototype.getPdf = function () {
- var title = this.htmlTitle // 导出名称
- // var type = this.downType // 导出类型 true ->图片 false-> pdf
- var htmlID = document.getElementById('pdfDom')
- // window.pageYoffset = 0; // 如果有滚动条影响,会导致导出的内容不全,可以直接设置导出前置顶
- // document.documentElement.scrollTop = 0;
- // document.body.scrollTop = 0;
- html2Canvas(htmlID, {
- allowTaint: true,
- // scrollY: 50, // 偏移量吧,如果有滚动条影响,但是不想设置滚动条置顶, 可以设置这个,但是要计算滚动了多少
- // scrollX:0,
- // x:0, // 距离左边距离
- // y:10,
- // width: 1000,
- // height: 800
- // 下面两个用来提高清晰度
- // dpi: window.devicePixelRatio*4, //将分辨率提高到特定的DPI 提高四倍
- dpi: 300, //将分辨率提高到特定的DPI 提高四倍
- scale:4, //按比例增加分辨率
- useCORS: true // 【重要】开启跨域配置
- }).then(function (canvas) {
- var contentWidth = canvas.width*2;
- var contentHeight = canvas.height*2;
- //一页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 imgHeight = 590.28;
- var imgWidth = 841.89 ;
- // var imgHeight = 592.28/contentWidth * contentHeight;
- var pageData = canvas.toDataURL('image/png', 1.0);
- // console.log(pageData,1111)
- // this.imgUrl = pageData
- const el = document.createElement("a");
- // 设置 href 为图片经过 base64 编码后的字符串,默认为 png 格式
- el.href = pageData;
- el.download = title;
- // 创建一个点击事件并对 a 标签进行触发
- const event = new MouseEvent("click");
- el.dispatchEvent(event)
- // var pdf = new JsPDF('landscape', 'pt', 'a4');
- // //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
- // //当内容未超过pdf一页显示的范围,无需分页
- // if (leftHeight < pageHeight) {
- // console.log(imgWidth, imgHeight,222)
- // 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');
- })
- }
- }
- }
|