使用当前 css 打印 html 页面

Print html page with current css

本文关键字:打印 html 页面 css      更新时间:2023-09-26

我想在html页面中打印一些已识别的div,并带有当前的css。

当我尝试通过"ctrl + p"打印页面时,包含css。但是,如果我通过按钮执行此操作,则打印屏幕不包括css。

有什么建议吗?谢谢。。

我的代码示例;

<head>
        <link rel="stylesheet" href="bootstrap.css" type="text/css" media="screen">
        <link rel="stylesheet" href="bootstrap.css" type="text/css" media="print">
        <link rel="stylesheet" href="cssFile.css" type="text/css" media="screen">
        <link rel="stylesheet" href="cssFile.css" type="text/css" media="print">
</head>

我使用相同的css文件两个链接,其中包括屏幕媒体属性和打印媒体属性。这种方法合适吗?我应该在 js 函数中编写一个新的 css 来打印吗?

我还尝试在js函数中添加css文件。

<script>
    $( document ).ready(function() {
        $("#button").click(function(){
            var divId = "div";
            window.frames["print_frame"].document.head.innerHTML='<link rel="stylesheet" href="css/bootstrap.css" type="text/css" media="print"> <link rel="stylesheet" href="css/cssFile.css" type="text/css" media="print">';
            window.frames["print_frame_ssd"].document.body.innerHTML=document.getElementById(divId).innerHTML;
            window.frames["print_frame"].window.focus();
            window.frames["print_frame"].window.print();
        }); 
    });
</script>

.

<div id="div">
   content..
   <iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
</div>

为了确保样式表正常,您可以查看这篇文章

https://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/

和你可以试试这个的功能

var prtContent = document.getElementById("your div id");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

试一试,让我知道它对你有用:)