简体   繁体   中英

How to print only a selected HTML element?

I am trying to implement a print feature in HTML. I know I can print the whole page with window.print() , but how do I print only a specific page element? For example a particular <DIV>Some text to print</DIV> .

You could use a print specific CSS stylesheet and hide everything but what you want printed.

<div class="no-print">I won't print</div><div class="something-else">I will!</div>

Just the no-print class will be hidden, but anything with a print class will show.

<style type="text/css" media="print">
   .no-print { display: none; }
</style>

If you are familiar to jQuery, you can use jQuery Print Element plugin like this:

$('SelectorToPrint').printElement();

Created something generic to use on any HTML element

HTMLElement.prototype.printMe = printMe;
function printMe(query){
  var myframe = document.createElement('IFRAME');
  myframe.domain = document.domain;
  myframe.style.position = "absolute";
  myframe.style.top = "-10000px";
  document.body.appendChild(myframe);
  myframe.contentDocument.write(this.innerHTML) ;
  setTimeout(function(){
  myframe.focus();
  myframe.contentWindow.print();
  myframe.parentNode.removeChild(myframe) ;// remove frame
  },3000); // wait for images to load inside iframe
  window.focus();
 }

Usage:

document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();

Hope this help
Regards
Gaurav Khurana

Simple html and pure javascript works best. Parameter "this" refers to current id, so that function is universal for all ids with textual content.

html body:

<div id="monitor" onclick="idElementPrint(this)">text i want to print</div>

pure javascript:

//or: monitor.textContent = "click me to print textual content";

const idElementPrint = ref => {
  const iframe = document.createElement("iframe");
  iframe.style.display = "none";
  document.body.appendChild(iframe);
  const pri = iframe.contentWindow;
  pri.document.open();
  pri.document.write(ref.textContent);
  pri.document.close();
  pri.focus();
  pri.print();
  pri.onafterprint = () => { document.body.removeChild(iframe); }
}

If you are using JQuery, you can use clone to do the following:

function printElement(e) {
  var ifr = document.createElement('iframe');
  ifr.style='height: 0px; width: 0px; position: absolute'
  document.body.appendChild(ifr);

  $(e).clone().appendTo(ifr.contentDocument.body);
  ifr.contentWindow.print();

  ifr.parentElement.removeChild(ifr);
}

and use like so: printElement(document.getElementById('myElementToPrint'))

If I understood you well you can use CSS3 to print your selected HTML element.

@media print {
  body.print-element *:not(.print) {
    display: none;
  }
}

Notice, that you just need a selector. This allows you to easily print an element or the entire page using CSS classes.

Here you can check a working example: https://jsfiddle.net/gengns/d50m8ztu/

If you're using bootstrap, just add classname d-print-none to the elements you don't want to display in print

Add this method

function printDiv(divName) {   
        let specific_element = document.getElementById(divName).innerHTML;
        let original_elements = document.body.innerHTML;
    
        document.body.innerHTML = specific_element;
        window.print();
        document.body.innerHTML = original_elements;
    }

If you need to print the HTML element with pure JS, you can open a window that contains only the element you want to print (without any HTML-markup).

For instance, you can print the image itself without wrapping it in any HTML by opening this image in a new window as a file.

Note: 'visible=none' doesn't actually make the window invisible, but it allows to open it as a separate window (not a tab).

afterprint event allows us to close the window when the printing dialog is closed. event.target points to the opened window instance.

Note: afterprint MUST be assigned before calling.print(), otherwise it would not be called.

let win = window.open('/absolute/image/path.jpg', '__blank', 'visible=none');
win.addEventListener('afterprint', event => event.target.close() );
win.print();

I found a solution that doesn't have the problems other solutions have. It copies the printed element to the body, and is fairly elegant and general:

CSS:

@media print {
  body *:not(.printable, .printable *) {
    // hide everything but printable elements and their children
    display: none;
  }
}

JS:

function printElement(e) {
  let cloned = e.cloneNode(true);
  document.body.appendChild(cloned);
  cloned.classList.add("printable");
  window.print();
  document.body.removeChild(cloned);
}

The only limitation is that the element loses styles it inherited from its previous parents. But it works on arbitrary elements in the document structure

Printing an Html or a Selected Html is easy using Print.Js Add Print.Js Library

http://printjs.crabbly.com/

  <form method="post" action="#" id="printJS-form">
    ...
  </form>

 <button type="button" onclick="printJS('printJS-form', 'html')">
    Print Form
 </button>

The simplest way to do it is:

elem = document.getElementById('elem').outerHTML

orig = document.documentElement.outerHTML

document.documentElement.outerHTML=elem
print()

document.documentElement.outerHTML = orig

This implementation will create and apply an ad-hoc temporary style that hides all the elements on print media except the one that we want to print. After the printing the temporary style is removed, so your document will get back to its initial state.

Feel free to adjust the ad-hoc style (like papar size, margins, etc) to fit your needs.


/**
 * @description Print the given element using browser built-in function
 * @param {HTMLElement} element
 */
function printElement(element) {
  if (!element) {
    throw new Error(`Invalid print target element`);
  }

  const printWrapper = "print-wrapper";
  const printElement = "print-element";
  const css = `
  body.${printWrapper} *:not(.${printElement}) {
    visibility:hidden;
  }
  body.${printWrapper} .${printElement} {
    width: 210mm;
    height: 297mm;
    left:0;
    top:0;
    position:fixed;
  }
  body.${printWrapper} .${printElement} * {
    visibility:initial;
    margin: 0;
  }
  `;

  const head = document.getElementsByTagName("head")[0];
  const style = document.createElement("style");

  style.setAttribute("type", "text/css");
  style.setAttribute("media", "print");

  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }

  head.appendChild(style);

  document.body.classList.add(printWrapper);
  element.classList.add(printElement);

  window.print();

  document.body.classList.remove(printWrapper);
  element.classList.remove(printElement);

  head.removeChild(style);
}
  function printDomElement(element) {
    element.classList.add("printCss");

    let printId = "printSvgId";
    let name = ".printCss";
    let rules = "-webkit-print-color-adjust:exact;height:100%;width:100%;position:fixed;top:0;left:0;margin:0;";

    var style = document.createElement('style');
    style.id = printId;
    style.media = "print";
    document.getElementsByTagName('head')[0].appendChild(style);

    if (!(style.sheet || {}).insertRule)(style.styleSheet || style.sheet).addRule(name, rules);
    else style.sheet.insertRule(name + "{" + rules + "}", 0);

    window.print();

    setTimeout(() => {
      element.classList.remove("printCss");
      let elem = document.getElementById(printId);
      if (elem) elem.remove();
    }, 500);

  }

Here is another (perhaps a more modern?) solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM