经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
vue前端实现打印下载示例详解
来源:jb51  时间:2022/8/15 15:40:47  对本文有异议

html2canvas介绍

分享一下几个后台管理系统比较常用的插件:下载、打印

html2canvas是在浏览器上对网页进行截图操作,实际上是操作DOM,这个插件也有好长时间了,比较稳定,目前使用还没有遇到什么bug

jspdf介绍

如果下载出来是pdf文件,可以加上jspdf插件,会先通过html2canvas把页面转化成base64图片,再通过jspdf导出

安装

  1. npm i html2canvas jspdf
  2. yarn add html2canvas jspdf

使用

  1. <template>
  2. <div>
  3. <h1 ref="toPdf">
  4. 导出区域
  5. </h1>
  6. <button @click="toPdfFn">导出pdf</button>
  7. </div>
  8. </template>
  9. <script>
  10. import html2canvas from "html2canvas"
  11. import JSPDF from "jspdf"
  12. export default {
  13. methods:{
  14. toPdfFn(){
  15. this.htmlToPdf('文件名','时间')
  16. },
  17. htmlToPdf(name,time){
  18. let element = this.$refs.toPdf
  19. html2canvas(element, {
  20. logging: false
  21. }).then(function(canvas) {
  22. let pdf = new JSPDF("p", "mm", "a4") // A4纸,纵向
  23. let ctx = canvas.getContext("2d")
  24. let a4w = 190;
  25. let a4h = 277 // A4大小,210mm x 297mm,四边各保留20mm的边距,显示区域190x277
  26. let imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
  27. let renderedHeight = 0
  28. while (renderedHeight < canvas.height) {
  29. let page = document.createElement("canvas")
  30. page.width = canvas.width
  31. page.height = Math.min(imgHeight, canvas.height - renderedHeight) // 可能内容不足一页
  32. // 用getImageData剪裁指定区域,并画到前面创建的canvas对象中
  33. page.getContext("2d").putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight,
  34. canvas.height - renderedHeight)), 0, 0)
  35. pdf.addImage(page.toDataURL("image/jpeg", 1.0), "JPEG", 10, 10, a4w, Math.min(a4h, a4w * page.height /
  36. page.width)) // 添加图像到页面,保留10mm边距
  37. // 如果后面还有内容,添加一个空页
  38. renderedHeight += imgHeight
  39. if (renderedHeight < canvas.height) {
  40. pdf.addPage()
  41. }
  42. }
  43. pdf.save(name + time)
  44. })
  45. }
  46. }
  47. }
  48. </script>

注意点:

1、能使用ref来获取html结构就用ref,尽量不使用id。如果使用的地方比较多可以挂载到vue实例上

2、导出的pdf空白情况:检查dom结构有没有获取到,还有就是css样式要写在导出区域内的元素中

printjs介绍

之前是使用vue-print-nb插件的,但是这个插件有点猫病,有时候会出现样式跨域的问题,有时候又正常,后面在GitHub上找到的一个,用到现在也没出现过什么问题

