简体   繁体   中英

How to print selected div instead complete page

I have two divs: div1 and div2 .

Maintaining the original css styles applied to the div2 element being printed.

I don't want to print content inside div1 but only the inside of div2 .

How to print?

Try this

<style type="text/css">
@media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>

Using my following solution you can print the specific div content from your web page if you don't want to print your full page.

<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('', 'new 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.print();
        mywindow.close();

        return true;
    }

</script>
</head>
<body>

<div id="yourdiv">
    Div you want to print. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante. 
</div>

<div>
    This will not be printed.
</div>

<div id="anotherdiv">
    Nor will this.
</div>

<input type="button" value="Print" onclick="PrintElem('#yourdiv')" />

</body>
</html>

Live Demo

<script type="text/javascript">
    function printDiv() {    
    var printContents = document.getElementById('Your printable div').innerHTML;
    var originalContents = document.body.innerHTML;
     document.body.innerHTML = printContents;
     window.print();
     document.body.innerHTML = originalContents;
    }
</script>

You can only print a whole page, not part ofg a page. So, there is two options, you can either copy the content of one element into a new page and print that, or prevent the other element from being printed.

You can use a media css to hide one element from printing. Example:

@media print {

   .div1 { display: none; }

}

Have a look at the jqPrint plugin for jQuery: http://plugins.jquery.com/project/jqPrint

You can also do it using jQuery:

<script>
function printArea(){
    $('body').css('visibility', 'hidden');
    $('.div2').css('visibility', 'visible');
    window.print();
}
</script>

I faced lots of issues while printing a div (part of HTML) using window.print(). Used below method and it works seamlessly in edge, chrome and Mozilla. How this below function helps mitigate the issue that I face is by the use of iframe. When using window.print() without the below code it was printing most of the page's design and all, which we didn't want. There are many CSS based options too but eventually this one below worked for me. From the below code "frameDoc.document.write........ frameDoc.document.close();" is controlling the format that can be seen in print preview as well.

function printDiv(id) {
      var contents = document.getElementById(id).innerHTML;
        var frame1 = document.createElement('iframe');
        frame1.name = "frame1";
        frame1.style.position = "absolute";
        frame1.style.top = "-1000000px";
        document.body.appendChild(frame1);
        var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
        frameDoc.document.open();
        frameDoc.document.write("<html><head>\n\n                " +
            "<style type=\"text/css\" media=\"print\">\n                       " +
            "@@page\n                    {\n                        " +
            "size:  auto;   /* auto is the initial value */\n                        " +
            "margin: 10mm;  /* this affects the margin in the printer settings */\n    " +
            "                }\n\n                    html\n                    {\n    " +
            "                    background-color: #FFFFFF;\n         " +
            "           }\n\n                    body\n                " +
            "    {   font-family:\"Times New Roman\", Times, serif;\n             " +
            "           border: none ;\n                  " +
            "      margin: 0; /* margin you want for the content */\n                " +
            "    }\n                   .table {\n                    width: 100%;\n      " +
            "              max-width: 100%;\n                    margin-bottom: 20px;\n        " +
            "            border-collapse: collapse;\n                 " +
            "   background-color: transparent;\n                    display: table;\n        " +
            "        }\n                .table-bordered {\n                 " +
            "   border: 1px solid #ccc;\n                }\n                tr {\n            " +
            "        display: table-row;\n                    vertical-align: inherit;\n              " +
            "      border-color: inherit;\n                    padding:15px;\n                }\n      " +
            "          .table-bordered tr td {border: 1px solid #ccc!important; padding:15px!important;}\n   " +
            "             </style><title></title></head><body>".concat(contents, "</body>"));
        frameDoc.document.close();
        setTimeout(function () {
            window.frames["frame1"].focus();
            window.frames["frame1"].print();
            document.body.removeChild(frame1);
        }, 500);
        return false;
}

Call this like

<a href="#" onclick="javascript:printDiv('divwithcontenttoprint')"> Print </a>

Easy way

@media print {
    body > div { display:none; }
    body .div { display:block; }
}
.class-toggle { display: inline-block; }
#div1, #div2 { display: none; }
function classToggle() {
  $('#div1').addClass('class-toggle');
}

classToggle();

Then you can play with event handler to handle how and when you want to print the output.

Use PrintArea jQuery Plugin to print specific div content. I have found the easy integration guide from here - How to print a specific area of the web page using jQuery

You need only the following code to use PrintArea jQuery Plugin.

<script>
$(document).ready(function(){
    $("#printButton").click(function(){
        var mode = 'iframe';
        var close = mode == "popup";
        var options = { mode : mode, popClose : close};
        $("div.printableArea").printArea( options );
    });
});
</script>
<script type="text/javascript">
    function printDiv() {    
    var printContents = document.getElementById('Your printable div').innerHTML;
    var originalContents = document.body.innerHTML;
     document.body.innerHTML = printContents;
     window.print();
     document.body.innerHTML = originalContents;
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM