【问题标题】:How do I print part of a rendered HTML page in JavaScript?如何在 JavaScript 中打印呈现的 HTML 页面的一部分?
【发布时间】:2010-11-07 12:03:34
【问题描述】:

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。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:
    <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

    【讨论】:

    • 有了这个分析器,我就不需要发明自行车了,谢谢!
    【解决方案2】:

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

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

    【讨论】:

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

    试试这个 JavaScript 代码:

    function printout() {
    
        var newWindow = window.open();
        newWindow.document.write(document.getElementById("output").innerHTML);
        newWindow.print();
    }
    

    【讨论】:

    • 这只是将一个未格式化的表格喷到我的新标签上。没有打印任何内容。
    【解决方案4】:

    我会这样做:

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

    【讨论】:

    • printDivCSS 如果您需要使用样式表格式化您正在打印的内容,就在那里。如果您不希望打印的文本使用样式表进行格式化,那么您就不需要它。
    • 我查了一下情况。 IE7 默认会打印活动帧,所以我必须 focus() 帧。它不会让我 focus() "visibility: hidden" 内容,所以我不得不删除那一点样式格式。框架的宽度、高度和框架边框已经为 0,因此即使没有样式格式,它也会被隐藏。这样,一切正常。哦,最后一点,如果用户尝试 CTRL+F 搜索页面,他们的搜索可能会在框架内找到匹配项,而他们看不到匹配项。您必须在完成打印后将框架空白以修复该框架。
    • @CodingWithStyle 如果您解释您的方法/解决方案而不仅仅是提供代码,这个答案会更有用。
    • 这似乎不再起作用 - 至少在 Chrome 中。打印对话框在 CSS 应用于 iframe 内容之前打开。
    • window.frames["print_frame"].window.focus(); setTimeout(function() { window.frames["print_frame"].window.print(); }, 0);
    【解决方案5】:

    按照与某些建议相同的方式,您至少需要执行以下操作:

    • 通过 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 不是动态加载的。如果您希望它真的不引人注目,那么您需要load the CSS dynamically like in this answer

    <!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>
    

    【讨论】:

    • 对于 FF,此解决方案将使用 div3 打印整个页面。对于 IE7,此解决方案将打印整个页面,但将 div3 替换为空白。
    • Firefox 的哪个版本?当我用 IE 测试它时,它是用 IE6 并且它工作正常——只打印“Div 3”。 Firefox 3.5.2 演示了相同的行为。 Google Chrome 2.0.172.43 也展示了相同的行为。也许我不明白你的要求。
    • 谢谢。我的情况是:我将您的建议 css @media print... 放入 site.css 中。我的页面呈现为
      也许css 对于这种情况不正确?
    • 如果不亲自查看 CSS 和页面源代码,这很难说。你能把它发布到像jsbin.com这样的地方吗?
    • 如果您需要在页面的一部分依赖于 JS 时打印页面的一部分,例如选项卡内的内容,这是最好的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多