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

时间:2009-07-02 00:25:30

标签: javascript jquery

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 个答案:

答案 0 :(得分:111)

我会这样做:

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

答案 1 :(得分:27)

与您至少需要做以下建议的一些建议相同:

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

示例CSS可以像这样简单:

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

  body .printable {
    display:block;
  }
}

然后,您的JavaScript只需要将“可打印”类应用于目标div,并且在打印发生时,它将是唯一可见的(只要没有其他冲突的CSS规则 - 单独的练习)。 / 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>

您可能希望在打印完成后从目标中删除该类,和/或在打印完成后删除动态添加的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>

答案 2 :(得分:11)

试试这个JavaScript代码:

function printout() {

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

答案 3 :(得分:6)

<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下方的URL        https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js

答案 4 :(得分:3)

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

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