Javascript를 사용하여 인쇄 대화 상자를 팝업하려면 어떻게 해야 합니까?
사용자를 프린터에 적합한 페이지로 안내하는 "인쇄" 링크가 있는 페이지가 있습니다.클라이언트는 사용자가 인쇄하기 쉬운 페이지에 도착할 때 인쇄 대화 상자가 자동으로 나타나길 원합니다.자바스크립트로 이걸 어떻게 하나요?
window.print();
사용자 지정 팝업을 의미하지 않는 한.
할 수 있습니다
<body onload="window.print()">
...
</body>
원하는 필드를 추가하고 인쇄할 수 있도록 하는 것이 좋습니다.
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();
};
클릭 이벤트 핸들러가 없는 링크만 있는 경우:
<a href="javascript:window.print();">Print Page</a>
저는 그들이 가로를 인쇄하는 것을 기억할 수 있도록 하기 위해 이것을 합니다. 이것은 많은 프린터의 많은 페이지에 필요합니다.
<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>
단추나 페이지 로드 시 연결할 수 있습니다.
window.print();
이미 답변이 제공된 것으로 알고 있습니다.하지만 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");
}
이제 인덱스.html:
<script>
function printDocument() {
window.print();
}
</script>
주의할 점은 클릭 시 이벤트가 비동기식인 이유는 IJS 런타임이 InvoidAsync와 같은 호출을 대기하기 때문입니다.
PS: 예를 들어, snet 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
}
이것이 도움이 되길 바랍니다 :)
이것이 오래된 질문이라는 것을 알지만, 이 유사한 문제와 싸우고 난 후, 저는 인쇄 화면을 여는 방법을 알게 되었고, 새로운 탭을 열 필요도 없고 팝업을 활성화할 필요도 없습니다.
바라건대, 이것이 다른 누군가에게 도움이 되기를 바랍니다.
/*
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
});
});
};
<script>
const _print = () => {
window.print();
}
</script>
또는
<body onload="window.print();"></body>
다음 문서를 참조하십시오. https://developer.mozilla.org/en-US/docs/Web/API/Window/print
문제가 있는 경우:
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;
});
언급URL : https://stackoverflow.com/questions/242182/how-can-i-pop-up-a-print-dialog-box-using-javascript
'programing' 카테고리의 다른 글
도커에서 저장과 내보내기의 차이점은 무엇입니까? (0) | 2023.08.25 |
---|---|
Python에서 프록시와 함께 Selenium 웹 드라이버 실행 (0) | 2023.08.25 |
스레드 메시징 시스템 데이터베이스 스키마 설계 (0) | 2023.08.25 |
장치 픽셀 비율은 정확히 무엇입니까? (0) | 2023.08.25 |
Swift에서 SQLite 데이터베이스 액세스 (0) | 2023.08.25 |