본문 바로가기
💻CODING/javascript

[js] 자바스크립트로 선택영역 프린트하기(ft. window.print)

by 코딩하는 갓디노 2021. 6. 28.

자바스크립트로 선택영역 프린트

 

자바스크립트로  dom을 제어하여
선택한 부분을 프린트 합니다. 

 

구현 내용

버튼 클릭시 프린트 기능 연결
선택 영역을 설정하여 그 부분만 프린트하도록 설정

 

 선택 영역 프린트 하기

  • window.print() 메소드는 보이는 화면을 그대로 프린트 하게 합니다.
  • 여기서  선택 영역(printSection)만 <div> 태그 요소를 새로 생성하며 그 안에 넣어주고, 이 부분만 window.print() 를 설정합니다.
  • 화면은 display none 과  block 을 이용하며 출력합니다.  
const onPrintFn = () => {
  const html = document.querySelector('html');
  const printSection = document.querySelector('.main-contents').innerHTML; //프린트 영역
  const printDiv = document.createElement("DIV");
  html.appendChild(printDiv);
  printDiv.innerHTML = printSection; //printDiv에 프린트 영역 내용을 담아줌
  document.body.style.display = 'none'; //전체 hide
  window.print(); //printDiv를 프린트
  document.body.style.display = 'block'; //프린트 후 전체 show
  printDiv.style.display = 'none'; // printDiv hide
}
반응형

댓글