yii2打印一页内容

Print a page content in yii2

我遇到了打印页面内容的问题。我使用了 window.print(),但它打印了整个 window。我只需要在我的页面中打印一些内容。请给我一个解决方案。

代码:

<html>
  <head>
    <script>
      function printContent(el)
      {
         var restorepage = document.body.innerHTML;
         var printcontent = document.getElementById(el).innerHTML;
         document.body.innerHTML = printcontent;
         window.print();
         document.body.innerHTML = restorepage;
     }
   </script>
  </head> 
  <body> 
    <h1>My page</h1>
    <div id="div1">DIV 1 content...</div>
    <button onclick="printContent('div1')">Print Content</button>
  </body>
</html>

当我在内容的 div 中使用我的打印功能时,我能够打印内容页面。