如何打印网页与iframe和css

How to print webpages with iframe and css

本文关键字:iframe css 网页 何打印 打印      更新时间:2023-09-26

我必须打印对话框的内容。我添加了一个空的iframe,然后我在javascript中添加内容。

这是我的js代码,我添加HTML和CSS作为iframe的子元素

    var layoutCSS = new String('<link href="css/ReportPageOne.css" rel="stylesheet" type="text/css">');
    var pageOneCSS = new String('<link href="css/ReportLayout.css" rel="stylesheet" type="text/css">');
    var pageTwoCSS = new String('<link href="css/ReportPageTwo.css" rel="stylesheet" type="text/css">');
    var materialityCSS = new String('<link href="css/MaterialityMatrix.css" rel="stylesheet" type="text/css">');
    window.frames.print_frame.document.head.innerHTML = layoutCSS + pageOneCSS + pageTwoCSS + materialityCSS;
    window.frames.print_frame.document.body.innerHTML = $('#__dialog1-cont').html();
    window.frames.print_frame.window.focus();
    window.frames.print_frame.window.print();

正确打开打印对话框,但CSS应用得不太好。

在打印页面的选项,我在"背景图形"检查,我使用谷歌浏览器。

在样式加载之前调用frame.print()

"一旦样式表及其所有导入的内容加载和解析完成,在样式开始应用于内容之前,load事件就会触发。"

试试这个:

head.lastChild.addEventListener("load", function (event) {
    // In IE, you have to focus() the Iframe prior to printing
    // or else the top-level page will print instead
    frame.focus();
    frame.print();
}, 0);

引用

  • https://github.com/abbotto/teleprint/blob/master/src/components/print.js
  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link Stylesheet_load_events