pdf.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import html2canvas from "html2canvas";
  2. import jsPDF from "jspdf";
  3. export const downloadPDF = page => {
  4. console.log(444);
  5. html2canvas(page).then(function(canvas) {
  6. canvas2PDF(canvas);
  7. });
  8. };
  9. const canvas2PDF = canvas => {
  10. let contentWidth = canvas.width;
  11. let contentHeight = canvas.height;
  12. // 一页pdf显示html页面生成的canvas高度;
  13. let pageHeight = contentWidth / 592.28 * 841.89 ;
  14. // let pageHeight = 841.89;
  15. // 未生成pdf的html页面高度
  16. let leftHeight = contentHeight;
  17. // 页面偏移
  18. let position = 0;
  19. // html页面生成的canvas在pdf中图片的宽高(本例为:横向a4纸[841.89,592.28],纵向需调换尺寸)
  20. let imgWidth = 592.28;
  21. let imgHeight = 592.28 / contentWidth * contentHeight;
  22. // let imgHeight = 841.89;
  23. let pageData = canvas.toDataURL('image/jpeg', 1.0);
  24. let PDF = new jsPDF('', 'pt', 'a4');
  25. // 两个高度需要区分: 一个是html页面的实际高度,和生成pdf的页面高度
  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('测试' + '.pdf')
  41. // let contentWidth = canvas.width;
  42. // let contentHeight = canvas.height;
  43. // console.log(contentWidth,contentHeight);
  44. // let imgHeight = contentHeight;
  45. // let imgWidth = contentWidth/2;
  46. // // 第一个参数: l:横向 p:纵向
  47. // // 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")
  48. // let pdf = new jsPDF('l', 'pt', 'a4');
  49. // pdf.addImage(
  50. // canvas.toDataURL("image/jpeg", 1.0),
  51. // "JPEG",
  52. // 0,
  53. // 0,
  54. // imgWidth,
  55. // imgHeight
  56. // );
  57. // pdf.save("导出.pdf");
  58. };