页面打印在JavaScript中

时间:2012-05-08 05:48:24

标签: php javascript css printing

我正在尝试通过java脚本打印页面。代码如下:

<script type="text/javascript">
        function PrintContent(){
            var DocumentContainer = document.getElementById("divtoprint");
            var WindowObject = window.open("", "PrintWindow","width=1200,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
            WindowObject.document.writeln(DocumentContainer.innerHTML);
            WindowObject.document.close();
            WindowObject.focus();
            WindowObject.print();
            WindowObject.close();
        }
    </script>

然后我调用了这个函数<a onclick="PrintContent();" style="cursor:pointer;"><img src="images/printer.png" alt="Print" title="printer"/></a>  还有我要打印的内容,放在<div id="divtoprint"> </div>

但在这种情况下,我得到没有CSS样式的打印页面。那么如何将css集成到我的打印页面呢?请帮帮我。

4 个答案:

答案 0 :(得分:2)

找到您的CSS的link(或其他),并确保其media属性包含print

答案 1 :(得分:2)

尝试:

<script type="text/javascript">
    function PrintContent(){
    var DocumentContainer = document.getElementById("divtoprint");
    var WindowObject = window.open("", "PrintWindow","width=1200,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
    WindowObject.document.write('<html><head><title>Printwindow</title>');
    WindowObject.document.write('<link rel="stylesheet" href="style.css">');
    WindowObject.document.write('</head><body>');
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.write('</body></html>');
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
    }
</script>

答案 2 :(得分:0)

你可以试试这个:

<style type="text/css">
    @media print {
        #divtoprint { /** your css code goes here **/ }
        /** other selector style goes here which style you print **/
    }
</style>

答案 3 :(得分:0)

您是否尝试过更改CSS标记以​​使用所有媒体?

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

或者如果你想更具体

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