Skip to content
Advertisement

How can I use window print in modal vue?

My vue component like this :

<template>
    ...
    <b-modal id="modalInvoice" size="lg"  title="Invoice">
        <Invoice/>
        <div slot="modal-footer" class="w-100"> 
            <b-btn size="sm" class="float-right" variant="warning" @click="show=false">
                <i class="fa fa-print"></i> Print
            </b-btn>
        </div>
    </b-modal>

    ...
        <b-btn variant="warning" class="btn-square mt-2" v-b-modal.modalInvoice @click="checkout()"><i class="fa fa-credit-card-alt"></i>Checkout</b-btn>
    ...
</template>
<script>
    ...
    export default {
        ...
        methods: {
            print() {
                window.print()
            }
        }
    }
</script>

If I click print button, it works. But it displays the entire website. I just want if I click the print button, it only shows the contents of the modal

How can I do it?

Advertisement

Answer

One way to doing this is by creating a clone of the modal and using css to limit visibility of what’s printed:

print () {
  const modal = document.getElementById("modalInvoice")
  const cloned = modal.cloneNode(true)
  let section = document.getElementById("print")

  if (!section) {
     section  = document.createElement("div")
     section.id = "print"
     document.body.appendChild(section)
  }

  section.innerHTML = "";
  section.appendChild(cloned);
  window.print();
}

@media screen {
  #print {
    display: none;
   }
}

@media print {
 body * {
  visibility:hidden;
  }
  #print, #print * {
    visibility:visible;
  }
  #print {
    position:absolute;
    left:0;
    top:0;
  }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement