Javascript 打印 DIV 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2255291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:29:10  来源:igfitidea点击:

Print the contents of a DIV

javascriptjqueryhtmlprinting

提问by usertest

Whats the best way to print the contents of a DIV?

打印 DIV 内容的最佳方法是什么?

回答by Bill Paetzke

Slight changes over earlier version - tested on CHROME

与早期版本相比略有变化 - 在 CHROME 上测试

function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<h1>' + document.title  + '</h1>');
    mywindow.document.write(document.getElementById(elem).innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

回答by BC.

I think there is a better solution. Make your div to print cover the entire document, but only when it's printed:

我认为有更好的解决方案。使您的 div 打印覆盖整个文档,但仅限于打印时:

@media print {
    .myDivToPrint {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
    }
}

回答by Erik

Although this has been said by @gabe, If you are using jQuery, you can use my printElementplugin.

虽然@gabe已经说过了,但如果您使用的是 jQuery,则可以使用我的printElement插件。

There's a sample here, and more information about the plugin here.

有一个样品在这里,和有关该插件的详细信息在这里

The usage is rather straight forward, just grab an element with a jQuery selector and print it:

用法相当简单,只需使用 jQuery 选择器抓取一个元素并打印它:

$("#myDiv").printElement();

I hope it helps!

我希望它有帮助!

回答by Gary Hayes

Using Jquery, simply use this function:

使用 Jquery,只需使用此函数:

<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
}
</script>

Your print button will look like this:

您的打印按钮将如下所示:

<button id="print" onclick="printContent('id name of your div');" >Print</button>

Edit: If you DO have form data that you need to keep, clone won't copy that, so you'll just need to grab all the form data and replace it after restore as so:

编辑:如果您确实有需要保留的表单数据,则克隆不会复制该数据,因此您只需要获取所有表单数据并在恢复后替换它,如下所示:

<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
var enteredtext = $('#text').val();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
$('#text').html(enteredtext);
}
</script>
<textarea id="text"></textarea>

回答by huston007

From here http://forums.asp.net/t/1261525.aspx

从这里http://forums.asp.net/t/1261525.aspx

<html>

<head>
    <script language="javascript">
        function printdiv(printpage) {
            var headstr = "<html><head><title></title></head><body>";
            var footstr = "</body>";
            var newstr = document.all.item(printpage).innerHTML;
            var oldstr = document.body.innerHTML;
            document.body.innerHTML = headstr + newstr + footstr;
            window.print();
            document.body.innerHTML = oldstr;
            return false;
        }
    </script>
    <title>div print</title>
</head>

<body>
    //HTML Page //Other content you wouldn't like to print
    <input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print ">

    <div id="div_print">

        <h1 style="Color:Red">The Div content which you want to print</h1>

    </div>
    //Other content you wouldn't like to print //Other content you wouldn't like to print
</body>

</html>

回答by Robert

i used Bill Paetzkeanswer to print a div contain images but it didn't work with google chrome

我使用Bill Paetzke答案打印包含图像的 div,但它不适用于谷歌浏览器

