prints.vue 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <template></template>
  2. <script>
  3. export default {
  4. methods: {
  5. init (obj) {
  6. var this_ = this;
  7. if(undefined != obj){
  8. this_.writeIframe(obj);
  9. }
  10. },
  11. writeIframe: function (content) {
  12. var w, doc, iframe = document.createElement('iframe'),
  13. f = document.body.appendChild(iframe);
  14. iframe.id = "myIframe";
  15. iframe.style = "position:absolute;width:0;height:0;";
  16. w = f.contentWindow || f.contentDocument;
  17. doc = f.contentDocument || f.contentWindow.document;
  18. doc.open();
  19. doc.write(content);
  20. doc.close();
  21. this.toPrint(w);
  22. setTimeout(function () {
  23. document.body.removeChild(iframe)
  24. }, 100)
  25. },
  26. toPrint: function (frameWindow) {
  27. try {
  28. setTimeout(function () {
  29. frameWindow.focus();
  30. try {
  31. if (!frameWindow.document.execCommand('print', false, null)) {
  32. frameWindow.print();
  33. }
  34. } catch (e) {
  35. frameWindow.print();
  36. }
  37. frameWindow.close();
  38. }, 10);
  39. } catch (err) {
  40. console.log('err', err);
  41. }
  42. }
  43. }
  44. }
  45. </script>