htmlToPdf.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import html2Canvas from 'html2canvas'
  2. import JsPDF from 'jspdf'
  3. export default {
  4. install(Vue, options) {
  5. Vue.prototype.getPdf = function () {
  6. var title = this.htmlTitle
  7. html2Canvas(document.querySelector('#pdfDom'), {
  8. allowTaint: true,
  9. tianTest: false,
  10. }).then(function (canvas) {
  11. let contentWidth = canvas.width
  12. let contentHeight = canvas.height
  13. let pageHeight = contentWidth / 592.28 * 841.89
  14. let leftHeight = contentHeight
  15. let position = 0
  16. let imgWidth = 595.28
  17. let imgHeight = 592.28 / contentWidth * contentHeight
  18. let pageData = canvas.toDataURL('image/jpeg', 1.0)
  19. let PDF = new JsPDF('', 'pt', 'a4')
  20. if (leftHeight < pageHeight) {
  21. PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
  22. } else {
  23. while (leftHeight > 0) {
  24. PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
  25. leftHeight -= pageHeight
  26. position -= 841.89
  27. if (leftHeight > 0) {
  28. PDF.addPage()
  29. }
  30. }
  31. }
  32. PDF.save(title + '.pdf')
  33. }
  34. )
  35. }
  36. }
  37. }