前端页面导出为PDF

397 阅读1分钟
  1. 要用到2个组件
    第一个.将页面html转换成图片
    npm install --save html2canvas 
    第二个.将图片生成pdf
    npm install jspdf --save
  1. 定义全局函数..创建一个htmlToPdf.js文件在指定位置,并且处理成文件流以便上传至后台服务器
// 导出页面为PDF格式
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';

/**
 *Base64字符串转二进制
 */
function dataURLtoBlob (dataurl) {
  var arr = dataurl.split(',');
  var mime = arr[0].match(/:(.*?);/)[1];
  var bstr = atob(arr[1]);
  var n = bstr.length;
  var u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  // 转换成file对象
  // return new File([u8arr], this.filename, {type: mime});
  return new Blob([u8arr], {
    type: mime
  });
}
// 将blob转换为file
function blobToFile (theBlob, fileName) {
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
}
export default {
  install (Vue, options) {
    Vue.prototype.getPdfForHtml = function (domValue, filename) {
      return html2Canvas(document.querySelector(domValue), {
        allowTaint: true
      }).then(function (canvas) {
        const contentWidth = canvas.width;
        const contentHeight = canvas.height;
        const pageHeight = (contentWidth / 592.28) * 841.89;
        let leftHeight = contentHeight;
        let position = 0;
        const imgWidth = 595.28;
        const imgHeight = (592.28 / contentWidth) * contentHeight;
        const pageData = canvas.toDataURL('image/jpeg', 1.0);
        const PDF = new JsPDF('', 'pt', 'a4');
        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')// 这句话可以在前端下载
        var buffer = PDF.output('datauristring');
        const blob = dataURLtoBlob(buffer);
        var file = blobToFile(blob, filename);
        return file
      });
    };
  }
};

  1. 在main.js中使用我们定义的函数文件
import htmlToPdf from '@/utils/htmlToPdf'
Vue.use(htmlToPdf)
  1. 要下载pdf或获取文件流,直接调用getPdfForHtml('#id')即可