在新窗口中打开PDF,打印PDF并关闭窗口。如何在javascript中执行此操作 [英] Open PDF in a new window, print that PDF and Close the window. How to do this in javascript

查看:194
本文介绍了在新窗口中打开PDF,打印PDF并关闭窗口。如何在javascript中执行此操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在新窗口中打开PDF,打印PDF并关闭窗口。如何在javascript中执行此操作。
这3个步骤应该只需点击一下。

Open PDF in a new window, print that PDF and Close the window. How to do this in javascript. This 3 steps should be done in One click.

推荐答案

有两种情况:通过get加载pdf要求或通过邮寄(表格)要求;我的场景通过打开打印对话框来解决它们,当关闭打印对话框时,关闭窗口。

There are two scenarios: loading the pdf through a get request or through a post (form) request; my scenario addresses them by bringing up the print dialog and when the print dialog is closed, closing the window.

对于get请求,这应该足够了:

For the get request, this should be sufficient:

function testprint(){
    var w = window.open(yourURL)
    w.focus()
    w.print()
    // Don't try to close it until you've give the window time to register the print dialog request
    setTimeout(function(){
        w.close() 
    }, 1000)
}

帖子有点更复杂。在争论这个问题一段时间之后,这就是我想出来的 - 它使用隐藏的iframe;我无法使用额外的窗口工作。结果就是你可以隐藏iframe,这样用户甚至不需要看到其他窗口。 (注意,您可以转换get解决方案以使用iframe并避免使用额外的窗口。)它假设您使用jQuery构建表单,并且帖子的结果将是您想要的PDF。

The post is a little more complicated. After battling this issue for a while, this is what I came up with - it uses a hidden iframe; I couldn't get it to work with an extra window. The upshot of that is though you can hide the iframe so the user doesn't even need to see the other window. (Note, you could convert the get solution to use the iframe as well and avoid the extra window all together.) It assumes you've build a form with jQuery, and the result of the post will be the PDF you want.

jQuery(document.body).append(form);
if (doPrint) {
    jQuery(document.body).append("<iframe style='display:none' id='doPrintId' name='doPrint'>");
    form.submit(function () {
        form.attr('target', 'doPrint');
    });
    var printWindow = document.getElementById('doPrintId');
    printWindow.onload = function(){
        printWindow.focus();
        printWindow.contentWindow.print();
        document.body.remove(printWindow);
    };

    form.submit();
} else {
    form.submit();
}

jQuery(document.body).remove(form);

这篇关于在新窗口中打开PDF,打印PDF并关闭窗口。如何在javascript中执行此操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