i just needed to add this line myWindow.onload=function(){to make it work and here is the full code

我只需要添加这一myWindow.onload=function(){行使其工作,这是完整的代码

<html>
<head>
    <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
    <script type="text/javascript">
        function PrintElem(elem) {
            Popup($(elem).html());
        }

        function Popup(data) {
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload=function(){ // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }
    </script>
</head>
<body>
    <div id="myDiv">
        This will be printed.
        <img src="image.jpg"/>
    </div>
    <div>
        This will not be printed.
    </div>
    <div id="anotherDiv">
        Nor will this.
    </div>
    <input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
</body>
</html>

also if someone just need to print a div with id he doesn't need to load jquery

此外,如果有人只需要打印带有 id 的 div,他就不需要加载 jquery

here is pure javascript code to do this

这是执行此操作的纯 javascript 代码

<html>
<head>
    <script type="text/javascript">
        function PrintDiv(id) {
            var data=document.getElementById(id).innerHTML;
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload=function(){ // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }
    </script>
</head>
<body>
    <div id="myDiv">
        This will be printed.
        <img src="image.jpg"/>
    </div>
    <div>
        This will not be printed.
    </div>
    <div id="anotherDiv">
        Nor will this.
    </div>
    <input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
</body>
</html>

i hope this can help someone

我希望这可以帮助某人

回答by Techie

function printdiv(printdivname) {
    var headstr = "<html><head><title>Booking Details</title></head><body>";
    var footstr = "</body>";
    var newstr = document.getElementById(printdivname).innerHTML;
    var oldstr = document.body.innerHTML;
    document.body.innerHTML = headstr+newstr+footstr;
    window.print();
    document.body.innerHTML = oldstr;
    return false;
}

This will print the divarea you want and set the content back to as it was. printdivnameis the divto be printed.

这将打印div您想要的区域并将内容设置回原样。printdivnamediv要打印的。

回答by dors

I think the solutions proposed so far have the following drawbacks:

我认为目前提出的解决方案有以下缺点:

  1. The CSS media query solutions assume there is only one div to print.
  2. The javascript solutions work only on certain browsers.
  3. Destroying the parent window content and recreating that creates a mess.
  1. CSS 媒体查询解决方案假设只有一个 div 需要打印。
  2. javascript 解决方案仅适用于某些浏览器。
  3. 销毁父窗口内容并重新创建会造成混乱。

I have improved on the solutions above. Here is something that I have tested that works really well with the following benefits.

我已经改进了上述解决方案。这是我测试过的东西,它非常有效,具有以下好处。

  1. Works on all the browsers including IE, Chrome, Safari and firefox.
  2. Doesn't destroy and reload the parent window.
  3. Can print any number of DIV's in a page.
  4. Uses html templates to avoid error prone string concatenation.
  1. 适用于所有浏览器,包括 IE、Chrome、Safari 和 firefox。
  2. 不破坏和重新加载父窗口。
  3. 可以在页面中打印任意数量的 DIV。
  4. 使用 html 模板来避免容易出错的字符串连接。

Key Points to note :

要注意的要点:

  1. Have to have a onload="window.print()" on the newly created window.
  2. Don't call targetwindow.close() or targetwindow.print() from the parent.
  3. Make sure you do targetwindow.document.close() and target.focus()
  4. I'm using jquery but you can do the same technique using plain javascript as well.
  5. You can see this in action here http://math.tools/table/multiplication. You can print each table separately, by clicking on the print button on the box header.
  1. 在新创建的窗口上必须有一个 onload="window.print()"。
  2. 不要从父级调用 targetwindow.close() 或 targetwindow.print() 。
  3. 确保你做了 targetwindow.document.close() 和 target.focus()
  4. 我正在使用 jquery,但您也可以使用普通的 javascript 来执行相同的技术。
  5. 您可以在http://math.tools/table/multiplication 中看到这一点。您可以通过单击框标题上的打印按钮分别打印每个表格。

<script id="print-header" type="text/x-jquery-tmpl">
   <html>
   <header>
       <title>Printing Para {num}</title>
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
       <style>
          body {
            max-width: 300px;
          }
       </style>
   </header>
   <body onload="window.print()">
   <h2>Printing Para {num} </h2>
   <h4>http://math.tools</h4>
</script>
<script id="print-footer" type="text/x-jquery-tmpl">
    </body>
    </html>
</script>
<script>
$('.printthis').click(function() {
   num = $(this).attr("data-id");
   w = window.open();
   w.document.write(
                   $("#print-header").html().replace("{num}",num)  +
                   $("#para-" + num).html() +
                   $("#print-footer").html() 
                   );
   w.document.close();
   w.focus();
   //w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window.
   ///w.close(); Don't do this otherwise chrome won't work
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a>
<a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a>
  
<p class="para" id="para-1">
  Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  

<p class="para" id="para-2">
  Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  

回答by Carl Russmann

Create a separate print stylesheet that hides all other elements except the content you want to print. Flag it using 'media="print"when you load it:

创建一个单独的打印样式表,隐藏除要打印的内容之外的所有其他元素。'media="print"加载时使用标记:

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

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

This allows you to have a completely different stylesheet loaded for printouts.

这允许您为打印输出加载完全不同的样式表。

If you want to force the browser's print dialog to appear for the page, you can do it like this on load using JQuery:

如果要强制为页面显示浏览器的打印对话框,可以在加载时使用 JQuery 这样做:

$(function() { window.print(); });

$(function() { window.print(); });

or triggered off of any other event you want such as a user clicking a button.

或由您想要的任何其他事件触发,例如用户单击按钮。

回答by Jason

I authored a plugin to address this scenario. I was unhappy with the plugins out there, and set out to make something more extensive/configurable.

我编写了一个插件来解决这种情况。我对那里的插件不满意,并着手制作更广泛/可配置的东西。

https://github.com/jasonday/printThis

https://github.com/jasonday/printThis