如何仅打印选定的HTML元素

How to print only a selected HTML element?

本文关键字:HTML 元素 何仅 打印      更新时间:2023-09-26

我正在尝试用HTML实现打印功能。我知道我可以用window.print()打印整个页面,但如何只打印特定的页面元素?例如特定的CCD_ 2。

您可以使用特定于打印的CSS样式表,并隐藏除您想要打印的内容之外的所有内容。

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

只有no-print类将被隐藏,但任何带有print类的内容都将显示。

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

如果你熟悉jQuery,你可以使用jQuery打印元素插件,如下所示:

$('SelectorToPrint').printElement();

创建了一些通用的东西,用于任何HTML元素

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();
 }

用法:

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

希望得到帮助
问候
Gaurav Khurana

我找到了一个解决方案,它没有其他解决方案的问题。它将印刷元素复制到机身上,相当优雅和通用:

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);
}

唯一的限制是元素会丢失从以前的父元素继承的样式。但它适用于文档结构中的任意元素

简单的html和纯javascript效果最好。参数";这个";指的是当前id,因此该函数对所有id都是通用的。通过使用";引用textContent";而不是";ref.innerHTML";您只能提取文本内容进行打印。

html正文:

<div id="monitor" onclick="idElementPrint(this)">element to print
<img src="example.jpg" width="200">
</div>

纯javascript:

/*or:
monitor.textContent = "click me to print content";
const imga = new Image(200); //width
imga.src = "./example.jpg";
monitor.appendChild(imga);
*/
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.innerHTML);
  pri.document.close();
  pri.focus();
  pri.print();
  pri.onafterprint = () => { document.body.removeChild(iframe); }
}

如果您使用引导程序,只需将类名d-print-none添加到您不想在打印中显示的元素中

如果您使用JQuery,您可以使用clone执行以下操作:

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);
}

并像这样使用:printElement(document.getElementById('myElementToPrint'))

如果我很了解你,你可以使用CSS3打印你选择的HTML元素。

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

请注意,您只需要一个选择器。这允许您使用CSS类轻松打印一个元素或整个页面。

在这里,您可以查看一个工作示例:https://jsfiddle.net/gengns/d50m8ztu/

如果你需要用纯JS打印HTML元素,你可以打开一个只包含你想要打印的元素的窗口(没有任何HTML标记)。

例如,通过在新窗口中将图像作为文件打开,您可以打印图像本身,而无需将其包装在任何HTML中。

注意:"visible=none"实际上并没有使窗口不可见,但它允许将其作为单独的窗口(而不是选项卡)打开。

afterprint事件允许我们在打印对话框关闭时关闭窗口。event.target指向打开的窗口实例。

注意:必须在调用.print()之前分配afterprint,否则将不会调用它。

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

使用Print.Js可以轻松打印Html或选定Html添加Print.Js库

http://printjs.crabbly.com/
  <form method="post" action="#" id="printJS-form">
    ...
  </form>
 <button type="button" onclick="printJS('printJS-form', 'html')">
    Print Form
 </button>

添加此方法

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;
    }

此实现将创建并应用一个特殊的临时样式,该样式将隐藏打印介质上的所有元素,但要打印的元素除外。打印后,临时样式将被删除,因此您的文档将恢复到其初始状态。

随意调整特殊风格(如教皇尺寸、边距等)以满足您的需求。


/**
 * @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);
}

最简单的方法是:

elem = document.getElementById('elem').outerHTML
orig = document.documentElement.outerHTML
document.documentElement.outerHTML=elem
print()
document.documentElement.outerHTML = orig
  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);
  }

将要打印的元素的样式设置为position:fixed,然后使其覆盖整个页面。

这里有另一个(也许是更现代的?)解决方案:

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