如何在 JavaScript 中打印呈现的 HTML 页面的一部分?

IT技术 javascript jquery
2021-01-21 05:14:22

JavaScript 代码 window.print() 可以打印当前的 HTML 页面。

如果我在 HTML 页面中有一个 div(例如,从ASP.NET MVC视图呈现的页面),那么我只想打印 div。

是否有任何 jQuery unobtrusive JavaScript或普通 JavaScript 代码来实现此请求?

更清楚一点,假设呈现的 HTML 页面如下所示:

<html xmlns="http://www.w3.org/1999/xhtml">

    <head id="Head" runat="server">
        <title>
            <asp:ContentPlaceHolder runat="server" ID="TitleContent" />
        </title>
    </head>

    <body>
            <div id="div1" class="div1">....</div>
            <div id="div2" class="div2">....</div>
            <div id="div3" class="div3">....</div>
            <div id="div4" class="div4">....</div>
            <div id="div4" class="div4">....</div>
        <p>
            <input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" />
        </p>
    </body>
</html>

然后我想点击打印按钮,只打印 div3。

5个回答

我会像这样去做:

<html>
    <head>
        <title>Print Test Page</title>
        <script>
            printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
            function printDiv(divId) {
                window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
                window.frames["print_frame"].window.focus();
                window.frames["print_frame"].window.print();
            }
        </script>
    </head>

    <body>
        <h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
        <b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>
        <div id="div1">This is the div1's print output</div>
        <br><br>
        <b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>
        <div id="div2">This is the div2's print output</div>
        <br><br>
        <b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
        <div id="div3">This is the div3's print output</div>
        <iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
    </body>
</html>
这似乎不再起作用 - 至少在 Chrome 中。打印对话框在 CSS 应用于 iframe 内容之前打开。
2021-03-19 05:14:22
我查了一下情况。默认情况下,IE7 将打印活动框架,所以我必须 focus() 框架。它不会让我 focus() “visibility: hidden” 内容,所以我不得不删除那一点样式格式。框架的宽度、高度和框架边框已经为 0,因此即使没有样式格式,它也会隐藏。这样,一切正常。哦,最后要注意的是,如果用户尝试按 CTRL+F 搜索页面,他们的搜索可能会在框架内找到匹配项,而他们看不到匹配项。完成打印后,您必须将框架清空以修复该框架。
2021-03-20 05:14:22
@CodingWithStyle 如果您解释了您的方法/解决方案而不仅仅是提供代码,那么这个答案会更有用。
2021-03-23 05:14:22
window.frames["print_frame"].window.focus(); setTimeout(function() { window.frames["print_frame"].window.print(); }, 0);
2021-03-26 05:14:22
如果您需要使用样式表格式化您正在打印的内容,printDivCSS 就在那里。如果您不希望您的打印文本使用样式表进行格式化,那么您就不需要它。
2021-03-28 05:14:22

与一些建议一样,您至少需要执行以下操作:

  • 通过 JavaScript 动态加载一些 CSS
  • 制作一些特定于打印的 CSS 规则
  • 通过 JavaScript 应用你喜欢的 CSS 规则

一个示例 CSS 可以像这样简单:

@media print {
  body * {
    display:none;
  }

  body .printable {
    display:block;
  }
}

然后,您的 JavaScript 只需要将“可打印”类应用于您的目标 div,并且在打印时它将是唯一可见的(只要没有其他冲突的 CSS 规则——单独的练习)。

<script type="text/javascript">
  function divPrint() {
    // Some logic determines which div should be printed...
    // This example uses div3.
    $("#div3").addClass("printable");
    window.print();
  }
</script>

您可能希望在打印发生后选择性地从目标中删除该类,和/或在打印发生后删除动态添加的 CSS。

下面是一个完整的工作示例,唯一的区别是打印 CSS 不是动态加载的。如果您希望它真的不引人注目,那么您将需要像在这个答案中一样动态加载 CSS

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Print Portion Example</title>
    <style type="text/css">
      @media print {
        body * {
          display:none;
        }

        body .printable {
          display:block;
        }
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  </head>

  <body>
    <h1>Print Section Example</h1>
    <div id="div1">Div 1</div>
    <div id="div2">Div 2</div>
    <div id="div3">Div 3</div>
    <div id="div4">Div 4</div>
    <div id="div5">Div 5</div>
    <div id="div6">Div 6</div>
    <p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
    <script type="text/javascript">
      function divPrint() {
        // Some logic determines which div should be printed...
        // This example uses div3.
        $("#div3").addClass("printable");
        window.print();
      }
    </script>
  </body>
</html>
谢谢。我的情况是:我将您建议的 css @media print... 放入 site.css。我的页面呈现为 <body> <div class="fixed"> <div class="col1"> <div id="DivForPrint"> </div> </div> </div> </body> 也许在这种情况下,css 不正确?
2021-03-13 05:14:22
如果您需要在页面的一部分依赖于 JS 时打印页面的一部分,这是最好的解决方案,例如标签内的内容
2021-03-23 05:14:22
如果不亲自查看 CSS 和页面源代码,很难说。你能把它发布到像jsbin.com这样的地方吗?
2021-04-07 05:14:22
对于 FF,此解决方案将使用 div3 打印整个页面。对于 IE7,此解决方案将打印整个页面,但将 div3 替换为空白。
2021-04-08 05:14:22
哪个版本的火狐?当我用 IE 测试它时,它是用 IE6 并且它工作正常——只打印“Div 3”。Firefox 3.5.2 演示了相同的行为。Google Chrome 2.0.172.43 也展示了相同的行为。也许我不明白你的要求。
2021-04-09 05:14:22

试试这个 JavaScript 代码:

function printout() {

    var newWindow = window.open();
    newWindow.document.write(document.getElementById("output").innerHTML);
    newWindow.print();
}
这只是将一个未格式化的表格喷到我的新标签上。什么都没打印。
2021-03-27 05:14:22
<div id="invocieContainer">
    <div class="row">
        ...Your html Page content here....
    </div>
</div>

<script src="/Scripts/printThis.js"></script>
<script>
    $(document).on("click", "#btnPrint", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $("#invocieContainer").printThis({
            debug: false, // show the iframe for debugging
            importCSS: true, // import page CSS
            importStyle: true, // import style tags
            printContainer: true, // grab outer container as well as the contents of the selector
            loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
            pageTitle: "", // add title to print page
            removeInline: false, // remove all inline styles from print elements
            printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
            header: null, // prefix to html
            formValues: true // preserve input/form values
        });

    });
</script>

对于 printThis.js 源代码,复制并粘贴到新标签中的 URL 以下 https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js

有了这个分析器,我就不需要发明自行车了,谢谢!
2021-03-23 05:14:22

您可以使用打印样式表,但这会影响所有打印功能。

您可以尝试在外部使用打印样式表,当按下按钮时通过 JavaScript 将其包含在内,然后调用window.print(),然后将其删除。

这会起作用,但需要进行一些修改以允许页面在打印目标后“重置”。(正如您所指出的,这将是一个问题。)例如,就在打印之前,打开一个模态窗口或某种叠加层,指示现在可以进行打印(或立即调用 window.print()),然后当用户单击时确定或关闭,样式表可以自行重置。
2021-03-20 05:14:22
哦,另外,您不一定需要动态加载外部 CSS 文件,您可以预先加载它,但只需在准备打印时调整目标 div 或其他容器上的类。(并在完成后删除类。)
2021-04-12 05:14:22