개발/Web관련
웹 페이지 특정 element 인쇄 하기 예시
yunzema
2020. 7. 3. 15:04
반응형
QR코드 이미지를 전체화면으로 출력하는 예시
const html = document.querySelector('html');
//qr code가 담겨 있는 img dom element 객체로 resource 가져오기
const printContents = document.querySelector(`.qr-code-container`).childNodes[0];
const imgResource = printContents.toDataURL();
//출력할 img dom을 담을 container div 생성
const printDivContainer = document.createElement('div');
printDivContainer.style = `
width:100%; height: 100%;
display:flex; justify-content:center; align-items:center;
`;
//qr code를 담을 img element를 생성하여 container에 담기
const imgEl = document.createElement('img');
imgEl.style = `width:${QR_WIDTH}px; height:${QR_HEIGHT}px;`;
printDivContainer.appendChild(imgEl);
//img load가 비동기이므로 load된 후 print를 실행해야 한다.
imgEl.onload = () => {
//body 전체를 안보이도록 처리
document.body.style.display = 'none';
//html dom에 출력할 dom append
html.appendChild(printDivContainer);
//출력 함수 호출
window.print();
//출력 창 띄운 후 원래 페이지 상태로 복귀
document.body.style.display = 'block';
html.removeChild(printDivContainer);
};
//img element에 리소스 대입
imgEl.src = imgResource;