【问题标题】:Link to print a URL链接以打印 URL
【发布时间】:2013-10-07 06:48:24
【问题描述】:

我想打开一个页面,但不是查看它,而是要求用户打印。

这与Content Disposition HTTP 标头的功能非常相似。
当设置为attachment 时,它会询问用户将文件保存在哪里(而不是在浏览器中显示)。

我有权限为用户打开页面,所以我可以use javascript:

var doc = open(url); //open the link for them instead of using an anchor href
doc.print(); //ask them to print it, this is a blocking call until the user is done
doc.close(); //immediately close the window so the user isn't interrupted

但我真的希望有一些我可以使用的服务器端标志,有这样的东西吗?

打开的页面不一定是 HTML 文档,因此在其中使用window.print();window.close(); 并非在所有情况下都有效。

【问题讨论】:

  • HTTP 不是 HTML,但您的回答似乎表明 HTTP 也没有好东西
  • 另外,我认为这个问题是指打印当前所在的页面。未链接到 将出现打印对话框的文档。

标签: javascript html http printing http-headers


【解决方案1】:

我决定用 Javascript 发布答案,因为它实际上并不简单:(
我在问题中写的内容无法跨浏览器工作(实际上是 Firefox,这次不是 IE!)

问题在于,在 Firefox 中,print() 实际上是非阻塞的,所以在我上面的示例中,新的open()'d 窗口会在 Firefox 打印之前关闭!

因此,您可以让窗口保持打开状态,也可以尝试使用隐藏框架;

function printUrl(url) {
    var frame = document.createElement('iframe');
    frame.setAttribute('src', url);

    //must be in the DOM to work in Firefox/IE
    document.body.appendChild(frame);

    //since it's in the DOM we need to hide it (lest we ruin our page layout)
    //can't use 'display:none' or 'visibility:hidden' because you can't get focus (needed for IE)
    //'z-index:-1' & 'opacity:0' wont help if there is no background in the elements above it and someone clicks through to it
    frame.style.position = 'absolute';
    frame.style.left = '-9999px';

    //when it is loaded, print it
    function printFrame() {
        //have to get focus in IE
        frame.contentWindow.focus();

        //print!
        frame.contentWindow.print();

        /* cant remove the element because print() is non-blocking in FF
         * (I.e. it would remove the frame before it was printed!)
        //cleanup
        //document.body.removeChild(frame);*/
    };

    //if it was cached, it may already be done (onload wont fire, IE8)
    if (frame.contentWindow && frame.contentDocument.readyState == 'complete')
        printFrame();
    else {
        if (frame.addEventListener)
            //W3C
            frame.addEventListener('load', printFrame, false);
        else
            //IE<9
            frame.attachEvent('onload', printFrame);
    }
}

经测试可在 FF、Chrome 和 IE>7 中运行
请注意,就像使用简单的open()(如果有效)一样,这将无法跨站点工作。您无法在弹出窗口或框架中访问不同域中页面的 window 方法。

【讨论】:

    【解决方案2】:

    您混淆了服务器端语言和客户端语言的作用。

    PHP 或 ASP 等服务器端语言在服务器上执行操作,例如在网上商店计算价格。

    Content-Disposition: attachment 标头在这方面有点奇怪,因为它控制 客户端 而不是服务器。

    一种客户端语言(在本例中为 JavaScript)执行用户浏览器上发生的事情。

    打印是一种客户端功能。您需要使用 JavaScript。

    【讨论】:

    • 完全正确。我正在寻找更多这些奇怪的东西,如果它们存在的话
    • @Hashbrown 没有要打印的内容。
    猜你喜欢
    • 1970-01-01
    • 2011-09-09
    • 2015-03-07
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2011-03-29
    • 2019-01-03
    • 2019-03-02
    相关资源
    最近更新 更多