Javascript를 사용하여 인쇄 대화 상자를 어떻게 팝업합니까?


162

사용자를 프린터 친화적 인 페이지로 안내하는 "인쇄"링크가있는 페이지가 있습니다. 클라이언트는 사용자가 인쇄용 페이지에 도달하면 자동으로 인쇄 대화 상자가 나타나기를 원합니다. 자바 스크립트로 어떻게 할 수 있습니까?

답변:


245
window.print();  

맞춤형 팝업을 의미하지 않는 한.


5
조금 오래되었지만 추가하고 싶습니다 ... window.print (); setTimeout ( "window.close ()", 100); . 나머지 페이지가로드 될 때까지 충분한 시간이 걸리지 만 인쇄 대화 상자의 인쇄 단추를 누르거나 취소 할 때까지 중단 된 다음 탭을 깔끔하게 다시 종료합니다.
Stephen

38

당신은 할 수 있습니다

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

22

원하는 필드를 추가하고 그런 식으로 인쇄 할 수 있습니다.

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
이것은 나를위한 매력처럼 작동했습니다. 브라우저에서 팝업을 허용하는 데 필요합니다. 탭이 사라지지 않기 때문에 "닫기"가 실행되는지 확실하지 않습니다.
rich

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>

3

클릭 이벤트 핸들러가없는 링크 만있는 경우 :

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

0

단추에 연결하거나 페이지로드시 연결할 수 있습니다.

window.print();

0

이미 답변이 제공되었음을 알고 있습니다. 하지만 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
    }

도움이 되었기를 바랍니다 :)


-6

문제가있는 경우 :

 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;
    });

3
어쨌든 이것을 함께 연결하는 이유는 무엇입니까? '<scr'+ 'ipt> print () </ scr'+ 'ipt>'
CRice
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.