javascript - 谷歌浏览器在打印预览中不显示图像

标签 javascript google-chrome printing popup

我有一些代码来创建一个弹出窗口,编写一些 html 并打印。谷歌浏览器在打印预览中不显示图像,但其他浏览器工作正常。在我的案例中,文件 Logo_big.png 丢失了。我怎样才能让它在 Chrome 中也能正常工作?

我的代码:

var newWindow = window.open('', '', 'width=100, height=100'),
        document = newWindow.document.open(),
        pageContent =
            '<!DOCTYPE html>' +
            '<html>' +
            '<head>' +
            '<meta charset="utf-8" />' +
            '<title>Inventory</title>' +
            '<style type="text/css">body {-webkit-print-color-adjust: exact; font-family: Arial; }</style>' +
            '</head>' +
            '<body><div><div style="width:33.33%; float:left;"><img src="img/Logo_big.png"/></body></html>';
        document.write(pageContent);
        document.close();
        newWindow.moveTo(0, 0);
        newWindow.resizeTo(screen.width, screen.height);
        newWindow.print();
        newWindow.close();

最佳答案

这里的问题是 javascript 没有给 DOM 足够的(任何)时间来加载/渲染图像,一旦它设置了 src

您需要留出时间让浏览器加载/渲染(从缓存或其他方式)图像,您可以通过设置 setTimeout 来延迟从正在设置的内容打印。

这个具体问题的一个例子是:

var newWindow = window.open('', '', 'width=100, height=100'),
document = newWindow.document.open(),
pageContent =
    '<!DOCTYPE html>' +
    '<html>' +
    '<head>' +
    '<meta charset="utf-8" />' +
    '<title>Inventory</title>' +
    '<style type="text/css">body {-webkit-print-color-adjust: exact; font-family: Arial; }</style>' +
    '</head>' +
    '<body><div><div style="width:33.33%; float:left;"><img src="img/Logo_big.png"/></body></html>';
document.write(pageContent);
document.close();
newWindow.moveTo(0, 0);
newWindow.resizeTo(screen.width, screen.height);
setTimeout(function() {
    newWindow.print();
    newWindow.close();
}, 250);

setTimeout 设置得越低,浏览器加载图像所需的时间就越少,因此您需要对此进行调整,并在适用的情况下考虑较慢的互联网连接/浏览器。

关于javascript - 谷歌浏览器在打印预览中不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31725373/

相关文章:

javascript - ng-init 与 Controller 中的函数,使用 $parent 时哪个是更好的做法?

javascript - 使用removeChild() jquery一次删除两个项目

Java打印数组列表编号

apache-flex - 如何使用 mx PrintDataGrid 打印 flex spark datagrid?或者有没有其他方法可以在不使用 mx PrintDataGrid 的情况下实现这一目标?

javascript - 有没有办法用 Javascript 搜索表格行内的文本?

javascript - Twitter Bootstrap : Hide other popovers when one is open

jquery - 为什么我的 jQuery 动画在基于 webkit 的浏览器中不稳定?

java - Chromium 与 SeleneseTestCase

javascript - 检测浏览器当前 "media"模式

c - 输入和输出数组不匹配