Is there a way to implement window printing within a Vue modal?

Behold my brilliant Vue component:

<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>

The issue at hand arises when clicking on the print button. The entire website appears in the print preview, while the intention was for only the modal content to be displayed.

A query emerges - how can this printing predicament be resolved?

Answer №1

To achieve this, one method is to duplicate the modal and utilize CSS to control the visibility of the content being printed:

print () {
  const invoiceModal = document.getElementById("modalInvoice");
  const clonedModal = invoiceModal.cloneNode(true);
  let printSection = document.getElementById("print");

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

  printSection.innerHTML = "";
  printSection.appendChild(clonedModal);
  window.print();
}

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

@media print {
  body * {
    visibility: hidden;
  }
  #print, #print * {
    visibility: visible;
  }
  #print {
    position: absolute;
    left: 0;
    top: 0;
  }
}

Answer №2

Enjoyed Brian's response, so I decided to create my own version using Vue 2 and Typescript

display(): void {
const modal = this.$refs['modalContent'] as HTMLElement;
const clonedModal: Node | null =
  modal && modal.cloneNode(true);

let displaySection = this.$refs.displayArea as HTMLElement;
if (!displaySection) {
  displaySection = document.createElement('div');
  displaySection.id = 'printPreview';
  document.body.appendChild(displaySection);
}

displaySection.innerHTML = '';
clonedModal && displaySection.appendChild(clonedModal);
window.print();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

showcasing every element from a multi-layered array within its own separate div using JavaScript

Is it possible to loop through a multidimensional array made up of 9 arrays with 9 elements each and display each item in a separate div? I want each div to contain one array item. Here's the code I have been working on: Link to my approach ...

Is it possible to deploy a build across various website subdomains without altering user data?

Currently, I am in the midst of developing a project for a client where I am responsible for both the front end and back end components. After much consideration, I have opted to use Remix due to my familiarity with React and proficiency in JavaScript/Type ...

Having trouble formatting JSON data in a jQuery datatable with accurate information

Currently, I am diving into the world of jQuery tables specifically for a report that I am working on. Despite successfully receiving the API response, I am facing challenges in binding it to the jQuery datatable. I have searched through various questions ...

What could be causing my code to have a pending promise when I am using await?

Why am I still getting pending promises even though I've used await in the getCart() method? Is there something fundamentally wrong with my code? I would greatly appreciate some help on this. Thank you! class User { constructor(..., cart) { / ...

Is the function failing to return a value?

I'm facing an issue with a certain piece of code that doesn't seem to be working as expected. Essentially, I have an array containing the accepted file types for a specific component. The code is designed to iterate over this array and check if t ...

Limiting the table width in TinyMCE

Currently, I am utilizing TinyMCE within a Vue application. I've set up TinyMCE with the table_grid: false configuration, causing a dialog to appear when a table is created. This dialog allows users to specify rows, columns, width, and more. Within t ...

I initially had ngRoute set up in my app, but decided to make the switch to ui-router. However, now it seems like

I currently have an application set up using express and angular. I decided to transition to ui-router in order to utilize multiple views, but it doesn't appear to be functioning as expected. app.js app.use(express.static(path.join(__dirname, ' ...

Efficiently accessing and displaying nested models in AngularJS

Currently, I am in the process of developing a website that involves numerous relational links between data. For instance, users have the ability to create bookings, which will include a booker and a bookee, as well as an array of messages that can be asso ...

Tips for stopping Angular from rendering a directive that is producing incorrect results after an error is thrown

My directives have a template and a compile function that modifies the template. Occasionally, Angular fails to recognize jQuery (and defaults to using jqLite), causing my compile to encounter errors. Despite this, Angular continues to render the directive ...

There was an error: Unable to access the 'axis' property because it is undefined

This is the code snippet I am working with: <html> <head> <meta charset="utf-8"> <title>a picture</title> <style> .axis path, .axis line{ fill: none; stro ...

What could be causing my express router.get endpoints with multiple paths to only render text?

Currently, I am in the process of configuring a password reset flow using Pug (formerly Jade) and Express. Oddly enough, GET requests that contain URLs with multiple appended paths are causing my Pug view files to render with only text. The images and sty ...

Navigating the Angular Element: A Guide to Clicking Buttons within Modal-Dialogs Using Protractor

I am currently creating an automation test for an angular application using the protractor framework. Test scenario: Click on the "Create PDF Report" button A modal-dialog window will appear Click on the "Run Report Now" button within the modal-d ...

Troubleshooting undefined index issue when retrieving data from database (related to Ajax functionality)

Despite following the instructions on w3schools, I am struggling to get the script to return the desired data when selecting a user from the dropdown menu. Instead, I keep receiving an error message stating "undefined index: userdrop". Could changing GET t ...

Is there a way to adjust the position of a Bootstrap 5 dropdown menu in real-time using javascript or jQuery?

Within my web app, I have implemented dynamically generated Bootstrap 5 dropdown menus that can sometimes be extensive. To optimize screen space usage, I am seeking a way to alter the offset computed by Popper.js through javascript. Unfortunately, I have e ...

Fetch() is not executing in the expected sequence

I've been working on setting up an API to pull a word and save it to state. A function should then read that state and perform its intended task. However, my original coding approach caused it to run out of order. The third code snippet was able to fi ...

Using JavaScript to issue a Windows authentication request for Kerberos

I have created a web API with Windows authentication enabled (using IIS as well). The issue arises when my client attempts to send an AJAX request to the web API, resulting in a 401 unauthorized response. Upon further investigation, it appears that the pr ...

Having trouble receiving a Java Response through Ajax when using dataType: "jsonp", but it works when using dataType: "text"

I am having trouble retrieving the Callback response value in ajax with the provided code snippet $.ajax({ type: 'POST', jsonpCallback: 'jsonCallback', contentType: 'application/json', url: apiurl, dataTyp ...

What is the best way to smoothly add or remove several classes to a div while scrolling?

Looking for assistance to create a fading effect where a logo fades out and a smaller version fades in as I scroll. The scaling aspect is currently functioning correctly on scroll (view JS Fiddle), but the fading transition needs some work, resulting in ch ...

Setting a specific time for a div element with opacity: A step-by-step guide

Is there a way to adjust the timing for the appearance of the add-to-cart when hovering over the product-list-item? Currently, it appears when I hover over the item and disappears when I move my mouse away. .product-list-item { position: relative; w ...

Angular UI Bootstrap Typeahead - Apply a class when the element is added to the document body

In my current project, I am utilizing angular bootstrap typeahead with multiple instances. Some of these instances are directly appended to the body using the "typeahead-append-to-body" option. Now, I have a specific instance where I need to customize the ...