ユーザーに印刷用ページに移動する「印刷」リンクのあるページがあります。クライアントは、ユーザーが印刷用ページに到達したときに印刷ダイアログボックスが自動的に表示されることを望んでいます。JavaScriptでこれを行うにはどうすればよいですか?
ユーザーに印刷用ページに移動する「印刷」リンクのあるページがあります。クライアントは、ユーザーが印刷用ページに到達したときに印刷ダイアログボックスが自動的に表示されることを望んでいます。JavaScriptでこれを行うにはどうすればよいですか?
回答:
私はこれが好きなので、好きなフィールドを追加してそのように印刷できます。
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();
};
答えはすでに提供されています。しかし、私はBlazorアプリ(かみそり)でこれを行うことについて詳しく説明したかっただけです...
JSInterop(C#からJavaScript関数を実行)を実行するには、IJSRuntimeを注入する必要があります。
あなたのかみそりのページで:
@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ネットコアのメッセージボックスにしたい場合:
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
}
お役に立てれば :)
問題がある場合:
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;
});