exportPdf.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // 导出页面为PDF格式
  2. import html2Canvas from "html2canvas";
  3. import JsPDF from "jspdf";
  4. export default {
  5. install(Vue, options) {
  6. Vue.prototype.getPdf = function() {
  7. var title = this.htmlTitle;
  8. html2Canvas(document.querySelector("#pdfDom"), {
  9. allowTaint: true
  10. }).then(function(canvas) {
  11. var pdf = new JsPDF("p", "mm", "a4"); // A4纸,纵向
  12. var ctx = canvas.getContext("2d");
  13. var a4w = 210;
  14. var a4h = 297; // A4大小,210mm x 297mm,四边不保留边距,显示区域210x297 (四边各保留20mm的边距,显示区域170x257)(pass)
  15. var imgHeight = Math.floor((a4h * canvas.width) / a4w); // 按A4显示比例换算一页图像的像素高度
  16. var renderedHeight = 0;
  17. while (renderedHeight < canvas.height) {
  18. var page = document.createElement("canvas");
  19. page.width = canvas.width;
  20. page.height = Math.min(imgHeight, canvas.height - renderedHeight); // 可能内容不足一页
  21. // 用getImageData剪裁指定区域,并画到前面建立的canvas对象中
  22. page
  23. .getContext("2d")
  24. .putImageData(
  25. ctx.getImageData(
  26. 0,
  27. renderedHeight,
  28. canvas.width,
  29. Math.min(imgHeight, canvas.height - renderedHeight)
  30. ),
  31. 0,
  32. 0
  33. );
  34. pdf.addImage(
  35. page.toDataURL("image/jpeg", 1.0),
  36. "JPEG",
  37. 0,
  38. 0,
  39. a4w,
  40. Math.min(a4h, (a4w * page.height) / page.width)
  41. ); // 添加图像到页面,保留10mm边距
  42. renderedHeight += imgHeight;
  43. if (renderedHeight < canvas.height) {
  44. pdf.addPage();
  45. } // 若是后面还有内容,添加一个空页
  46. // delete page;
  47. }
  48. pdf.save(title + ".pdf");
  49. });
  50. };
  51. }
  52. };