사용자를 프린터 친화적 인 페이지로 안내하는 "인쇄"링크가있는 페이지가 있습니다. 클라이언트는 사용자가 인쇄용 페이지에 도달하면 자동으로 인쇄 대화 상자가 나타나기를 원합니다. 자바 스크립트로 어떻게 할 수 있습니까?
사용자를 프린터 친화적 인 페이지로 안내하는 "인쇄"링크가있는 페이지가 있습니다. 클라이언트는 사용자가 인쇄용 페이지에 도달하면 자동으로 인쇄 대화 상자가 나타나기를 원합니다. 자바 스크립트로 어떻게 할 수 있습니까?
답변:
원하는 필드를 추가하고 그런 식으로 인쇄 할 수 있습니다.
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 #에서 자바 스크립트 함수 실행)을 수행하려면 IJSRuntime을 삽입해야합니다.
RAZOR 페이지에서 :
@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와 같은 호출을 기다리고 있기 때문입니다.
추신 : 예를 들어 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
}
도움이 되었기를 바랍니다 :)
문제가있는 경우 :
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;
});