【问题标题】:Printing a html table with JS on window load在窗口加载时使用 JS 打印 html 表格
【发布时间】:2016-08-25 06:08:20
【问题描述】:

我需要将表格元素的内容打印到 POS 收据打印机,我这样做是这样的:

    <?php
    private function message(){
    return '<!DOCTYPE html><html moznomarginboxes mozdisallowselectionprint><body style="padding:30px;">'
.'<table id="print-area" style="height: 501px; border:1px solid red;padding:1em;margin:0 0 1em" width="364" ><tr><td>example</td></tr></table></table>'
.'<p>&nbsp;</p></body> </html>'}
    ?>

我正在做的是将 PHP 函数的返回值传递给一个新函数。请忽略 php 函数的结构和逻辑,这些只是我如何执行此操作的示例,我知道这可能不是最好的方法,但我真正需要帮助的是 JavaScript 部分。为什么不打印并关闭新窗口?

我只需要打印表格并使其适合 POS 收据页面,而不需要打印整个空白区域......我已经尝试过使用此版本的 PrintReceipt 功能,但它会打印很多空白区域收据。

    public function PrintReceipt($content) {

    echo"<!DOCTYPE html><script type='application/javascript'>
                    window.onload=function(){          
                        var myWindow = window.open('', 'MsgWindow', 'width=200,height=100');
                        myWindow.document.write('" . $content . "');
                        myWindow.print();
                        myWindow.close();              
                    }
    </script>";
}

【问题讨论】:

  • 我测试了你的 js 函数和 OP 中提供的一段代码......它在我的环境中按预期工作(在 OP 中使用的第二个版本)......可能问题出在其他地方。您必须为此发布更多代码
  • @NishanthMatha 我在我这边运行它时收到此错误:TypeError: myWindow.frames.print_frame is undefined step4:5:29 它只是打开新的窗口,但不将其发送到打印机。
  • 我测试了第二版代码
  • 是的,第二版代码(又名旧版)的问题是,当我尝试打印时,它只会在收据上打印一个大空白区域,我希望桌子适合收据纸的尺寸...
  • 你似乎在使用框架..你能发布你的print_frame代码

标签: javascript php html css printing


【解决方案1】:

如果您不使用frames,则声明以下几行是没有意义的:

myWindow.frames['print_frame'].document.title = document.title; 
myWindow.document.getElementById('print-area').contentWindow.print();   

这意味着您在 OP 中的第二次尝试是正确的。如果有空白空间,那绝对是css 问题。如果您希望表格占据页面宽度的100%,请执行以下操作:

return '&lt;table id="print-area" style="height: 100%; border:1px solid red;padding:1em;margin:0 0 1em" width="100%" &gt;&lt;tr&gt;&lt;td&gt;example&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/table&gt;';

而不是

return '<!DOCTYPE html><html moznomarginboxes mozdisallowselectionprint><body style="padding:30px;">' .'<table id="print-area" style="height: 501px; border:1px solid red;padding:1em;margin:0 0 1em" width="364" ><tr><td>example</td></tr></table></table>' .'<p>&nbsp;</p></body> </html>'}

【讨论】:

  • 我测试了你的 js 函数和 OP 中提供的代码......它在我的环境中按预期工作......可能问题出在其他地方。您必须为此发布更多代码
  • 嗨,这是正确的答案!我可以推断它可以在 POS 打印机上工作,就像在普通打印机上工作一样。感谢您的帮助@Nishanth
猜你喜欢
  • 1970-01-01
  • 2020-07-11
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2018-06-07
相关资源
最近更新 更多