👨‍💻 프로그래밍/Javascript

[JavaScript] 특정 영역 내용 출력(인쇄/프린트)하기

톰아스 2024. 1. 31. 23:58
반응형

웹 개발자로서, 특정 <div> 태그의 내용을 빠르게 확인하고 디버깅하는 방법을 소개하려고 한다. 이 글에서는 간단하면서도 효과적인 Javascript 코드를 통해 어떻게 <div> 태그 내용을 출력할 수 있는지 알아 보겠다.

1. JavaScript Code

웹 페이지에서 특정 <Div> 태그의 내용을 출력하는 Javascript 코드입니다.

var contents;
var retBody;

function printWindow(div) {
    prtContent = document.getElementById(div);
    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
    window.print();
}

function beforePrint(){
    initBody = document.body.innerHTML;
    document.body.innerHTML = contents.innerHTML;
}

function afterPrint(){
    document.body.innerHTML = retBody;
}

필요에 따라 Jquery 및 SetProperties를 통해 프린트할 영역의 CSS를 변경하고 출력 이후 원상 복구할 수도 있다

2. HTML Code

웹 페이지 프린트 기능을 사용할 수 있는 Button 태그와 출력될 div 영역의 HTML 코드입니다.

<button onclick="printWindow(reportPrint)">Print/출력하기</button>
<div id="reportPrint">이 부분이 출력됨</div>
반응형