如何打印HTML页面的一部分?

6

我有一个HTML页面,想要打印其中的一部分内容。我知道一个JavaScript函数可以用来打印整个页面。

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

但是我怎么打印页面的一部分呢?

如果有人有想法,请与我分享。

4个回答

9

您应该使用单独的CSS文件来为打印媒体进行样式设置。这样可以在打印页面时隐藏/显示页面的部分内容。

HTML:

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

包含:

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

print.css

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

另一种解决方案是打开一个仅包含要打印内容的新窗口。您可以在弹出窗口或iframe中实现此操作。个人认为CSS解决方案更加优雅,但这取决于您的选择。

2

可以使用JavaScript和iframes来实现:

  1. 将容器的innerHTML转储到iFrame中(加上任何打印特定的CSS)
  2. 打印iFrame内容。

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>


1
如果您想在页面上实现多个“打印此部分”功能,则打印媒体样式表(在其他答案中描述)是前进的方式......但结合替代样式表,以便您可以切换到每个部分的样式表。

0

您可以使用JavaScript将CSS样式应用于media="print",以隐藏除所需打印内容以外的所有内容。

您还可以在另一个窗口或[隐藏的]<iframe>中加载页面并进行打印。


1
我不确定我理解了你的答案,但无需使用JavaScript。浏览器在打印时会使用正确的CSS重新绘制页面。 - Alsciende
@Alsciende,我知道。我理解问题是希望仅打印文档的一小部分,而不是整个文档。我的意思是他可以在打印开始之前插入用于打印介质的CSS规则,以便除了该小部分外,其他所有内容都被隐藏。 - strager

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接