Javascript print div content in asp.net mvc

2014-07-10 javascript jquery asp.net asp.net-mvc printing

Html:

 <div id="printDiv" class="table-responsive">

        @Html.Raw(Model.Content)

    </div>

<button type="button" onclick="Print()">Print</button>

Javascript:

function Print() {
        alert("working");
        $("#printDiv").printThis();
    }

When i click to Print button , i want to print div content.However if i click to button, i get below exception for javascript code.

Uncaught TypeError: undefined is not a function 

I do not have any idea Where i miss exactly ?

Any help will be appreciated. Thanks.

Answers

Try Adding printThis.js.

Download the js file from below Link

https://github.com/jasonday/printThis

Sample code

<!DOCTYPE html>
  <html>
  <head>
<script src="assets/js/jquery-1.9.1.js"></script>
<script src="assets/js/printThis.js"></script>
<style>
        .drag 
    {
      width: 100px;
      height: 100px;
      background-color: #000;
    }

    #box
    {
      width: 500px;
      height: 400px;
      background-color:red;
    }
</style>
</head>

<body>

  <div id="box">
        <div id="drag">aaaaaaaaaaaaaaaaa</div>
    </div>

    <script>
        $("#drag").printThis()
    </script>


</body>

</html>

1- paste this javascript code in your asp.net webform or ASP.NET MVC view

<script type="text/javascript">

    function PrintElem(elem)
    {
        Popup($(elem).html());
    }

    function Popup(data)
    {
        var mywindow = window.open('', 'divprint', 'height=400,width=600');
        mywindow.document.write('<html><head><title></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.focus(); // necessary for IE >= 10

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

        return true;
    }

</script>

2- create print button:

<table class="table table-bordered">
    <tr>
     <td style="text-align:center">
     <input type="submit" value="Print " onclick="PrintElem('#divprint')" 
        class="btn btn-danger" />
        </td>
    </tr>
</table>

3- name your div id which you need to print ,

<div id="divprint"> 
// your code to print 
</div> 

Related