2

Consider the following code example:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML5-Template</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <style type="text/css">
            .print_this{
                display: none;
            }

            @media print {
                .print_this {
                    display: block;
                    width: 1024px;
                    height: 768px;
                }
            }
        </style>  
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                setTimeout(function () {
                    var el = document.getElementById("report");
                    el.focus();
                    el.print();
                }, 1500);
            });
        </script>
    </head>
    <body>
        <div id="Container">
            <object class="print_this" id="report" name="report" type="application/pdf" data="Certificate.pdf"></object>
        </div>
    </body>
</html>

I want to hide the object from the user in the window, but print ONLY the contents of the tag when the print dialog is displayed...is this possible?

NOTE: Code was from elsewhere on the internet, however I have a feeling this is very much, non standards based?

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
  • @HMarioD, thats an example. – Matthew Layton Jan 03 '13 at 17:52
  • @seriesOne, I don't will post an answer because bellow you have a good one, but I want to tell you that you are loading the jquery library just for instantiate a handler, you can do the same with: document.addEventListener("DOMContentLoaded",setTimeout(....), false);. Consider the overhead loading the entire library and parse it. – HMarioD Jan 03 '13 at 18:40
  • @HMarioD...I've always wanted to know how $(document).ready works!!! But every non jQuery way I've found seems overly convoluted! Presumably there is some reason for this, however I like the "DOMContentLoaded" mechanism! As for your answer, the problem I am experiencing with the JavaScript is that print() is not a function of HTMLElement (el). – Matthew Layton Jan 04 '13 at 09:17

1 Answers1

1

You're on the right track. Now you need to define, within the print media block, a screen-only class (.screen_only { display: none; }) to hide the stuff you don't want to show to the printer:

.print_this{
    display: none;
}

@media print {
    .print_this {
        display: block;
        width: 1024px;
        height: 768px;
    }
    .screen_only {
        display: none;
    }
}​

See http://fiddle.jshell.net/jhfrench/UdQSX/2/show/ for a working example. When the page loads in a browser you will see "This doesn't show when printed". Now print the page and you will see "This only shows for the printer".

Jeromy French
  • 11,812
  • 19
  • 76
  • 129