在utils文件里面创建一个print.js文件

  1. // 打印类属性、方法定义
  2. /* eslint-disable */
  3. const Print = function (dom, options) {
  4. if (!(this instanceof Print)) return new Print(dom, options);
  5. this.options = this.extend({
  6. 'noPrint': '.no-print'
  7. }, options);
  8. if ((typeof dom) === "string") {
  9. this.dom = document.querySelector(dom);
  10. } else {
  11. this.isDOM(dom)
  12. this.dom = this.isDOM(dom) ? dom : dom.$el;
  13. }
  14. this.init();
  15. };
  16. Print.prototype = {
  17. init: function () {
  18. var content = this.getStyle() + this.getHtml();
  19. this.writeIframe(content);
  20. },
  21. extend: function (obj, obj2) {
  22. for (var k in obj2) {
  23. obj[k] = obj2[k];
  24. }
  25. return obj;
  26. },
  27. getStyle: function () {
  28. var str = "",
  29. styles = document.querySelectorAll('style,link');
  30. for (var i = 0; i < styles.length; i++) {
  31. str += styles[i].outerHTML;
  32. }
  33. str += "<style>" + (this.options.noPrint ? this.options.noPrint : '.no-print') + "{display:none;}</style>";
  34. return str;
  35. },
  36. getHtml: function () {
  37. var inputs = document.querySelectorAll('input');
  38. var textareas = document.querySelectorAll('textarea');
  39. var selects = document.querySelectorAll('select');
  40. for (var k = 0; k < inputs.length; k++) {
  41. if (inputs[k].type == "checkbox" || inputs[k].type == "radio") {
  42. if (inputs[k].checked == true) {
  43. inputs[k].setAttribute('checked', "checked")
  44. } else {
  45. inputs[k].removeAttribute('checked')
  46. }
  47. } else if (inputs[k].type == "text") {
  48. inputs[k].setAttribute('value', inputs[k].value)
  49. } else {
  50. inputs[k].setAttribute('value', inputs[k].value)
  51. }
  52. }
  53. for (var k2 = 0; k2 < textareas.length; k2++) {
  54. if (textareas[k2].type == 'textarea') {
  55. textareas[k2].innerHTML = textareas[k2].value
  56. }
  57. }
  58. for (var k3 = 0; k3 < selects.length; k3++) {
  59. if (selects[k3].type == 'select-one') {
  60. var child = selects[k3].children;
  61. for (var i in child) {
  62. if (child[i].tagName == 'OPTION') {
  63. if (child[i].selected == true) {
  64. child[i].setAttribute('selected', "selected")
  65. } else {
  66. child[i].removeAttribute('selected')
  67. }
  68. }
  69. }
  70. }
  71. }
  72. return this.dom.outerHTML;
  73. },
  74. writeIframe: function (content) {
  75. var w, doc, iframe = document.createElement('iframe'),
  76. f = document.body.appendChild(iframe);
  77. iframe.id = "myIframe";
  78. //iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
  79. iframe.setAttribute('style', 'position:absolute;width:0;height:0;top:-10px;left:-10px;');
  80. w = f.contentWindow || f.contentDocument;
  81. doc = f.contentDocument || f.contentWindow.document;
  82. doc.open();
  83. doc.write(content);
  84. doc.close();
  85. var _this = this
  86. iframe.onload = function(){
  87. _this.toPrint(w);
  88. setTimeout(function () {
  89. document.body.removeChild(iframe)
  90. }, 100)
  91. }
  92. },
  93. toPrint: function (frameWindow) {
  94. try {
  95. setTimeout(function () {
  96. frameWindow.focus();
  97. try {
  98. if (!frameWindow.document.execCommand('print', false, null)) {
  99. frameWindow.print();
  100. }
  101. } catch (e) {
  102. frameWindow.print();
  103. }
  104. frameWindow.close();
  105. }, 10);
  106. } catch (err) {
  107. console.log('err', err);
  108. }
  109. },
  110. isDOM: (typeof HTMLElement === 'object') ?
  111. function (obj) {
  112. return obj instanceof HTMLElement;
  113. } :
  114. function (obj) {
  115. return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
  116. }
  117. };
  118. const MyPlugin = {}
  119. MyPlugin.install = function (Vue, options) {
  120. // 4. 添加实例方法
  121. Vue.prototype.$print = Print
  122. }
  123. export default MyPlugin

printjs源码在这里

在main.js中注册

  1. import Vue from "vue";
  2. import print from "./src/utils/print.js";
  3. Vue.use(print)

在需要的地方使用

  1. <template>
  2. <div>
  3. <h1 ref="print">
  4. <div>打印区域</div>
  5. </h1>
  6. <button @click="printFn">打印</button>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. methods: {
  12. printFn() {
  13. //传入dom结构即可
  14. this.$print(this.$refs.print);
  15. },
  16. },
  17. };
  18. </script>

注意:需使用ref获取dom节点,若直接通过id或class获取则webpack打包部署后打印内容为空 

指定不打印区域 方法

方法一. 添加no-print样式类

  1. <div class="no-print">不要打印我</div>

方法二. 自定义类名

  1. <div class="do-not-print-me-xxx">不要打印我</div>
  2. this.$print(this.$refs.print,{'no-print':'.do-not-print-me-xxx'}) // 使用

以上就是vue前端实现打印下载示例详解的详细内容,更多关于vue前端打印下载的资料请关注w3xue其它相关文章!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号