toPdf.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import html2canvas from 'html2canvas'
  2. import jsPDF from 'jspdf'
  3. export default (id, name) => {
  4. const demo = document.getElementById(id)
  5. demo.style.overflow = 'visible'
  6. html2canvas(demo, {
  7. useCORS: true, // 允许跨域
  8. scrollX: -8, // 修正x轴偏移
  9. height: document.getElementById(id).scrollHeight, //
  10. width: document.getElementById(id).scrollWidth, // 为了使横向滚动条的内容全部展示,这里必须指定
  11. background: '#FFFFFF' // 如果指定的div没有设置背景色会默认成黑色
  12. }).then(canvas => {
  13. var contentWidth = canvas.width
  14. var contentHeight = canvas.height
  15. // 一页pdf显示html页面生成的canvas高度;
  16. var pageHeight = (contentWidth / 595.28) * 841.89
  17. // 未生成pdf的html页面高度
  18. var leftHeight = contentHeight
  19. // pdf页面偏移
  20. var position = 0
  21. // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
  22. var imgWidth = 555.28
  23. var imgHeight = (555.28 / contentWidth) * contentHeight
  24. console.time('222')
  25. var pageData = canvas.toDataURL('image/png', 1)
  26. // eslint-disable-next-line new-cap
  27. var pdf = new jsPDF('', 'pt', 'a4')
  28. console.timeEnd('222')
  29. // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
  30. // 当内容未超过pdf一页显示的范围,无需分页
  31. console.time('444')
  32. if (leftHeight < pageHeight) {
  33. pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight)
  34. } else {
  35. while (leftHeight > 0) {
  36. pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
  37. leftHeight -= pageHeight
  38. position -= 841.89
  39. // 避免添加空白页
  40. if (leftHeight > 0) {
  41. pdf.addPage()
  42. }
  43. }
  44. }
  45. console.timeEnd('444')
  46. console.time('555')
  47. pdf.save(name + '.pdf')
  48. console.timeEnd('555')
  49. })
  50. demo.style.overflow = 'auto'
  51. }