htmlToPdf.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * @param html { String } DOM树
  3. * @param isOne { Boolean } 是否为单页 默认 否(false)
  4. * @param type { String } 类型 默认 A4(A4)
  5. * @return 文件 {pdf格式}
  6. */
  7. 'use strict'
  8. import {jsPDF} from 'jspdf'
  9. import html2canvas from 'html2canvas'
  10. export default async (html, isOne, type) => {
  11. let contentWidth = html.scrollWidth // 获得该容器的宽
  12. let contentHeight = html.scrollHeight // 获得该容器的高
  13. let canvas = document.createElement('canvas')
  14. let scale = 2 // 解决清晰度问题,先放大 2倍
  15. canvas.width = contentWidth // 将画布宽&&高放大两倍
  16. canvas.height = contentHeight
  17. canvas.getContext('2d').scale(scale, scale)
  18. let opts = {
  19. scale: scale,
  20. // canvas: canvas,
  21. width: contentWidth,
  22. height: contentHeight,
  23. dpi: window.devicePixelRatio * 2,
  24. backgroundColor: '#fff',
  25. useCORS: true
  26. }
  27. return html2canvas(html, opts).then(canvas => {
  28. let pageData = canvas.toDataURL('image/jpeg', 1.0) // 清晰度 0 - 1
  29. let pdf
  30. if (isOne) {
  31. // 单页
  32. console.log(contentWidth, 'contentWidth')
  33. console.log(contentHeight, 'contentHeight')
  34. // jspdf.js 插件对单页面的最大宽高限制 为 14400
  35. let limit = 14400
  36. if (contentHeight > limit) {
  37. let contentScale = limit / contentHeight
  38. contentHeight = limit
  39. contentWidth = contentScale * contentWidth
  40. }
  41. let orientation = 'p'
  42. // 在 jspdf 源码里,如果是 orientation = 'p' 且 width > height 时, 会把 width 和 height 值交换,
  43. // 类似于 把 orientation 的值修改为 'l' , 反之亦同。
  44. if (contentWidth > contentHeight) {
  45. orientation = 'l'
  46. }
  47. // orientation Possible values are "portrait" or "landscape" (or shortcuts "p" or "l")
  48. pdf = new jsPDF(orientation, 'mm', [contentWidth, contentHeight]) // 下载尺寸 a4 纸 比例
  49. // pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置
  50. pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight)
  51. } else {
  52. //一页 pdf 显示 html 页面生成的 canvas高度
  53. let pageHeight = (contentWidth / 210) * 297
  54. //未生成 pdf 的 html页面高度
  55. let leftHeight = contentHeight
  56. //页面偏移
  57. let position = 0
  58. //a4纸的尺寸[595.28,841.89],html 页面生成的 canvas 在pdf中图片的宽高
  59. let imgWidth = 210
  60. let imgHeight = (imgWidth / contentWidth) * contentHeight
  61. pdf = new jsPDF('', 'mm', 'a4') // 下载尺寸 a4 纸 比例
  62. //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
  63. //当内容未超过pdf一页显示的范围,无需分页
  64. if (leftHeight < pageHeight) {
  65. pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
  66. } else {
  67. while (leftHeight > 0) {
  68. pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
  69. leftHeight -= pageHeight
  70. position -= 297
  71. //避免添加空白页
  72. if (leftHeight > 0) {
  73. pdf.addPage()
  74. }
  75. }
  76. }
  77. }
  78. return pdf
  79. })
  80. }