如何使用JavaScript弹出打印对话框?

194

我有一个带有“打印”链接的页面,该链接会将用户带到适合打印的页面。客户想要在用户到达打印友好页面时自动出现打印对话框。如何使用JavaScript实现此功能?

10个回答

288
window.print();  

除非你要一个自定义外观的弹出窗口。


8
有点老了,但我喜欢添加 ... window.print();setTimeout("window.close()", 100);。这个代码片段等待足够的时间以加载页面的其余部分,然后挂起直到在打印对话框上点击打印按钮或取消按钮,然后整洁地关闭标签页。 - Stephen

45

你可以这样做

<body onload="window.print()">
...
</body>

25

我喜欢这样,这样你可以添加任何字段,并以这种方式打印它。

function printPage() {
    var w = window.open();

    var headers =  $("#headers").html();
    var field= $("#field1").html();
    var field2= $("#field2").html();

    var html = "<!DOCTYPE HTML>";
    html += '<html lang="en-us">';
    html += '<head><style></style></head>';
    html += "<body>";

    //check to see if they are null so "undefined" doesnt print on the page. <br>s optional, just to give space
    if(headers != null) html += headers + "<br/><br/>";
    if(field != null) html += field + "<br/><br/>";
    if(field2 != null) html += field2 + "<br/><br/>";

    html += "</body>";
    w.document.write(html);
    w.window.print();
    w.document.close();
};

2
这对我来说非常有效。需要允许浏览器中的弹出窗口。我不确定“close”是否会被执行,因为选项卡从未消失。 - rich
它可以工作,但会打开一个新标签页。有没有办法防止这种情况发生? - Bellu

12

如果您只是有一个没有点击事件处理程序的链接:

<a href="javascript:window.print();">Print Page</a>

5
你可以将它绑定到按钮或页面的加载上。
window.print();

5

我这样做是为了确保他们记得打印横向页面,因为很多打印机需要这种方式来打印很多页面。

<a href="javascript:alert('Please be sure to set your printer to Landscape.');window.print();">Print Me...</a>

或者
<body onload="alert('Please be sure to set your printer to Landscape.');window.print();">
etc.
</body>

2

我知道答案已经被提供了,但是我想进一步阐述如何在Blazor应用程序(Razor)中执行此操作...

您需要注入IJSRuntime以执行JSInterop(从C#运行JavaScript函数)

在您的Razor页面中:

@inject IJSRuntime JSRuntime

一旦你完成注入,创建一个按钮并添加点击事件,该事件调用一个C#方法:

<MatFAB Icon="@MatIconNames.Print" OnClick="@(async () => await print())"></MatFAB>

(如果您不使用MatBlazor,可以选择更简单的东西)
或者更简单一些,如果您不使用MatBlazor。
<button @onclick="@(async () => await print())">PRINT</button>

对于C#方法:

public async Task print()
{
    await JSRuntime.InvokeVoidAsync("printDocument");
}

现在在您的 index.html 文件中:

<script>
    function printDocument() {
        window.print();
    }
</script>

需要注意的是,onclick事件是异步的原因是因为IJSRuntime等待它的调用,例如InvokeVoidAsync。

PS:例如,在asp net core中想要弹出消息框:

await JSRuntime.InvokeAsync<string>("alert", "Hello user, this is the message box");

要有一个确认消息框:
bool question = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to do this?");
    if(question == true)
    {
        //user clicked yes
    }
    else
    {
        //user clicked no
    }

希望这能帮到您 :)

1
这很有帮助,@James-Heffer,但是你甚至可以进一步简化它(仅针对打印部分),不需要创建自己的JavaScript方法printDocument,只需调用await JSRuntime.InvokeVoidAsync("print");并直接调用给定的方法即可。 - Grandizer
这种方法是否可以应用于ASP.NET MVC 5场景?我正在运行.NET 4.5。 - Axel Samyn

1

我知道这是一个老问题,但在解决了类似的问题后,我找到了一种打开打印屏幕的方法,而不必打开新标签页,也不必启用弹出窗口。

希望这能帮助其他人。

/*
    Example:
    <a href="//example.com" class="print-url">Print</a>
*/

//LISTEN FOR PRINT URL ITEMS TO BE CLICKED
$(document).off('click.PrintUrl').on('click.PrintUrl', '.print-url', function(e){

    //PREVENT OTHER CLICK EVENTS FROM PROPAGATING
    e.preventDefault();

    //TRY TO ASK THE URL TO TRIGGER A PRINT DIALOGUE BOX
    printUrl($(this).attr('href'));
});

//TRIGGER A PRINT DIALOGE BOX FROM A URL
function printUrl(url) {    

    //CREATE A HIDDEN IFRAME AND APPEND IT TO THE BODY THEN WAIT FOR IT TO LOAD
    $('<iframe src="'+url+'"></iframe>').hide().appendTo('body').on('load', function(){
        
        var oldTitle    = $(document).attr('title');                //GET THE ORIGINAL DOCUMENT TITLE
        var that        = $(this);                                  //STORE THIS IFRAME AS A VARIABLE           
        var title       = $(that).contents().find('title').text();  //GET THE IFRAME TITLE
        $(that).focus();                                            //CALL THE IFRAME INTO FOCUS (FOR OLDER BROWSERS)   

        //SET THE DOCUMENT TITLE FROM THE IFRAME (THIS NAMES THE DOWNLOADED FILE)
        if(title && title.length) $(document).attr('title', title);
        
        //TRIGGER THE IFRAME TO CALL THE PRINT
        $(that)[0].contentWindow.print();

        //LISTEN FOR THE PRINT DIALOGUE BOX TO CLOSE
        $(window).off('focus.PrintUrl').on('focus.PrintUrl', function(e){
            e.stopPropagation();                                            //PREVENT OTHER WINDOW FOCUS EVENTS FROM RUNNING            
            $(that).remove();                                               //GET RID OF THE IFRAME
            if(title && title.length) $(document).attr('title', oldTitle);  //RESET THE PAGE TITLE
            $(window).off('focus.PrintUrl');                                //STOP LISTENING FOR WINDOW FOCUS
        });
    });    
};

文档非常好!A+ - Paul - Soura Tech LLC

1

-7

如果有问题:

 mywindow.print();

使用替代方案:

'<scr'+'ipt>print()</scr'+'ipt>'

全文:

 $('.print-ticket').click(function(){

        var body = $('body').html();
        var ticket_area = '<aside class="widget tickets">' + $('.widget.tickets').html() + '</aside>';

        $('body').html(ticket_area);
        var print_html = '<html lang="tr">' + $('html').html() + '<scr'+'ipt>print()</scr'+'ipt>' + '</html>'; 
        $('body').html(body);

        var mywindow = window.open('', 'my div', 'height=600,width=800');
        mywindow.document.write(print_html);
        mywindow.document.close(); // necessary for IE >= 10'</html>'
        mywindow.focus(); // necessary for IE >= 10
        //mywindow.print();
        mywindow.close();

        return true;
    });

6
你为什么要把这些连接在一起呢? '<scr'+'ipt>print()</scr'+'ipt>' - CRice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接