printPdf.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import html2canvas from 'html2canvas'
  2. import jsPDF from 'jspdf'
  3. export default function printPdf(selecters, name='导出') {
  4. html2canvas(document.querySelector('#studentInfo'), {
  5. // 背景设为白色(默认为黑色)
  6. background: '#fff',
  7. dpi: 400, // 导出pdf清晰度,DPI越低,扫描的清晰度越低
  8. scale: 3
  9. }).then(canvas => {
  10. // document.body.appendChild(canvas)
  11. const contentWidth = canvas.width
  12. const contentHeight = canvas.height
  13. // 一页pdf显示html页面生成的canvas高度;
  14. var pageHeight = contentWidth / 592.28 * 841.89
  15. // 未生成pdf的html页面高度
  16. var leftHeight = contentHeight
  17. // pdf页面偏移
  18. var position = 0
  19. // html页面生成的canvas在pdf中图片的宽高(a4纸的尺寸[595.28,841.89])
  20. var imgWidth = 595.28
  21. var imgHeight = 592.28 / contentWidth * contentHeight
  22. var pageData = canvas.toDataURL('image/jpeg', 1.0)
  23. // eslint-disable-next-line
  24. var pdf = new jsPDF('', 'pt', 'a4')
  25. // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
  26. // 当内容未超过pdf一页显示的范围,无需分页
  27. if (leftHeight < pageHeight) {
  28. pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
  29. } else {
  30. while (leftHeight > 0) {
  31. pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
  32. leftHeight -= pageHeight
  33. position -= 841.89
  34. // 避免添加空白页
  35. if (leftHeight > 0) {
  36. pdf.addPage()
  37. }
  38. }
  39. }
  40. pdf.save(`${name}.pdf`)
  41. })
  42. }