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


68

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

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

是否有jQuery兼容的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。

Answers:


117

我会这样处理:

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

2
如果您需要使用样式表格式化要打印的内容,就可以使用printDivCSS。如果您不希望使用样式表设置打印文本的格式,则不需要它。
编码风格

4
我检查了情况。IE7默认会打印活动框架,因此我必须对框架进行focus()处理。它不会让我focus()“可见性:隐藏”内容,因此我不得不删除一点样式格式。框架的宽度,高度和框架边界均为0,因此即使不设置样式格式也不会隐藏。这样,一切正常。哦,最后一点,如果用户尝试CTRL + F搜索页面,则他们的搜索可能会在框架内找到匹配项,但看不到匹配项。在完成打印后,您必须将框架空白以修复该框架。
编码样式

9
@CodingWithStyle如果您解释了您的方法/解决方案,而不仅仅是提供代码,那么此答案将更加有用。
肖恩·宾恩

2
这似乎不再起作用-至少在Chrome中。在CSS应用于iframe内容之前,将打开“打印”对话框。
萝卜

4
window.frames["print_frame"].window.focus(); setTimeout(function() { window.frames["print_frame"].window.print(); }, 0);
莎阿·阿巴兹汗

29

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

  • 通过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>

对于FF,此解决方案将使用div3打印整个页面。对于IE7,此解决方案将打印整个页面,但将div3替换为空白。
肯特郡,

哪个版本的Firefox?当我使用IE6进行测试时,它与IE6兼容,并且可以正常工作-仅打印“ Div 3”。Firefox 3.5.2演示了相同的行为。Google Chrome 2.0.172.43也演示了相同的行为。也许我不明白您的要求。
Zack The Human

谢谢。我的情况是:我将您建议的CSS @media print ...放入site.css。我的页面显示为<body> <div class =“ fixed”> <div class =“ col1”> <div id =“ DivForPrint”> </ div> </ div> </ div> </ body> CSS在这种情况下是不正确的?
肯特郡

我自己看不见CSS和页面源就很难说。您可以将其发布到jsbin.com之类的地方吗?
Zack The Human

如果您需要在页面的该部分取决于JS时打印页面的一部分,例如,选项卡中的内容
网站的时间为

11

尝试以下JavaScript代码:

function printout() {

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

1
这就为我带来了一个未格式化的表格到一个新选项卡上。什么都没打印。
SteveCav 2015年

7
<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源代码,请在新选项卡https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js中的URL下复制并定位


有了这个分析器,我不需要发明自行车,谢谢!
Akmal

4

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

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


这将起作用,但需要进行一些修改以允许在打印目标后页面“重置”。(如您所指出的,这将是一个问题。)例如,在打印之前,打开一个模式窗口或某种类型的叠加层,指示现在可以进行打印(或立即调用window.print()),然后在用户单击时单击确定或关闭,样式表可以自行重置。
Funka

哦,而且,您不一定需要动态加载外部CSS文件,您可以预先加载它,而在准备打印时只需调整目标div或其他容器上的类即可。(并在完成后删除类。)
Funka
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.