【问题标题】:printing contents in a new tab prints a blank page在新选项卡中打印内容打印空白页
【发布时间】:2014-09-04 12:24:15
【问题描述】:

我正在尝试将 div 的内容打印到新选项卡,但是,它仅第一次打印空白页。当我手动打印页面时,它工作正常。我正在加载包含在 div 中的 2 个表。

HTML 结构:

<div class="receipt_bg" id="print_receipt">
  <div id="div1">
    table1
  </div>
  <div id="div2">
    table2
  </div>
</div>
<button type="button" id="print_btn">Print</button>

Javascript:

$('#print_btn').click(printClick);

function printClick(receipt_bg) {
  var DocumentContainer = $('.receipt_bg').html();
  var WindowObject = window.open("PrintWindow","_blank");
  WindowObject.document.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">'+ '<html><head><title>test print receipt</title>    <link href="../css/style.defaultprint.css" rel="stylesheet" type="text/css" /></head><body>' +     DocumentContainer + '</body></html>')
  setTimeout(WindowObject.print(), 5);
  WindowObject.close();
}

我什至尝试使用 WindowObject.onload = WindowObject.print(); 代替 setTimeout(WindowObject.print(), 5); 它似乎仍然不起作用。我看到了一个类似的帖子,但它的解决方案对我不起作用。

【问题讨论】:

    标签: javascript html printing new-window


    【解决方案1】:

    检查此网址。 它包含一些从页面打印内容的示例。它有你需要的一切。

    我曾使用 jQuery Print Element 1.2 进行打印,在此,如果您有大量内容要打印,那么您需要将超时时间从 50 增加到 500,否则当您遇到问题时它会显示空白页,但对我来说它只发生在 Chrome 浏览器中,除此之外我还没有遇到这个问题。 检查 printElement js。下面的 url 包含带有演示和源代码的好例子。

    检查这个:jQuery Print Page Options

    这里是代码,对你有帮助。

    function printClick(receipt_bg) {
        var DocumentContainer = $('.receipt_bg').html();
        var WindowObject = window.open("", "printElementWindow", "width=650,height=440,scrollbars=yes");
        WindowObject.document.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">'+ '<html><head><title>test print receipt</title>    <link href="../css/style.defaultprint.css" rel="stylesheet" type="text/css" /></head><body>' +     DocumentContainer + '</body><script type="text/javascript">setTimeout(printPage(),1000);  function printPage(){focus();print();}<\/script></html>')
        WindowObject.close();
     }
    

    这对你有用,我在你的窗口代码中添加了一个 javascript 函数,它将在超时后执行。试试看,让我知道,它是否适合你。您可以根据您的内容延长或规定超时。

    【讨论】:

    • 如果不为此使用任何插件,我是否无法做到这一点?我尝试将超时时间从 50 增加到 500 甚至 1000,但仍然没有运气。
    • @ekta : 你得到你的答案还是我进一步帮助你?
    • 我可以通过使用一些插件来解决这个问题,但我不想这样做。你能在不使用插件的情况下帮助我吗?我尝试在 setTimeout() 中增加时间。
    • @ekta 检查更新的答案,它有你的解决方案。试试我提到的例子。
    猜你喜欢
    • 2013-01-27
    • 2012-03-20
    • 2015-05-18
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2016-12-08
    相关资源
    最近更新 更多