vue.jsdomprintingvue-componentprinting-web-page

Call vue-html-to-paper print function on a new window


I have a Vue component I'd like to print. When the user presses a print button, a function is called which opens the component in a new window to isolate the HTML, and get the formatting right.

    async openPrintDetailsDialogue() {
      const prtHtml = document.getElementById('printable').innerHTML;
      let stylesHtml = '';
      for (const node of [...document.querySelectorAll('link[rel="stylesheet"], style')]) {
        stylesHtml += node.outerHTML;
      }
      var newWindow = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
      newWindow.document.write(`<!DOCTYPE html>
        <html>
          <head>
            ${stylesHtml}
          </head>
          <body id="printme">
            ${prtHtml}
          </body>
        </html>`);
      newWindow.document.close();
      newWindow.focus();
      ...

I then try to print using $htmlToPaper.

      ...
      await this.$htmlToPaper('printme');
      newWindow.close();
    }

However, the main window alerts Element to print #printme not found!.

I add the plugin VueHtmlToPaper in my mounted() function:


  mounted() {
    Vue.use(VueHtmlToPaper);
  }

I've already tried passing my existing styles.css to the $htmlToPaper() call options, which changed nothing. I also have some styles in my vue file's <style scoped>, which couldn't be included in the options parameter either.

How can I get VueHtmlToPaper to "point" to newWindow?


Solution

  • By opening a new window you have a new separate webpage, where is no Vue Js instance. It does not work so and you will not make it work this way. You should use a Modal, change the current page or make a new page with Vue instance for printing.