打印DIV的内容

use*_*est 315 html javascript printing jquery

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

Bil*_*zke 485

对早期版本的轻微更改 - 在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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个快速的解决方案.理想的解决方案是使用单独的CSS进行打印.也许您可以详细说明问题的详细信息(要求). (7认同)
  • 您可以在弹出窗口中引用样式表.在<head>标签之间添加另一行代码:mywindow.document.write('<link rel ="stylesheet"href ="main.css"type ="text/css"/>'); (5认同)
  • @Rahil将其更改为:mywindow.document.close(); mywindow.focus(); mywindow.print(); mywindow.close(); (5认同)
  • 如果无法加载打印预览,有时可能会发生打印预览的内容很大(我注意到它仅适用于Chrome,而相同的页面打印在Firefox中完美,但我不排除它可能会在Firefox或其他浏览器中发生).我找到的最好方法是仅在加载窗口后运行打印(并关闭).所以在:`mywindow.document.write(data);`添加这个:`mywindow.document.write('<script type ="text/javascript"> $(window).load(function(){window.print( ); window.close();}); </ script>');`并删除:`mywindow.print();`和`mywindow.close();` (5认同)
  • ^ add newwindow.focus(); 启用打印跨浏览器. (3认同)
  • 这有时在Chrome中无效.Chrome打印预览显示空白页面.在加载打印预览窗口之前未加载图像. (2认同)

BC.*_*BC. 156

我认为有更好的解决方案.使您的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 应该溢出到多个页面的内容似乎在Chrome中被截断. (14认同)
  • 不幸的是,它不会像预期的那样在IE中运行,请参阅:http://stackoverflow.com/questions/975129/why-does-internet-explorer-8-print-invisible-content (5认同)
  • 当有垂直滚动条时,在 Chrome 中不起作用 (4认同)
  • 你可能需要把z-index:9999999; 如果您有其他元素位于更高. (2认同)

小智 41

尽管@gmcalab已经说过,如果你使用的是jQuery,你可以使用我的printElement插件.

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

用法相当紧张,只需使用jQuery选择器抓取一个元素并打印出来:

$("myDiv").printElement();
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!

  • 8年后,这将产生"a.browser未定义",因为.browser调用已在jquery 1.9中删除 (10认同)

Gar*_*yes 21

使用Jquery,只需使用此功能:

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

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

<button id="print" onclick="printContent('id name of your div');" >Print</button>
Run Code Online (Sandbox Code Playgroud)

编辑:如果您有需要保留的表单数据,克隆将不会复制该表单数据,因此您只需要获取所有表单数据并在还原后将其替换为:

<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>
Run Code Online (Sandbox Code Playgroud)


hus*_*007 16

从这里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>
Run Code Online (Sandbox Code Playgroud)


Rob*_*ert 13

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

我只需添加此行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>
Run Code Online (Sandbox Code Playgroud)

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

这是纯粹的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>
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助别人


Tec*_*hie 11

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;
}
Run Code Online (Sandbox Code Playgroud)

这将打印您想要的div区域并将内容设置回原样.printdivname是要打印的div.


Ste*_*erg 10

如果您想拥有原始文档中的所有样式(包括内联样式),您可以使用此方法。

  1. 复制完整的文档
  2. 将正文替换为您要打印的元素。

执行:

class PrintUtil {
  static printDiv(elementId) {
    let printElement = document.getElementById(elementId);
    var printWindow = window.open('', 'PRINT');
    printWindow.document.write(document.documentElement.innerHTML);
    setTimeout(() => { // Needed for large documents
      printWindow.document.body.style.margin = '0 0';
      printWindow.document.body.innerHTML = printElement.outerHTML;
      printWindow.document.close(); // necessary for IE >= 10
      printWindow.focus(); // necessary for IE >= 10*/
      printWindow.print();
      printWindow.close();
    }, 1000)
  }   
}
Run Code Online (Sandbox Code Playgroud)

  • 我不知道这是最好的解决方案,但它效果很好。谢谢! (3认同)

小智 9

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

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

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

如果要强制为页面显示浏览器的打印对话框,可以使用JQuery在加载时执行此操作:

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

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

  • 是的,它也有效; 很难 - 很好,不可能 - 确切地知道情景是什么. (2认同)

Jas*_*son 7

我创作了一个插件来解决这个问题.我对那里的插件不满意,并着手制作更广泛/可配置的内容.

https://github.com/jasonday/printThis


小智 7

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

  1. CSS媒体查询解决方案假设只有一个div可以打印.
  2. javascript解决方案仅适用于某些浏览器.
  3. 销毁父窗口内容并重新创建它会造成混乱.

我对上述解决方案进行了改进.以下是我测试过的具有以下优点的方法.

  1. 适用于所有浏览器,包括IE,Chrome,Safari和Firefox.
  2. 不破坏并重新加载父窗口.
  3. 可以在页面中打印任意数量的DIV.
  4. 使用html模板以避免容易出错的字符串连接.

要点:

  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>
Run Code Online (Sandbox Code Playgroud)
<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>
  
Run Code Online (Sandbox Code Playgroud)


She*_*ack 7

虽然有点晚了,但我发现这真的非常好!

function printDiv(divID) {
    //Get the HTML of div
    var divElements = document.getElementById(divID).innerHTML;
    //Get the HTML of whole page
    var oldPage = document.body.innerHTML;

    //Reset the page's HTML with div's HTML only
    document.body.innerHTML = 
       "<html><head><title></title></head><body>" + 
              divElements + "</body>";

    //Print Page
    window.print();

    //Restore orignal HTML
    document.body.innerHTML = oldPage;
          
}
Run Code Online (Sandbox Code Playgroud)

  • 使用 Vue 或 React 等框架时,此解决方案可能会遇到一个问题,即当您从打印屏幕返回时,DOM 会失去反应性。 (7认同)

liv*_*ove 6

接受的解决方案无效。Chrome浏览器正在打印空白页,因为它没有及时加载图像。此方法有效:

编辑:我的帖子发表后,似乎接受的解决方案已被修改。为什么要投票?该解决方案也可以正常工作。

    function printDiv(divName) {

        var printContents = document.getElementById(divName).innerHTML;
        w = window.open();

        w.document.write(printContents);
        w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');

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

        return true;
    }
Run Code Online (Sandbox Code Playgroud)