我有一个带有“打印”链接的页面,可以将用户带到打印机友好页面。客户希望在用户到达打印页面时自动显示打印对话框。我怎么能用javascript做到这一点?
答案 0 :(得分:202)
window.print();
除非你的意思是自定义弹出窗口。
答案 1 :(得分:35)
你可以做到
<body onload="window.print()">
...
</body>
答案 2 :(得分:18)
我喜欢这样,所以你可以添加你想要的任何字段并以这种方式打印。
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();
};
答案 3 :(得分: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>
答案 4 :(得分:1)
如果您只有一个没有click事件处理程序的链接:
<a href="javascript:window.print;">Print Page</a>
答案 5 :(得分:0)
您可以将其绑定到按钮或加载页面。
window.print();
答案 6 :(得分:0)
我知道已经提供了答案。但是我只是想详细说明在Blazor应用程序(剃刀)中执行此操作的过程...
您需要注入IJSRuntime才能执行JSInterop(从C#运行javascript函数)
在您的剃刀页中:
@inject IJSRuntime JSRuntime
一旦注入,就创建一个带有单击事件的按钮,该事件调用C#方法:
<MatFAB Icon="@MatIconNames.Print" OnClick="@(async () => await print())"></MatFAB>
(或者,如果您不使用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
}
希望这会有所帮助:)
答案 7 :(得分:-6)
如果问题:
mywindow.print();
使用altenative:
'<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;
});