pdf.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. };