htmlToPdf.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. // var type = this.downType // 导出类型 true ->图片 false-> pdf
  9. var htmlID = document.getElementById('pdfDom')
  10. // window.pageYoffset = 0; // 如果有滚动条影响,会导致导出的内容不全,可以直接设置导出前置顶
  11. // document.documentElement.scrollTop = 0;
  12. // document.body.scrollTop = 0;
  13. html2Canvas(htmlID, {
  14. allowTaint: true,
  15. // scrollY: 50, // 偏移量吧,如果有滚动条影响,但是不想设置滚动条置顶, 可以设置这个,但是要计算滚动了多少
  16. // scrollX:0,
  17. // x:0, // 距离左边距离
  18. // y:10,
  19. // width: 1000,
  20. // height: 800
  21. // 下面两个用来提高清晰度
  22. // dpi: window.devicePixelRatio*4, //将分辨率提高到特定的DPI 提高四倍
  23. dpi: 300, //将分辨率提高到特定的DPI 提高四倍
  24. scale:4, //按比例增加分辨率
  25. useCORS: true // 【重要】开启跨域配置
  26. }).then(function (canvas) {
  27. var contentWidth = canvas.width*2;
  28. var contentHeight = canvas.height*2;
  29. //一页pdf显示html页面生成的canvas高度;
  30. var pageHeight = contentWidth / 592.28 * 841.89;
  31. //未生成pdf的html页面高度
  32. var leftHeight = contentHeight;
  33. //页面偏移
  34. var position = 0;
  35. //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
  36. var imgHeight = 590.28;
  37. var imgWidth = 841.89 ;
  38. // var imgHeight = 592.28/contentWidth * contentHeight;
  39. var pageData = canvas.toDataURL('image/png', 1.0);
  40. // console.log(pageData,1111)
  41. // this.imgUrl = pageData
  42. const el = document.createElement("a");
  43. // 设置 href 为图片经过 base64 编码后的字符串,默认为 png 格式
  44. el.href = pageData;
  45. el.download = title;
  46. // 创建一个点击事件并对 a 标签进行触发
  47. const event = new MouseEvent("click");
  48. el.dispatchEvent(event)
  49. // var pdf = new JsPDF('landscape', 'pt', 'a4');
  50. // //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
  51. // //当内容未超过pdf一页显示的范围,无需分页
  52. // if (leftHeight < pageHeight) {
  53. // console.log(imgWidth, imgHeight,222)
  54. // pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
  55. // } else { // 分页
  56. // while(leftHeight > 0) {
  57. // pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
  58. // leftHeight -= pageHeight;
  59. // position -= 841.89;
  60. // //避免添加空白页
  61. // if(leftHeight > 0) {
  62. // pdf.addPage();
  63. // }
  64. // }
  65. // }
  66. // pdf.save(title+'.pdf');
  67. })
  68. }
  69. }
  70. }