htmlToPdf.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // 导出页面为PDF格式--测试-wzw
  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. useCORS: true//解决跨域问题
  11. }).then(function (canvas) {
  12. let contentWidth = canvas.width
  13. let contentHeight = canvas.height
  14. let pageHeight = contentWidth / 592.28 * 841.89
  15. let leftHeight = contentHeight
  16. let position = 0
  17. let imgWidth = 595.28
  18. let imgHeight = 592.28 / contentWidth * contentHeight
  19. let pageData = canvas.toDataURL('image/jpeg', 1.0)
  20. let PDF = new JsPDF('', 'pt', 'a4')
  21. if (leftHeight < pageHeight) {
  22. PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
  23. } else {
  24. while (leftHeight > 0) {
  25. PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
  26. leftHeight -= pageHeight
  27. position -= 841.89
  28. if (leftHeight > 0) {
  29. PDF.addPage()
  30. }
  31. }
  32. }
  33. PDF.save(title + '.pdf')
  34. }
  35. )
  36. }
  37. }
  38. }