How to print a portion of an HTML page?

前端 未结 4 1798
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: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 = `
          
              
              Name Card
          
          ${content}
      `;
          
      // 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();
      
    });

    Print your name badge

    Hello my name is

    Max Powers

    You will be required to wear your name badge at all times

    Print

提交回复
热议问题