exportPdf.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // 导出页面为PDF格式
  2. import html2Canvas from 'html2canvas'
  3. import JsPDF from 'jspdf'
  4. export default{
  5. install (Vue, options) {
  6. Vue.prototype.getPdf = function () {
  7. var title = this.htmlTitle
  8. html2Canvas(document.querySelector('#pdfDom'), {
  9. allowTaint: true
  10. }).then(function (canvas) {
  11. var pdf = new JsPDF('p', 'mm', 'a4') // A4纸,纵向
  12. var ctx = canvas.getContext('2d')
  13. var a4w = 210;
  14. var a4h = 297 // A4大小,210mm x 297mm,四边不保留边距,显示区域210x297 (四边各保留20mm的边距,显示区域170x257)(pass)
  15. var imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
  16. var renderedHeight = 0
  17. while (renderedHeight < canvas.height) {
  18. var page = document.createElement('canvas')
  19. page.width = canvas.width
  20. page.height = Math.min(imgHeight, canvas.height - renderedHeight) // 可能内容不足一页
  21. // 用getImageData剪裁指定区域,并画到前面建立的canvas对象中
  22. page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
  23. pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面,保留10mm边距
  24. renderedHeight += imgHeight
  25. if (renderedHeight < canvas.height) {
  26. pdf.addPage()
  27. } // 若是后面还有内容,添加一个空页
  28. // delete page;
  29. }
  30. pdf.save(title + '.pdf')
  31. })
  32. }
  33. }
  34. }