2013-10-01 61 views
0

我想打开一个页面,但不要查看它,它会要求用户打印。打印URL的链接

这非常类似于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();在所有情况下都不起作用。

+0

可能的重复[我们可以使打印按钮没有JavaScript?](http://stackoverflow.com/questions/1720013/can-we-make-print-button-without-javascript) –

+0

HTTP不是HTML,但是看起来好像你的回答显示HTTP没有好的东西, – Hashbrown

+0

也是,我想这个问题是指打印它当前所在的页面。不链接到其中将出现打印对话的文档*。 – Hashbrown

回答

0

您已经混淆了服务器端和客户端语言的功能。

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

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

客户端语言(本例中为JavaScript)执行用户浏览器上发生的操作。

打印是客户端功能。你需要使用JavaScript。

+0

正好。我正在钓更多的这些古怪,如果他们存在 – Hashbrown

+0

@Hashbrown没有什么可打印的。 –

0

我决定张贴在Javascript的答案,因为它实际上不是小事:(
我在这个问题写过将无法正常工作跨浏览器(它实际上是火狐,IE不是这一次!)

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

所以,你可以离开窗口打开,或者你可以尝试使用隐藏帧;

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不同域上的页面方法,无论是在弹出窗口还是在框架中。