How to print a portion of an HTML page?

前端 未结 4 1795
Happy的楠姐
Happy的楠姐 2021-01-13 06:35

I have an html page i want to print a portion of this html page, I know a javascript function to print a page,

onClick=\"javascript:window.print(); return fa         


        
相关标签:
4条回答
  • 2021-01-13 07:03

    You can apply a CSS style to hide everything but what you want printed for media="print" using Javascript.

    You can also load the page in another window or a [hidden] <iframe> and print that.

    0 讨论(0)
  • 2021-01-13 07:03

    If you want to implement multiple "Print this section" features on a page, then print media stylesheets (described in other answers) are the way forward…

    … but combine that with alternative stylesheets so you can switch to one for each section.

    0 讨论(0)
  • 2021-01-13 07:10

    You should use a separate css for the print media. This allows you to hide/show portions of the page when it gets printed.

    html :

    <div class="dont-print-that">
       blah
    </div>
    print this!
    

    include:

    <link rel="stylesheet" type="text/css" media="print" href="print.css" />
    

    print.css

    .dont-print-that{display:none;}
    

    The other solution is to open a new window with only the content you want to print. You could either do that in a popup or an iframe. Personally I find the CSS solution more elegant, but that's up to you.

    0 讨论(0)
  • 2021-01-13 07:22

    It can be done using JavaScript and iframes:

    1. Dump the innerHTML of the container into the iFrame (plus any print-specific CSS
    2. print the iFrame contents.

    Try it out in JSFiddle

    You can see the code here, but it won't work due to what are probably security limitations in StackOverflow's renderer.

    const printButton = document.getElementById('print-button');
    
    printButton.addEventListener('click', event => {
      // build the new HTML page
      const content = document.getElementById('name-card').innerHTML;
      const printHtml = `<html>
          <head>
              <meta charset="utf-8">
              <title>Name Card</title>
          </head>
          <body>${content}</body>
      </html>`;
          
      // get the iframe
      let iFrame = document.getElementById('print-iframe');
      
      // set the iFrame contents and print
      iFrame.contentDocument.body.innerHTML = printHtml;
      iFrame.focus();
        iFrame.contentWindow.print();
      
    });
    <h1>Print your name badge</h1>
    <div id="name-card" class="card">
      <p>Hello my name is</p>
      <h2>Max Powers</h2>
    </div>
    <p>You will be required to wear your name badge at all times</p>
    <a id="print-button" class="btn btn-primary">Print</a>
    
    <iframe id="print-iframe" width="0" height="0"></iframe>

    0 讨论(0)
提交回复
热议问题