Css styles not getting applied in the page which I am trying to print using javascript

I am trying to print the contents of a specific div with a class called “container” which has a number of divs having their individual classes. The problem I am facing is that when I click the print button the print preview shows the contents to be printed in completely plain format, no css styles applied. But I want the contents to be exactly the way it is being displayed in the browser. I have tried a number of ways and solutions from here but nothing seems to work. Please suggest me some way to do it. I was trying to do it with javascript. The javascript code given below is cpied as I said I was trying out all the possible ways.

javascript

$(function () {
    $("#btnPrint").click(function () {
        var contents = $("#content").html();
        var frame1 = $('<iframe />');
        frame1[0].name = "frame1";
        frame1.css({ "position": "absolute", "top": "-1000000px" });
        $("body").append(frame1);
        var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
        frameDoc.document.open();
        //Create a new HTML document.
        frameDoc.document.write('<html><head><title>DIV Contents</title>');
        frameDoc.document.write('</head><body>');
        //Append the external CSS file.
        frameDoc.document.write('<link href="C:UsersIntelEnvstestprojectstaticdoc.css" rel="stylesheet" type="text/css" />');
        //Append the DIV contents.
        frameDoc.document.write(contents);
        frameDoc.document.write('</body></html>');
        frameDoc.document.close();
        setTimeout(function () {
            window.frames["frame1"].focus();
            window.frames["frame1"].print();
            frame1.remove();
        }, 500);
    });
});

The below images are the way it is being displayed in the browser and the way it is displayed in the preview

This is how i want it to get it printed

this is how  want to get it printed and this is how it getting printed]2

html file

<link rel="stylesheet" href="{% static 'doc.css' %}" media="all"/>

<div class="main-container">
  <div class="container" id="content"> 

     

        {% if object.reportable %}
        <div class="report">
            <p>Reportable </p>
        </div>
        {% endif %}

        {% if object.non_reportable %}
        <div class="report">
            <p>Non-Reportable </p>
        </div>
        {% endif %}

        {% if object.over_ruled %}
        <div class="over">
            <p>Over Ruled </p>
        </div>
        {% endif %}

        {% if object.equivalent_citations %}
        <div class="cit">
            <p><b>Equivalent Citations:</b> {{object.equivalent_citations}}</p>
        </div>
        {% endif %}

        <div class="crt">
            <p><b>In The {{object.court_type}}</b></p>
        </div>

        <div class="appeal">
            <p><b>{{object.apelLate_type}}</b></p>
        </div>

        <div class="jdge">
            <p> <b>Before:</b> {{object.judge_name}}</p>
        </div>

        <div class="party-name">
            <p> <b> {{object.party_name}} </b> </p>
        </div>

       
        <div class="case-no">
            <p><b>Case No.:</b> {{object.case_no}} </p>
        </div>
        ...
        


  <div class="container-2">
    <input type="button" id="btnPrint" value="Print" />
    </div>
</div>

Answer

Consider the following example: https://jsfiddle.net/Twisty/aspehr0m/7/

JavaScript

$(function() {
  $("#btnPrint").click(function() {
    var contents = $("#content").html();
    var frame1 = $('<iframe>', {
        id: "frame1",
        name: "frame1"
      })
      .css({
        "position": "absolute",
        "top": "-1000000px"
      })
      .appendTo($("body"));
    var myHTML = $("<html>");
    $("<head>").appendTo(myHTML);
    $("<title>").html("DIV Contents").appendTo($("head", myHTML));
    $("<body>").appendTo(myHTML);
    $("body > link").clone().appendTo($("body", myHTML));
    $("body", myHTML).append(contents);
    console.log("Content", myHTML.prop("outerHTML"));
    var frameDoc = window.frames.frame1;
    frameDoc.document.open();
    //Create a new HTML document.
    frameDoc.document.write(myHTML.prop("outerHTML"));
    frameDoc.document.close();
    setTimeout(function() {
      frame1.focus();
      window.frames.frame1.print();
      frame1.remove();
    }, 500);
  });
});

Here you can use .clone() to make a copy of the existing Stylesheet Link. this will ensure it uses the same as the primary page.

It is consider a better practice not to mix JavaScript and jQuery, to stick to one or the other. In this case, it’s a bit easier to to manage the iFrame element with native JavaScript.

Update

You might consider making a new Function: https://jsfiddle.net/Twisty/aspehr0m/38/

JavaScript

$(function() {
  $.fn.printContent = function() {
    var target = $(this);
    var title;
    if (target.attr("title") != undefined) {
      title = target.attr("title");
    } else {
      title = "Element Contents"
    }
    var uid = Date.now();
    var printFrame = $("<iframe>", {
      id: "printFrame_" + uid,
      name: "printFrame_" + uid
    }).css({
      position: "absolute",
      top: "-1000000px"
    }).appendTo($("body"));
    var frameHTML = $("<html>");
    $("<head>").appendTo(frameHTML);
    $("<title>").html(title).appendTo($("head", frameHTML));
    $("<body>").appendTo(frameHTML);
    if ($("body > link").length == 1) {
      $("body > link").clone().appendTo($("body", frameHTML));
    }
    $("body", frameHTML).append(target.html());
    var winFrame = window.frames['printFrame_' + uid];
    winFrame.document.open();
    winFrame.document.write(frameHTML.prop("outerHTML"));
    winFrame.document.close();
    setTimeout(function() {
      printFrame.focus();
      winFrame.print();
      printFrame.remove();
    }, 100);
  };

  $("#btnPrint").click(function() {
    $("#content").printContent();
  });
});