pdf.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import html2canvas from 'html2canvas'
  2. import jsPDF from 'jspdf'
  3. export const downloadPDF = page => {
  4. html2canvas(page).then(function (canvas) {
  5. canvas2PDF(canvas)
  6. })
  7. }
  8. const canvas2PDF = canvas => {
  9. let contentWidth = canvas.width
  10. let contentHeight = canvas.height
  11. //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
  12. let imgWidth = 595.28
  13. let imgHeight = (592.28 / contentWidth) * contentHeight
  14. //let imgHeight = 700/contentWidth * contentHeight;
  15. //一页pdf显示html页面生成的canvas高度;
  16. var pageHeight = (contentWidth / 592.28) * 841.89
  17. let totalHeight = contentHeight
  18. // 第一个参数: l:横向 p:纵向
  19. // 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")
  20. let pdf = new jsPDF('p', 'pt')
  21. let position = 0
  22. // pdf.addImage(
  23. // canvas.toDataURL("image/jpeg", 1.0),
  24. // "JPEG",
  25. // 0,
  26. // 0,
  27. // imgWidth,
  28. // imgHeight
  29. // );
  30. if (totalHeight < pageHeight) {
  31. pdf.addImage(canvas.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, imgWidth, imgHeight)
  32. } else {
  33. while (totalHeight > 0) {
  34. pdf.addImage(canvas.toDataURL('image/jpeg', 1.0), 'JPEG', 0, position, imgWidth, imgHeight)
  35. totalHeight -= pageHeight
  36. position -= 841.89
  37. //避免添加空白页
  38. if (totalHeight > 0) {
  39. pdf.addPage()
  40. }
  41. }
  42. }
  43. // pdf.addImage(
  44. // canvas.toDataURL("image/jpeg", 1.0),
  45. // "JPEG",
  46. // 0,
  47. // position,
  48. // imgWidth,
  49. // imgHeight
  50. // );
  51. pdf.save('导出.pdf')
  52. }